source
stringlengths
3
86
python
stringlengths
75
1.04M
bmv2stf.py
#!/usr/bin/env python # 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 BMv2 behavioral model simulator with input from an stf file from __future__ import print_function from subprocess import Popen from threading import Thread from glob import glob import json import sys import re import os import stat import tempfile import shutil import difflib import subprocess import signal import time import random import errno import socket from string import maketrans from collections import OrderedDict try: from scapy.layers.all import * from scapy.utils import * except ImportError: pass SUCCESS = 0 FAILURE = 1 class TimeoutException(Exception): pass def signal_handler(signum, frame): raise TimeoutException, "Timed out!" signal.signal(signal.SIGALRM, signal_handler) class Options(object): def __init__(self): self.binary = None self.verbose = False self.preserveTmp = False self.observationLog = None def nextWord(text, sep = None): # Split a text at the indicated separator. # Note that the separator can be a string. # Separator is discarded. spl = text.split(sep, 1) if len(spl) == 0: return '', '' elif len(spl) == 1: return spl[0].strip(), '' else: return spl[0].strip(), spl[1].strip() def ByteToHex(byteStr): return ''.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip() def HexToByte(hexStr): bytes = [] hexStr = ''.join( hexStr.split(" ") ) for i in range(0, len(hexStr), 2): bytes.append( chr( int (hexStr[i:i+2], 16 ) ) ) return ''.join( bytes ) def reportError(*message): print("***", *message) class Local(object): # object to hold local vars accessable to nested functions pass def FindExe(dirname, exe): dir = os.getcwd() while len(dir) > 1: if os.path.isdir(os.path.join(dir, dirname)): rv = None rv_time = 0 for dName, sdName, fList in os.walk(os.path.join(dir, dirname)): if exe in fList: n=os.path.join(dName, exe) if os.path.isfile(n) and os.access(n, os.X_OK): n_time = os.path.getmtime(n) if n_time > rv_time: rv = n rv_time = n_time if rv is not None: return rv dir = os.path.dirname(dir) return exe def run_timeout(options, args, timeout, stderr): if options.verbose: print("Executing ", " ".join(args)) local = Local() local.process = None def target(): procstderr = None if stderr is not None: procstderr = open(stderr, "w") local.process = Popen(args, stderr=procstderr) local.process.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 reportError("Process failed to start") return -1 if options.verbose: print("Exit code ", local.process.returncode) return local.process.returncode timeout = 10 * 60 class ConcurrentInteger(object): # Generates exclusive integers in a range 0-max # in a way which is safe across multiple processes. # It uses a simple form of locking using folder names. # This is necessary because this script may be invoked # concurrently many times by make, and we need the many simulator instances # to use different port numbers. def __init__(self, folder, max): self.folder = folder self.max = max def lockName(self, value): return "lock_" + str(value) def release(self, value): os.rmdir(self.lockName(value)) def generate(self): # try 10 times for i in range(0, 10): index = random.randint(0, self.max) file = self.lockName(index) try: os.makedirs(file) return index except: time.sleep(1) continue return None class BMV2ActionArg(object): def __init__(self, name, width): # assert isinstance(name, str) # assert isinstance(width, int) self.name = name self.width = width class TableKey(object): def __init__(self): self.fields = OrderedDict() def append(self, name, type): self.fields[name] = type class TableKeyInstance(object): def __init__(self, tableKey): assert isinstance(tableKey, TableKey) self.values = {} self.key = tableKey for f,t in tableKey.fields.iteritems(): if t == "ternary": self.values[f] = "0&&&0" elif t == "lpm": self.values[f] = "0/0" elif t == "exact": self.values[f] = "0" elif t == "valid": self.values[f] = "0" else: raise Exception("Unexpected key type " + t) def set(self, key, value): array = re.compile("(.*)\$([0-9]+)(.*)"); m = array.match(key) if m: key = m.group(1) + "[" + m.group(2) + "]" + m.group(3) found = False if key in self.key.fields: found = True elif key + '$' in self.key.fields: key = key + '$' found = True elif key + '.$valid$' in self.key.fields: key = key + '.$valid$' found = True elif key.endswith(".valid"): alt = key[:-5] + "$valid$" if alt in self.key.fields: key = alt found = True if not found: for i in self.key.fields: if i.endswith("." + key) or i.endswith("." + key + "$"): key = i found = True elif key == "valid" and i.endswith(".$valid$"): key = i found = True if not found and key == "valid" and "$valid$" in self.key.fields: key = "$valid$" found = True if not found: raise Exception("Unexpected key field " + key) if self.key.fields[key] == "ternary": self.values[key] = self.makeMask(value) elif self.key.fields[key] == "lpm": self.values[key] = self.makeLpm(value) else: self.values[key] = value def makeMask(self, value): # TODO -- we really need to know the size of the key to make the mask properly, # but to find that, we need to parse the headers and header_types from the json if value.startswith("0x"): mask = "F" value = value[2:] prefix = "0x" elif value.startswith("0b"): mask = "1" value = value[2:] prefix = "0b" elif value.startswith("0o"): mask = "7" value = value[2:] prefix = "0o" else: raise Exception("Decimal value "+value+" not supported for ternary key") return value values = "0123456789abcdefABCDEF*" replacements = (mask * 22) + "0" trans = maketrans(values, replacements) m = value.translate(trans) return prefix + value.replace("*", "0") + "&&&" + prefix + m def makeLpm(self, value): if value.find('/') >= 0: return value if value.startswith("0x"): bits_per_digit = 4 elif value.startswith("0b"): bits_per_digit = 1 elif value.startswith("0o"): bits_per_digit = 3 else: value = "0x" + hex(int(value)) bits_per_digit = 4 digits = len(value) - 2 - value.count('*') return value.replace('*', '0') + "/" + str(digits*bits_per_digit) def __str__(self): result = "" for f in self.key.fields: if result != "": result += " " result += self.values[f] return result class BMV2ActionArguments(object): def __init__(self, action): assert isinstance(action, BMV2Action) self.action = action self.values = {} def set(self, key, value): found = False for i in self.action.args: if key == i.name: found = True if not found: raise Exception("Unexpected action arg " + key) self.values[key] = value def __str__(self): result = "" for f in self.action.args: if result != "": result += " " result += self.values[f.name] return result def size(self): return len(self.action.args) class BMV2Action(object): def __init__(self, jsonAction): self.name = jsonAction["name"] self.args = [] for a in jsonAction["runtime_data"]: arg = BMV2ActionArg(a["name"], a["bitwidth"]) self.args.append(arg) def __str__(self): return self.name def makeArgsInstance(self): return BMV2ActionArguments(self) class BMV2Table(object): def __init__(self, jsonTable): self.match_type = jsonTable["match_type"] self.name = jsonTable["name"] self.key = TableKey() self.actions = {} for k in jsonTable["key"]: name = k["target"] if isinstance(name, list): name = "" for t in k["target"]: if name != "": name += "." name += t self.key.append(name, k["match_type"]) actions = jsonTable["actions"] action_ids = jsonTable["action_ids"] for i in range(0, len(actions)): actionName = actions[i] actionId = action_ids[i] self.actions[actionName] = actionId def __str__(self): return self.name def makeKeyInstance(self): return TableKeyInstance(self.key) # Represents enough about the program executed to be # able to invoke the BMV2 simulator, create a CLI file # and test packets in pcap files. class RunBMV2(object): def __init__(self, folder, options, jsonfile): self.clifile = folder + "/cli.txt" self.jsonfile = jsonfile self.stffile = None self.folder = folder self.pcapPrefix = "pcap" self.interfaces = {} self.expected = {} # for each interface number of packets expected self.expectedAny = [] # interface on which any number of packets is fine self.packetDelay = 0 self.options = options self.json = None self.tables = [] self.actions = [] self.switchLogFile = "switch.log" # .txt is added by BMv2 self.readJson() def readJson(self): with open(self.jsonfile) as jf: self.json = json.load(jf) for a in self.json["actions"]: self.actions.append(BMV2Action(a)) for t in self.json["pipelines"][0]["tables"]: self.tables.append(BMV2Table(t)) for t in self.json["pipelines"][1]["tables"]: self.tables.append(BMV2Table(t)) def filename(self, interface, direction): return self.folder + "/" + self.pcapPrefix + str(interface) + "_" + direction + ".pcap" def interface_of_filename(self, f): return int(os.path.basename(f).rstrip('.pcap').lstrip(self.pcapPrefix).rsplit('_', 1)[0]) def do_cli_command(self, cmd): if self.options.verbose: print(cmd) self.cli_stdin.write(cmd + "\n") self.cli_stdin.flush() self.packetDelay = 1 def do_command(self, cmd): if self.options.verbose: print("STF Command:", cmd) first, cmd = nextWord(cmd) if first == "": pass elif first == "add": self.do_cli_command(self.parse_table_add(cmd)) elif first == "setdefault": self.do_cli_command(self.parse_table_set_default(cmd)) elif first == "packet": interface, data = nextWord(cmd) interface = int(interface) data = ''.join(data.split()) time.sleep(self.packetDelay) try: self.interfaces[interface]._write_packet(HexToByte(data)) except ValueError: reportError("Invalid packet data", data) return FAILURE self.interfaces[interface].flush() self.packetDelay = 0 elif first == "expect": interface, data = nextWord(cmd) interface = int(interface) data = ''.join(data.split()) if data != '': self.expected.setdefault(interface, []).append(data) else: self.expectedAny.append(interface) else: if self.options.verbose: print("ignoring stf command:", first, cmd) def parse_table_set_default(self, cmd): tableName, cmd = nextWord(cmd) table = self.tableByName(tableName) actionName, cmd = nextWord(cmd, "(") action = self.actionByName(table, actionName) actionArgs = action.makeArgsInstance() cmd = cmd.strip(")") while cmd != "": word, cmd = nextWord(cmd, ",") k, v = nextWord(word, ":") actionArgs.set(k, v) command = "table_set_default " + tableName + " " + actionName if actionArgs.size(): command += " => " + str(actionArgs) return command def parse_table_add(self, cmd): tableName, cmd = nextWord(cmd) table = self.tableByName(tableName) key = table.makeKeyInstance() actionArgs = None actionName = None prio, cmd = nextWord(cmd) number = re.compile("[0-9]+") if not number.match(prio): # not a priority; push back cmd = prio + " " + cmd prio = "" while cmd != "": if actionName != None: # parsing action arguments word, cmd = nextWord(cmd, ",") k, v = nextWord(word, ":") actionArgs.set(k, v) else: # parsing table key word, cmd = nextWord(cmd) if cmd.find("=") >= 0: # This command retrieves a handle for the key # This feature is currently not supported, so we just ignore the handle part cmd = cmd.split("=")[0] if word.find("(") >= 0: # found action actionName, arg = nextWord(word, "(") action = self.actionByName(table, actionName) actionArgs = action.makeArgsInstance() cmd = arg + cmd cmd = cmd.strip("()") else: k, v = nextWord(word, ":") key.set(k, v) if prio != "": # Priorities in BMV2 seem to be reversed with respect to the stf file # Hopefully 10000 is large enough prio = str(10000 - int(prio)) command = "table_add " + table.name + " " + action.name + " " + str(key) + " => " + str(actionArgs) if table.match_type == "ternary": command += " " + prio return command def actionByName(self, table, actionName): for name, id in table.actions.items(): action = self.actions[id] if action.name == actionName: return action # Try again with suffixes candidate = None for name, id in table.actions.items(): action = self.actions[id] if action.name.endswith(actionName): if candidate is None: candidate = action else: raise Exception("Ambiguous action name " + actionName + " in " + table.name) if candidate is not None: return candidate raise Exception("No action", actionName, "in table", table) def tableByName(self, tableName): originalName = tableName for t in self.tables: if t.name == tableName: return t # If we can't find that try to match the tableName with a table suffix candidate = None for t in self.tables: if t.name.endswith(tableName): if candidate == None: candidate = t else: raise Exception("Table name " + tableName + " is ambiguous between " + candidate.name + " and " + t.name) if candidate is not None: return candidate raise Exception("Could not find table " + tableName) def interfaceArgs(self): # return list of interface names suitable for bmv2 result = [] for interface in sorted(self.interfaces): result.append("-i " + str(interface) + "@" + self.pcapPrefix + str(interface)) return result def generate_model_inputs(self, stffile): self.stffile = stffile with open(stffile) as i: for line in i: line, comment = nextWord(line, "#") first, cmd = nextWord(line) if first == "packet" or first == "expect": interface, cmd = nextWord(cmd) interface = int(interface) if not interface in self.interfaces: # Can't open the interfaces yet, as that would block ifname = self.interfaces[interface] = self.filename(interface, "in") os.mkfifo(ifname) return SUCCESS def check_switch_server_ready(self, proc, thriftPort): """While the process is running, we check if the Thrift server has been started. If the Thrift server is ready, we assume that the switch was started successfully. This is only reliable if the Thrift server is started at the end of the init process""" while True: if proc.poll() is not None: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(0.5) result = sock.connect_ex(("localhost", thriftPort)) if result == 0: return True def run(self): if self.options.verbose: print("Running model") wait = 0 # Time to wait before model starts running concurrent = ConcurrentInteger(os.getcwd(), 1000) rand = concurrent.generate() if rand is None: reportError("Could not find a free port for Thrift") return FAILURE thriftPort = str(9090 + rand) rv = SUCCESS try: os.remove("/tmp/bmv2-%d-notifications.ipc" % rand) except OSError: pass try: runswitch = [FindExe("behavioral-model", "simple_switch"), "--log-file", self.switchLogFile, "--log-flush", "--use-files", str(wait), "--thrift-port", thriftPort, "--device-id", str(rand)] + self.interfaceArgs() + ["../" + self.jsonfile] if self.options.verbose: print("Running", " ".join(runswitch)) sw = subprocess.Popen(runswitch, cwd=self.folder) def openInterface(ifname): fp = self.interfaces[interface] = RawPcapWriter(ifname, linktype=0) fp._write_header(None) # Try to open input interfaces. Each time, we set a 2 second # timeout. If the timeout expires we check if the bmv2 process is # not running anymore. If it is, we check if we have exceeded the # one minute timeout (exceeding this timeout is very unlikely and # could mean the system is very slow for some reason). If one of the # 2 conditions above is met, the test is considered a FAILURE. start = time.time() sw_timeout = 60 # open input interfaces # DANGER -- it is critical that we open these fifos in the same # order as bmv2, as otherwise we'll deadlock. Would be nice if we # could open nonblocking. for interface in sorted(self.interfaces): ifname = self.interfaces[interface] while True: try: signal.alarm(2) openInterface(ifname) signal.alarm(0) except TimeoutException: if time.time() - start > sw_timeout: return FAILURE if sw.poll() is not None: return FAILURE else: break # at this point we wait until the Thrift server is ready # also useful if there are no interfaces try: signal.alarm(int(sw_timeout + start - time.time())) self.check_switch_server_ready(sw, int(thriftPort)) signal.alarm(0) except TimeoutException: return FAILURE time.sleep(0.1) runcli = [FindExe("behavioral-model", "simple_switch_CLI"), "--thrift-port", thriftPort] if self.options.verbose: print("Running", " ".join(runcli)) try: cli = subprocess.Popen(runcli, cwd=self.folder, stdin=subprocess.PIPE) self.cli_stdin = cli.stdin with open(self.stffile) as i: for line in i: line, comment = nextWord(line, "#") self.do_command(line) cli.stdin.close() for interface, fp in self.interfaces.iteritems(): fp.close() # Give time to the model to execute time.sleep(2) cli.terminate() sw.terminate() sw.wait() except Exception as e: cli.terminate() sw.terminate() sw.wait() raise e # This only works on Unix: negative returncode is # minus the signal number that killed the process. if sw.returncode != 0 and sw.returncode != -15: # 15 is SIGTERM reportError("simple_switch died with return code", sw.returncode); rv = FAILURE elif self.options.verbose: print("simple_switch exit code", sw.returncode) cli.wait() if cli.returncode != 0 and cli.returncode != -15: reportError("CLI process failed with exit code", cli.returncode) rv = FAILURE finally: try: os.remove("/tmp/bmv2-%d-notifications.ipc" % rand) except OSError: pass concurrent.release(rand) if self.options.verbose: print("Execution completed") return rv def comparePacket(self, expected, received): received = ''.join(ByteToHex(str(received)).split()).upper() expected = ''.join(expected.split()).upper() if len(received) < len(expected): reportError("Received packet too short", len(received), "vs", len(expected)) return FAILURE for i in range(0, len(expected)): if expected[i] == "*": continue; if expected[i] != received[i]: reportError("Received packet ", received) reportError("Packet different at position", i, ": expected", expected[i], ", received", received[i]) reportError("Full received packed is ", received) return FAILURE return SUCCESS def showLog(self): with open(self.folder + "/" + self.switchLogFile + ".txt") as a: log = a.read() print("Log file:") print(log) def checkOutputs(self): if self.options.verbose: print("Comparing outputs") direction = "out" for file in glob(self.filename('*', direction)): interface = self.interface_of_filename(file) if os.stat(file).st_size == 0: packets = [] else: try: packets = rdpcap(file) except: reportError("Corrupt pcap file", file) self.showLog() return FAILURE # Log packets. if self.options.observationLog: observationLog = open(self.options.observationLog, 'w') for pkt in packets: observationLog.write('%d %s\n' % ( interface, ''.join(ByteToHex(str(pkt)).split()).upper())) observationLog.close() # Check for expected packets. if interface in self.expectedAny: if interface in self.expected: reportError("Interface " + interface + " has both expected with packets and without") continue if interface not in self.expected: expected = [] else: expected = self.expected[interface] if len(expected) != len(packets): reportError("Expected", len(expected), "packets on port", str(interface), "got", len(packets)) self.showLog() return FAILURE for i in range(0, len(expected)): cmp = self.comparePacket(expected[i], packets[i]) if cmp != SUCCESS: reportError("Packet", i, "on port", str(interface), "differs") return FAILURE # remove successfully checked interfaces if interface in self.expected: del self.expected[interface] if len(self.expected) != 0: # didn't find all the expects we were expecting reportError("Expected packects on ports", self.expected.keys(), "not received") return FAILURE else: return SUCCESS def run_model(options, tmpdir, jsonfile, testfile): bmv2 = RunBMV2(tmpdir, options, jsonfile) result = bmv2.generate_model_inputs(testfile) if result != SUCCESS: return result result = bmv2.run() if result != SUCCESS: return result result = bmv2.checkOutputs() return result ######################### main def usage(options): print("usage:", options.binary, "[-v] [-observation-log <file>] <json file> <stf file>"); def main(argv): options = Options() options.binary = argv[0] argv = argv[1:] while len(argv) > 0 and argv[0][0] == '-': if argv[0] == "-b": options.preserveTmp = True elif argv[0] == "-v": options.verbose = True elif argv[0] == '-observation-log': if len(argv) == 1: reportError("Missing argument", argv[0]) usage(options) sys.exit(1) options.observationLog = argv[1] argv = argv[1:] else: reportError("Unknown option ", argv[0]) usage(options) argv = argv[1:] if len(argv) < 2: usage(options) return FAILURE if not os.path.isfile(argv[0]) or not os.path.isfile(argv[1]): usage(options) return FAILURE tmpdir = tempfile.mkdtemp(dir=".") result = run_model(options, tmpdir, argv[0], argv[1]) if options.preserveTmp: print("preserving", tmpdir) else: shutil.rmtree(tmpdir) if options.verbose: if result == SUCCESS: print("SUCCESS") else: print("FAILURE", result) return result if __name__ == "__main__": sys.exit(main(sys.argv))
tommy.py
#!/usr/bin/python # -*- coding: UTF-8 -*- from os import system, name import itertools import threading import time import sys import datetime from base64 import b64decode,b64encode from datetime import date expirydate = datetime.date(2022, 1, 12 ) #expirydate = datetime.date(2021, 12, 30) today=date.today() def hero(): def chalo(): done = False #here is the animation def animate(): for c in itertools.cycle(['|', '/', '-', '\\']) : if done: break sys.stdout.write('\rconnecting to server for next colour--------- ' + c) sys.stdout.flush() time.sleep(0.1) sys.stdout.write('\rDone! ') t = threading.Thread(target=animate) t.start() #long process here time.sleep(20) done = True def chalo1(): done = False #here is the animation def animate(): for c in itertools.cycle(['|', '/', '-', '\\']): if done: break sys.stdout.write('\rgetting the colour wait --------- ' + c) sys.stdout.flush() time.sleep(0.1) sys.stdout.write('\rDone! ') t = threading.Thread(target=animate) t.start() #long process here time.sleep(20) done = True def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') a_type=set.selectbox("Type",["LR","DT","ADABOOST [Recommended]","SVM"]) #st.write("The shape is ",d.shape) #cl=st.selectbox("Select the number of clusters",[2,3,4,5,6,7,8,9,10]) st.write("This is Version 1") g,r=0,0 p=-1 j=1 rr=st.radio("Select the cell",("1","2","3","4")) if a_type=="LR": if rr=="1": st.write("hello") if rr=="2": a=st.number_input("Enter the Last fist color",value=1,step=1) b=st.number_input("Enter the Last second",value=1,step=1) c=st.number_input("Enter the last third color",value=1,step=1) e=st.number_input("Enter the last fourth color",value=1,step=1) f=st.number_input("Enter the last fifth color",value=1,step=1) if st.button("Predict 2nd"): with st.spinner('In Progress.....'): d=pd.read_excel("rd6.xlsx") #clf = svm.SVC(kernel="") #clf = DecisionTreeClassifier(random_state=0) X=d[['A','B','C','D','E']] y=d['Y'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.001) #st.write("The shape is ",d.shape) clf = LogisticRegression(random_state=0).fit(X, y) #st.write("You selected ",s_type) p=clf.predict([[a,b,c,e,f]]) if p%2==0: #r=r+1 st.success("Next is GREEN") elif p%2==1: #g=g+1 st.error("Next is RED") if rr== "3": a=st.number_input("Enter the Last fist color",value=1,step=1) b=st.number_input("Enter the Last second",value=1,step=1) if st.button("Predict 3rd"): with st.spinner('In Progress....'): d=pd.read_excel("rd3.xlsx") #clf = svm.SVC(kernel="") #clf = DecisionTreeClassifier(random_state=0) X=d[['A','B']] y=d['Y'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.001) #st.write("The shape is ",d.shape) clf = LogisticRegression(random_state=0).fit(X, y) #st.write("You selected ",s_type) p=clf.predict([[a,b]]) if p%2==0: #r=r+1 st.success("Next is GREEN") elif p%2==1: #g=g+1 st.error("Next is RED") if rr=="4": a=st.number_input("Enter the Last fist color",value=1,step=1) b=st.number_input("Enter the Last second",value=1,step=1) c=st.number_input("Enter the last third color",value=1,step=1) if st.button("Predict 4th"): with st.spinner('In Progress..'): d=pd.read_excel("rd4.xlsx") #clf = svm.SVC(kernel="") #clf = DecisionTreeClassifier(random_state=0) X=d[['A','B','C']] y=d['Y'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.001) #st.write("The shape is ",d.shape) clf = LogisticRegression(random_state=0).fit(X, y) #st.write("You selected ",s_type) p=clf.predict([[a,b,c]]) if p%2==0: #r=r+1 st.success("Next is GREEN") elif p%2==1: #g=g+1 st.error("Next is RED") #if g>r: #st.success("Next is GREEN - {} %".format((g/5)*100)) #else: #st.error("Next is RED - {} %".format((r/5)*100)) elif a_type=="ADABOOST [Recommended]": a=st.number_input("Enter the Last Period last digit",value=1,step=1) b=st.number_input("Enter the Last Price last digit",value=1,step=1) with st.spinner('In Progress...'): d=pd.read_excel("Emerd_n.xlsx") clf = DecisionTreeClassifier(random_state=0) X=d[['A','B','C']] y=d['Y'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.001) #st.write("The shape is ",d.shape) abc = AdaBoostClassifier(n_estimators=100,learning_rate=3,base_estimator=clf) # Train Adaboost Classifer model = abc.fit(X_train, y_train) #Predict the response for test dataset y_pred = model.predict([[a,b,a+1]]) p=y_pred[0] if p==0: #r=r+1 st.error("Next is RED") elif p==1: #g=g+1 st.success("Next is GREEN") #if g>r: #st.success("Next is GREEN - {} %".format((g/5)*100)) #else: #st.error("Next is RED - {} %".format((r/5)*100)) elif a_type=="SVM": if st.button("Classify"): a=st.number_input("Enter the Last Period last digit",value=1,step=1) b=st.number_input("Enter the Last Price last digit",value=1,step=1) with st.spinner('In Progress...'): d=pd.read_excel("Emerd_n.xlsx") clf = svm.SVC(kernel="") #clf = DecisionTreeClassifier(random_state=0) X=d[['A','B','C']] y=d['Y'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.001) #st.write("The shape is ",d.shape) clf.fit(X_train,y_train) #st.write("You selected ",s_type) p=clf.predict([[a,b,a+1]]) if p==0: #r=r+1 st.error("Next is RED") elif p==1: #g=g+1 st.success("Next is GREEN") #if g>r: #st.success("Next is GREEN - {} %".format((g/5)*100)) #else: #st.error("Next is RED - {} %".format((r/5)*100)) elif a_type=="DT": a=st.number_input("Enter the Last Period last digit",value=2,step=1) b=st.number_input("Enter the Last Price last digit",value=2,step=1) if st.button("Classify"): with st.spinner('In Progress...'): d=pd.read_excel("Emerd_n.xlsx") #clf = svm.SVC() clf = DecisionTreeClassifier(random_state=0) X=d[['A','B','C']] y=d['Y'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.001) #st.write("The shape is ",d.shape) clf.fit(X,y) #st.write("You selected ",s_type) p=clf.predict([[a,b,a+1]]) if p==1: #r=r+1 st.error("Next is RED") elif p==0: #g=g+1 st.success("Next is GREEN") #if g>r: #st.success("Next is GREEN - {} %".format((g/5)*100)) #else: #st.error("Next is RED - {} %".format((r/5)*100))
cache_server.py
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import SocketServer from contextlib import contextmanager from multiprocessing import Process, Queue from six.moves import SimpleHTTPServer from pants.util.contextutil import pushd, temporary_dir from pants.util.dirutil import safe_mkdir from pants_test.testutils.file_test_util import exact_files # A very trivial server that serves files under the cwd. class SimpleRESTHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def __init__(self, request, client_address, server): # The base class implements GET and HEAD. # Old-style class, so we must invoke __init__ this way. SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, request, client_address, server) def do_HEAD(self): return SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD(self) def do_PUT(self): path = self.translate_path(self.path) content_length = int(self.headers.getheader('content-length')) content = self.rfile.read(content_length) safe_mkdir(os.path.dirname(path)) with open(path, 'wb') as outfile: outfile.write(content) self.send_response(200) self.end_headers() def do_DELETE(self): path = self.translate_path(self.path) if os.path.exists(path): os.unlink(path) self.send_response(200) else: self.send_error(404, 'File not found') self.end_headers() class FailRESTHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): """Reject all requests""" def __init__(self, request, client_address, server): # Old-style class, so we must invoke __init__ this way. SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, request, client_address, server) def _return_failed(self): self.send_response(401, 'Forced test failure') self.end_headers() def do_HEAD(self): return self._return_failed() def do_GET(self): return self._return_failed() def do_PUT(self): return self._return_failed() def do_DELETE(self): return self._return_failed() class TestCacheServer(object): """A wrapper class that represents the underlying REST server. To create a TestCacheServer, use the `cache_server` factory function. """ def __init__(self, url, cache_root): self.url = url self._cache_root = cache_root def corrupt_artifacts(self, pattern): """Corrupts any artifacts matching the given pattern. Returns the number of files affected. """ regex = re.compile(pattern) count = 0 for f in exact_files(self._cache_root, ignore_links=True): if not regex.match(f): continue # Truncate the file. abspath = os.path.join(self._cache_root, f) artifact_size = os.path.getsize(abspath) with open(abspath, 'r+w') as outfile: outfile.truncate(artifact_size // 2) count += 1 return count def _cache_server_process(queue, return_failed, cache_root): """A pickleable top-level function to wrap a SimpleRESTHandler. We fork a separate process to avoid affecting the `cwd` of the requesting process. """ httpd = None try: with temporary_dir() as tmpdir: cache_root = cache_root if cache_root else tmpdir with pushd(cache_root): # SimpleRESTHandler serves from the cwd. if return_failed: handler = FailRESTHandler else: handler = SimpleRESTHandler httpd = SocketServer.TCPServer(('localhost', 0), handler) port = httpd.server_address[1] queue.put(port) httpd.serve_forever() finally: if httpd: httpd.shutdown() @contextmanager def cache_server(return_failed=False, cache_root=None): """A context manager which launches a temporary cache server on a random port. Yields a TestCacheServer to represent the running server. """ queue = Queue() process = Process(target=_cache_server_process, args=(queue,return_failed, cache_root)) process.start() try: port = queue.get() yield TestCacheServer('http://localhost:{0}'.format(port), cache_root) finally: process.terminate()
etcd_rendezvous.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import datetime import json import logging import random import sys import threading import time from base64 import b64decode, b64encode from typing import Optional import etcd # type: ignore[import] # pyre-ignore[21]: Could not find name `Store` in `torch.distributed`. from torch.distributed import Store from torch.distributed.elastic.rendezvous import ( RendezvousClosedError, RendezvousError, RendezvousHandler, RendezvousParameters, RendezvousTimeoutError, ) from .utils import _parse_rendezvous_endpoint _log_fmt = logging.Formatter("%(levelname)s %(asctime)s %(message)s") _log_handler = logging.StreamHandler(sys.stderr) _log_handler.setFormatter(_log_fmt) log = logging.getLogger(__name__) log.propagate = False log.setLevel(logging.INFO) log.addHandler(_log_handler) # Retryable failure exception means the we were too late to make # a desired state transition (e.g. because of a race condition), # and should now restart from the beginning. # A small delay is recommended to avoid spamming Etcd. class EtcdRendezvousRetryableFailure(Exception): pass # Similar to retryable failure, but the new state we observed suggests we # can re-try immediately, i.e. without a need for "safety delay". class EtcdRendezvousRetryImmediately(Exception): pass # Default timeout for the rendezvous. _DEFAULT_TIMEOUT: int = 600 # 10 minutes # Additional waiting time after reaching the minimum number of nodes # in case the rendezvous is elastic (min != max). _DEFAULT_LAST_CALL_TIMEOUT: int = 30 # 30 seconds # Various constants used internally in EtcdRendezvous CONST_ETCD_SETUP_TTL = 5 CONST_ETCD_FROZEN_TTL = 10 CONST_ETCD_JOINABLE_EPHEMERAL_TTL = 10 # Ephemeral node TTL for worker's keep-alive key: CONST_WORKER_KEEPALIVE_TTL = 10 # TTL for the ephemeral run_id-specific directory. All rendezvous state data # for a specific run_id (job instance) is contained within directory. # Its only role is to clean-up rendezvous data from old runs (for the case when # etcd server is persistent), and has no affect on correctnes, but should be # larger than any timeouts that a worker process is expected to survive: CONST_RUNID_SUBROOT_TTL = 7200 # 2 hours # Delay (sleep) for a small random amount to reduce CAS failures. # This does not affect correctness, but will reduce requests to etcd server. def cas_delay(): time.sleep(random.uniform(0, 0.1)) class EtcdRendezvousHandler(RendezvousHandler): """ Implements a :py:class:`torchelastic.rendezvous.RendezvousHandler` interface backed by :py:class:`torchelastic.rendezvous.etcd_rendezvous.EtcdRendezvous`. Torchelastic uses a URL to configure the type of rendezvous to use and to pass implementation specific configurations to the rendezvous module. The basic etcd rendezvous configuration URL looks like the following :: etcd://<etcd_address>:<port>/<job_id>?min_workers=<min_workers>&max_workers=<max_workers> # noqa W605 -- example -- etcd://localhost:2379/1234?min_workers=1&max_workers=3 The URL above is interpreted as follows: 1. Use the rendezvous handler that is registered with the ``etcd`` scheme 2. The ``etcd`` endpoint to use is ``localhost:2379`` 3. ``job_id == 1234`` is used as the prefix in etcd (this allows one to share a common etcd server for multiple jobs so long as the ``job_ids`` are guaranteed to be unique). Note that the job id can be any string (e.g. does not need to be a number) as long as it is unique. 4. ``min_workers=1`` and ``max_workers=3`` specifies a range for membership size - torchelastic starts running the job as long as the cluster size is greater than or equal to ``min_workers`` and admits up to ``max_workers`` into the cluster. Below are a full list of the parameters that can be passed to etcd rendezvous: +--------------------------------------------+--------------------------+ | Parameter | Description | +============================================+==========================+ | min_workers | minimum number of | | | workers for the | | | rendezvous to be valid | +--------------------------------------------+--------------------------+ | max_workers | maximum number of | | | workers to admit | +--------------------------------------------+--------------------------+ | timeout | total timeout within | | | which next_rendezvous is | | | expected to succeed | | | (default 600s) | +--------------------------------------------+--------------------------+ | last_call_timeout | additional wait amount | | | (“last call”) after min | | | number of workers has | | | been reached (defaults | | | to 30s) | +--------------------------------------------+--------------------------+ | etcd_prefix | path prefix (from etcd | | | root), inside which all | | | etcd nodes will be | | | created (defaults to | | | ``/torchelastic/p2p``) | +--------------------------------------------+--------------------------+ """ def __init__(self, rdzv_impl): self._rdzv_impl = rdzv_impl def __del__(self): # TODO: look into using weakref here instead. del self._rdzv_impl def get_backend(self) -> str: return "etcd" def next_rendezvous(self): rdzv_version, rank, world_size = self._rdzv_impl.rendezvous_barrier() log.info("Creating EtcdStore as the c10d::Store implementation") store = self._rdzv_impl.setup_kv_store(rdzv_version) return store, rank, world_size def is_closed(self): try: _, state = self._rdzv_impl.get_rdzv_state() return state["status"] == "closed" except etcd.EtcdKeyNotFound: # No rendezvous state, so it cannot be closed. return False def set_closed(self): self._rdzv_impl.set_closed() def num_nodes_waiting(self): try: _, state = self._rdzv_impl.get_rdzv_state() if state["status"] == "final": return state["num_workers_waiting"] except etcd.EtcdKeyNotFound: pass return 0 def get_run_id(self) -> str: return self._rdzv_impl._run_id def shutdown(self) -> bool: try: self.set_closed() return True except BaseException as e: log.warning(f"Shutdown failed. Error occurred: {str(e)}") return False # TODO: we should probably handle a few additional errors, # like EtcdLeaderElectionInProgress and EtcdWatcherCleared. These are # only relevant for multi-node Etcd ensemble. A simple retry would work, # but is verbose to add everywhere. Consider wrapping the client calls # into auto-retry for these errors? # class EtcdRendezvous(object): """ A rendezvous implementation that uses `etcd <https://etcd.io/>`__ as the backend store. """ def __init__( self, client, prefix, run_id, num_min_workers, num_max_workers, timeout, last_call_timeout, ): self.client = client log.info("Etcd machines: " + str(self.client.machines)) self._prefix = prefix self._run_id = run_id self._num_min_workers = num_min_workers self._num_max_workers = num_max_workers self._timeout = timeout self._last_call_timeout = last_call_timeout # For cleaning up TTL refresher threads (for ephemeral keys) self._lease_run_id_stop = None self._lease_this_rank_stop = None if not self._prefix.endswith("/"): self._prefix += "/" # Setup a permanent prefix dir, if didn't exist if self._prefix != "/": self.create_path_if_not_exists(self._prefix) # Lease a "sub-root" node specific to this job instance (run_id) self.create_path_if_not_exists(self.get_path(""), ttl=CONST_RUNID_SUBROOT_TTL) self._lease_run_id_stop = self.setup_lease_renewal( self.get_path(""), ttl=CONST_RUNID_SUBROOT_TTL ) # Subdir for all rendezvous work self.create_path_if_not_exists(self.get_path("/rdzv")) # Create a rendezvous version counter, if doesn't exist try: self.client.write( key=self.get_path("/rdzv/version_counter"), value="0", prevExist=False ) except etcd.EtcdAlreadyExist: pass def __del__(self): # TODO: look into using weakref here instead. if self._lease_run_id_stop is not None: self._lease_run_id_stop.set() if self._lease_this_rank_stop is not None: self._lease_this_rank_stop.set() def rendezvous_barrier(self): """ Main entry point for next rendezvous. This method is blocking until rendezvous succeeds or a timeout occurs. Returns: ``(rdzv_version, rank, world_size)`` Raises: RendezvousTimeoutError - timeout waiting for rendezvous RendezvousClosedError - rendezvous is or was closed while waiting RendezvousError - other persistent errors that render the rendezvous non-retryable """ self._rendezvous_deadline = time.time() + self._timeout while True: if time.time() > self._rendezvous_deadline: raise RendezvousTimeoutError() log.info("Attempting to join next rendezvous") try: # Dis-own our lease in the previous rendezvous, if exists if self._lease_this_rank_stop is not None: self._lease_this_rank_stop.set() return self.init_phase() except EtcdRendezvousRetryImmediately: # The type of failure suggests we can retry without delay pass except EtcdRendezvousRetryableFailure: # In case of retryable failure, wait a small delay # to avoid spamming etcd time.sleep(1) except RendezvousTimeoutError: log.info("Rendezvous timeout occured in EtcdRendezvousHandler") raise except RendezvousClosedError: log.info( f"Rendezvous for run_id={self._run_id} was observed to be closed" ) raise except RendezvousError: raise except Exception as e: # In case of a general exception, wait a small delay # to avoid spamming etcd # FIXME: there are a few things that fall under this like # etcd.EtcdKeyNotFound, etc, which could be handled more explicitly. log.info("Rendezvous attempt failed, will retry. Reason: " + str(e)) time.sleep(1) def init_phase(self): """ Initially, the rendezvous state is expected to be one of: 1. empty (non-existent) - in this case we try to create a new one. 2. joinable - we try to join it. 3. final - we announce ourselves as waiting, and go into monitoring mode Any other state is considered transitional, and will be retried after a short delay. Returns: ``(rdzv_version, rank, world_size)`` Raises: RendezvousClosedError - current rendezvous was/is closed EtcdRendezvousRetryableFailure - observed some intermediate state, which is best handled by retrying later """ try: active_version = self.try_create_rendezvous() state = json.loads(active_version.value) log.info("New rendezvous state created: " + str(state)) except etcd.EtcdAlreadyExist: active_version, state = self.get_rdzv_state() # Note: it is possible for above query to fail (etcd.EtcdKeyNotFound), # but this is ok for us - just means we'll restart from beginning. log.info("Observed existing rendezvous state: " + str(state)) if state["status"] == "closed": raise RendezvousClosedError() if state["status"] == "joinable": return self.join_phase(state["version"]) if state["status"] == "final": self.handle_existing_rendezvous(state["version"]) raise EtcdRendezvousRetryImmediately() self.try_wait_for_state_change(etcd_index=active_version.etcd_index + 1) raise EtcdRendezvousRetryableFailure() def join_phase(self, expected_version): """ We observed a rendezvous state in 'joinable' state, and attempt to join this particular version, and then wait for all other peers to join. """ # Failure to join will propagate an exception, causing a re-entry. active_version, this_rank = self.join_rendezvous(expected_version) state = json.loads(active_version.value) log.info( "Joined rendezvous version {} as rank {}. Full state: {}".format( state["version"], this_rank, state ) ) # If this worker was first to reach num_min_workers requirement, # and rendezvous is still joinable (therefore it is elastic), # then this worker will be repsonsible for waiting out the "last call" # timeout and closing (i.e. transitioning to 'frozen') the rendezvous # afterwards. # As a safety against a potential failure of this worker (during the # last call timeout), the rendezvous state is made ephemeral # when min_num_workers is reached. if this_rank == self._num_min_workers - 1 and state["status"] == "joinable": log.info("Rank {} is responsible for join last call.".format(this_rank)) last_call_deadline = time.time() + self._last_call_timeout self.handle_join_last_call(expected_version, last_call_deadline) log.info("Rank {} finished join last call.".format(this_rank)) # Wait for rendezvous state to be frozen, which means a fixed set of peers log.info("Waiting for remaining peers.") active_version = self.wait_for_peers(expected_version) state = json.loads(active_version.value) assert ( state["version"] == expected_version ), "Logic error: failed to observe version mismatch" return self.confirm_phase(expected_version, this_rank) def confirm_phase(self, expected_version, this_rank): """ Once the rendezvous state trainsitions from 'joinable' to 'frozen', we have every participant confirm their membership and setup per-member keep-alive TTL keys, and then wait for all other participants to confirm, which would then successfully conclude this rendezvous. """ log.info("All peers arrived. Confirming membership.") self.confirm_membership(expected_version, this_rank) log.info("Waiting for confirmations from all peers.") active_version = self.wait_for_final(expected_version) state = json.loads(active_version.value) log.info( "Rendezvous version {} is complete. Final state: {}".format( state["version"], state ) ) # Rendezvous version number; our rank in it; world size return state["version"], this_rank, len(state["participants"]) def handle_existing_rendezvous(self, expected_version): """ Handle the case when there's an existing (state 'final) rendezvous already in place, and we have to announce ourselves waiting, and wait until the next rendezvous opportunity. """ # If state is 'final' -> increment num_workers_waiting # Then, observe state changes: # 1. if it's no longer final -> bail out and re-try # 2. if keep alives are missing, destroy it and bail out. active_state = self.announce_self_waiting(expected_version) log.info( "Added self to waiting list. Rendezvous full state: {}".format( active_state.value ) ) self.wait_for_rendezvous_to_free(expected_version) log.info("Previously existing rendezvous state changed. Will re-try joining.") def try_create_rendezvous(self): """ Create new rendezvous state or raise an exception that indicates an unexpected state (e.g. already exists) Raises: RendezvousError - on unexpected state """ # Initially active_version is ephemeral - this is to handle the # possibility that might fail to complete the setup transaction, # i.e. the transition "setup" -> "joinable". active_version = self.client.write( key=self.get_path("/rdzv/active_version"), value=json.dumps({"status": "setup"}), prevExist=False, ttl=CONST_ETCD_SETUP_TTL, ) try: version_counter = self.client.get(self.get_path("/rdzv/version_counter")) version_counter.value = str(int(version_counter.value) + 1) self.client.update(version_counter) except (etcd.EtcdKeyNotFound, etcd.EtcdCompareFailed): raise RendezvousError( "Unexpected state of EtcdRendezvousHandler, worker needs to die." ) # Any failure below results in declaring a retryable rendezvous failure. # The ephemeral /rdzv/active_version will expire and someone can then # re-try the setup process. # Create directory node for participant data self.client.write( key=self.get_path("/rdzv/v_{}".format(version_counter.value)), value=None, dir=True, prevExist=False, ) # Publish rendezvous version and signal it is ready-to-be-joined. # If rendezvous was set closed just before this, a retry will happen, # where the closed condition will be handled. return self.client.test_and_set( key=self.get_path("/rdzv/active_version"), value=json.dumps( { "status": "joinable", "version": version_counter.value, "participants": [], } ), prev_value=active_version.value, ) def join_rendezvous(self, expected_version): """ Helper method for the join phase. """ # Use compare-and-swap to add self to rendezvous state: while True: cas_delay() active_version, state = self.get_rdzv_state() if state["status"] != "joinable": raise EtcdRendezvousRetryableFailure( "Rendezvous state became non-joinable before we could join. " "Must join next one." ) if state["version"] != expected_version: raise EtcdRendezvousRetryImmediately( "Rendezvous version changed. Must try join the new one." ) assert ( len(state["participants"]) < self._num_max_workers ), "Logic error: joinable rendezvous should always have space left" this_rank = len(state["participants"]) state["participants"].append(this_rank) # When reaching min workers, or changing state to frozen, we'll set # the active_version node to be ephemeral. set_ttl: Optional[int] = None if len(state["participants"]) == self._num_max_workers: state["status"] = "frozen" state["keep_alives"] = [] set_ttl = CONST_ETCD_FROZEN_TTL elif len(state["participants"]) >= self._num_min_workers: set_ttl = CONST_ETCD_JOINABLE_EPHEMERAL_TTL try: # Compare-and-swap. active_version = self.client.test_and_set( key=self.get_path("/rdzv/active_version"), value=json.dumps(state), prev_value=active_version.value, ttl=set_ttl, ) # We succeeded joining. return active_version, this_rank except etcd.EtcdCompareFailed: log.info("Join rendezvous CAS unsuccessful, retrying") def wait_for_peers(self, expected_version): """ Helper method for the join phase. """ active_version, state = self.get_rdzv_state() while True: if state["status"] == "frozen" and state["version"] == expected_version: # Success, all peers arrived. return active_version elif state["status"] == "joinable" and state["version"] == expected_version: # Continue waiting for any interesting events. active_version, state = self.try_wait_for_state_change( etcd_index=active_version.etcd_index + 1 ) else: # No valid transition possible at this point raise EtcdRendezvousRetryableFailure( "Rendezvous state transition no longer possible. Must re-enter." ) def confirm_membership(self, expected_version, this_rank): """ Helper method for the confirm phase """ # Compare-and-swap loop while True: cas_delay() active_version, state = self.get_rdzv_state() if state["status"] != "frozen": raise EtcdRendezvousRetryImmediately( "Rendezvous no longer frozen, before we confirmed. " "Must join next one" ) if state["version"] != expected_version: raise EtcdRendezvousRetryImmediately( "Rendezvous version changed. Must try join the new one." ) this_lease_key = self.get_path( "/rdzv/v_{}/rank_{}".format(expected_version, this_rank) ) self.client.set(this_lease_key, value=None, ttl=CONST_WORKER_KEEPALIVE_TTL) state["keep_alives"].append(this_lease_key) if len(state["keep_alives"]) == len(state["participants"]): # Everyone confirmed (this rank is last to do so) state["status"] = "final" state["num_workers_waiting"] = 0 finalize = True else: finalize = False try: # Compare-and-swap. If new state is still frozen, keep it ephemeral. active_version = self.client.test_and_set( key=self.get_path("/rdzv/active_version"), value=json.dumps(state), prev_value=active_version.value, ttl=None if finalize else CONST_ETCD_FROZEN_TTL, ) self._lease_this_rank_stop = self.setup_lease_renewal( this_lease_key, ttl=CONST_WORKER_KEEPALIVE_TTL ) return active_version except etcd.EtcdCompareFailed: log.info("Confirm membership CAS unsuccessful, retrying") def wait_for_final(self, expected_version): """ Helper method for the confirm phase """ active_version, state = self.get_rdzv_state() while True: if state["status"] == "final" and state["version"] == expected_version: # Succcess. This rendezvous is final, and we accept it. return active_version elif state["status"] == "frozen" and state["version"] == expected_version: # Continue waiting for any interesting events. active_version, state = self.try_wait_for_state_change( etcd_index=active_version.etcd_index + 1 ) else: # No valid transition possible at this point raise EtcdRendezvousRetryableFailure( "Rendezvous state transition no longer possible. Must re-enter." ) def announce_self_waiting(self, expected_version): """ Announce this worker is waiting (via num_workers_waiting counter) to join next rendezvous, but only if state and version match. """ while True: cas_delay() active_version, state = self.get_rdzv_state() if state["status"] != "final" or state["version"] != expected_version: raise EtcdRendezvousRetryImmediately() # Increment counter to signal an additional waiting worker. state["num_workers_waiting"] += 1 try: active_version = self.client.test_and_set( key=self.get_path("/rdzv/active_version"), value=json.dumps(state), prev_value=active_version.value, ) return active_version except etcd.EtcdCompareFailed: log.info("Announce self as waiting CAS unsuccessful, retrying") def wait_for_rendezvous_to_free(self, expected_version): """ When there's an existing valid rendezvous in state 'final', we have to wait until the next opportunity to join. Such opportunity may come from: 1. rendezvous state changed by someone else, in which case we unblock and retry. 2. rendezvous becomes invalid because at least one member failed to renew their leased keep_alive node. We detect this, and destroy the rendezvous. """ active_version, state = self.get_rdzv_state() while True: if state["status"] != "final" or state["version"] != expected_version: return # Check if current rendezvous state is valid, in the sense that all # its members are alive (renewing their lease). # If not, try destroy this rendezvous, so a new one can be created. alive_members = self.client.get( self.get_path("/rdzv/v_{version}".format(version=expected_version)) ) keep_alive_keys = [ch.key for ch in alive_members.children] for key in state["keep_alives"]: if key not in keep_alive_keys: # This participant didn't renew their lease. We'll declare this # rendezvous version as dead (but only if it hadn't changed) log.info("Keep-alive key {} is not renewed.".format(key)) log.info( "Rendevous version {} is incomplete. ".format(expected_version) ) log.info("Attempting to destroy it.") # Compare-and-delete operation. Throws if compare failed, # which means rendezvous was already destroyed/re-created/closed, # and we can try to re-enter the barrier. self.client.delete( key=self.get_path("/rdzv/active_version"), prevValue=active_version.value, ) log.info( "Destroyed rendezvous version {} successfully.".format( expected_version ) ) # We can return (and retry) immediately return # Existing rendezvous seems valid, no reason to destroy it. # We just have to wait until something changes and re-check. try: overall_timeout = ( max(self._rendezvous_deadline - time.time(), 0.0) + 1.0 ) self.client.watch( key=self.get_path("/rdzv"), index=active_version.etcd_index + 1, recursive=True, timeout=overall_timeout, ) except (etcd.EtcdEventIndexCleared, etcd.EtcdWatchTimedOut): pass if time.time() > self._rendezvous_deadline: raise RendezvousTimeoutError() active_version, state = self.get_rdzv_state() def handle_join_last_call(self, expected_version, deadline): """ After we reach min number of workers, one particular worker takes on the responsibility of waiting an additional timeout before closing the join window. If the worker responsible for this fails, the rendezvous will be destroyed due to expiring TTL, and the other participants will re-rendezvous. Here we expect to see state <joinable, expected_version> Exit gracefully if either: 1. state becomes <frozen, expected_version> 2. timeout happens (reaching deadline), in which case we try the tranisiton to <frozen, expected_version> Exit with exception otherwise. """ active_version, state = self.get_rdzv_state() while True: if state["status"] == "frozen" and state["version"] == expected_version: # Worker set became frozen before last-call timeout. This is possible # when num_max_workers is reached before the tiemout. return if state["status"] != "joinable" or state["version"] != expected_version: raise EtcdRendezvousRetryableFailure( "Rendezvous state transition no longer possible. Must re-enter." ) # If timeout occurred, attempt a state transition (joinable -> frozen) if time.time() >= deadline: state["status"] = "frozen" state["keep_alives"] = [] try: active_version = self.client.test_and_set( key=self.get_path("/rdzv/active_version"), value=json.dumps(state), prev_value=active_version.value, ttl=CONST_ETCD_FROZEN_TTL, ) # We successfully made this rendezvous frozen. return except etcd.EtcdCompareFailed: log.info("Join last-call transition CAS unsuccessful. Will retry") cas_delay() active_version, state = self.get_rdzv_state() continue # Timeout did not occur, so we must refresh TTL, and wait for # further changes. Note: we only want TTL to be refreshed if # state is still joinable, hence we use CAS for that here, # even though we don't change any of the data. try: active_version = self.client.test_and_set( key=self.get_path("/rdzv/active_version"), value=active_version.value, prev_value=active_version.value, ttl=CONST_ETCD_JOINABLE_EPHEMERAL_TTL, ) # Minimize "oversleeping": timeout = min( CONST_ETCD_JOINABLE_EPHEMERAL_TTL / 2, deadline - time.time() + 1.0, # Oversleeping by 1s is ok. ) active_version, state = self.try_wait_for_state_change( etcd_index=active_version.etcd_index + 1, timeout=timeout ) except etcd.EtcdCompareFailed: log.info("Join last-call TTL refresh CAS unsuccessful, will retry") cas_delay() active_version, state = self.get_rdzv_state() def set_closed(self): """ Mark rendezvous 'closed' for current run_id, which is used to signal other participants to not attempt to perform (re-)rendezvous. This is useful when one of the workers decides the job is complete. """ while True: active_version, state = self.get_rdzv_state() if state["status"] == "closed": # Already closed by someone else. return state["status"] = "closed" try: self.client.test_and_set( key=self.get_path("/rdzv/active_version"), value=json.dumps(state), prev_value=active_version.value, ) return except etcd.EtcdCompareFailed: log.info("Set closed CAS unsuccessful, retrying") cas_delay() def get_rdzv_state(self): active_version = self.client.get(key=self.get_path("/rdzv/active_version")) return active_version, json.loads(active_version.value) def try_wait_for_state_change(self, etcd_index, timeout=None): # Don't sleep past the overall deadline (at least more than by 1s) overall_timeout = max(self._rendezvous_deadline - time.time(), 0.0) + 1.0 timeout = overall_timeout if timeout is None else min(timeout, overall_timeout) try: self.client.watch( self.get_path("/rdzv/active_version"), index=etcd_index, timeout=timeout ) except (etcd.EtcdEventIndexCleared, etcd.EtcdWatchTimedOut): pass if time.time() > self._rendezvous_deadline: raise RendezvousTimeoutError() # Unfortunately, we have to do another fetch in order to get last etcd_index. return self.get_rdzv_state() def get_path(self, path): if not path.startswith("/"): path = "/" + path return "{prefix}run_{run_id}{path}".format( prefix=self._prefix, run_id=self._run_id, path=path ) def create_path_if_not_exists(self, full_path, ttl=None): try: self.client.write( key=full_path, value=None, dir=True, prevExist=False, ttl=ttl ) except etcd.EtcdAlreadyExist: pass def setup_lease_renewal(self, full_path, ttl): # NOTE: For ephemeral key TTL renewal (~lease) to work correctly, # make sure you don't call any long-blocking methods that do not # release the Python's GIL! An example of this is calling a pybind11 # extension function that is blocking / long-running, but is not # doing a scoped release of the GIL. def lease_worker(client, path, ttl, stop_event): while True: try: client.refresh(path, ttl=ttl) except etcd.EtcdKeyNotFound: break except ConnectionRefusedError: # This error usually occurs during test when the server already got terminated but the # python garbage collector have not yet invoked the __del__ method. break if stop_event.wait(timeout=ttl / 2): break lease_stop_event = threading.Event() lease_thread = threading.Thread( target=lease_worker, args=(self.client, full_path, ttl, lease_stop_event) ) lease_thread.daemon = True lease_thread.start() return lease_stop_event def store_extra_data(self, rdzv_version, key, value): node = self.get_path("/rdzv/v_{}/extra_data".format(rdzv_version)) try: # If first time we are storing anything: extra_data = self.client.write( key=node, value=json.dumps({key: value}), prevExist=False ) return except etcd.EtcdAlreadyExist: pass # CAS loop, to make sure we don't lose concurrent stores. while True: # We never delete extra_data. Failure here should be fatal, no special handling. extra_data = self.client.get(node) new_extra_data_value = json.loads(extra_data.value) new_extra_data_value[key] = value try: extra_data = self.client.test_and_set( key=node, value=json.dumps(new_extra_data_value), prev_value=extra_data.value, ) return except etcd.EtcdCompareFailed: log.info("Store extra_data CAS unsuccessful, retrying") time.sleep(0.1) def load_extra_data(self, rdzv_version, key, timeout=None): # 'extra_data' node itself, and the directory it is located in: node = self.get_path("/rdzv/v_{}/extra_data".format(rdzv_version)) node_dir = self.get_path("/rdzv/v_{}".format(rdzv_version)) # TODO: implement timeout # https://github.com/pytorch/elastic/issues/12 while True: # Combined wait for the node itself, and the key inside it. root = self.client.get(node_dir) # Find the extra_data node, if it exists extra_data = [n for n in root.children if n.key == node] assert len(extra_data) <= 1 # Node for extra_data exists, check the desired key inside it. if len(extra_data) == 1: extra_data_dict = json.loads(extra_data[0].value) if key in extra_data_dict: return extra_data_dict[key] # The 'extra_data' node doesn't exist, or they key isn't published yet. # Wait for interesting events on the extra_data node and retry. try: self.client.watch(node, index=root.etcd_index + 1) except (etcd.EtcdEventIndexCleared, etcd.EtcdWatchTimedOut): pass def setup_kv_store(self, rdzv_version): store_path = self.get_path(f"/rdzv/v_{rdzv_version}/kv") self.create_path_if_not_exists(store_path) return EtcdStore(etcd_client=self.client, etcd_store_prefix=store_path) # pyre-fixme[11]: Annotation `Store` is not defined as a type. class EtcdStore(Store): """ Implements a c10 Store interface by piggybacking on the rendezvous etcd instance. This is the store object returned by ``EtcdRendezvous`` """ def __init__( self, etcd_client, etcd_store_prefix, # Default timeout same as in c10d/Store.hpp timeout: Optional[datetime.timedelta] = None, ): super().__init__() # required for pybind trampoline. self.client = etcd_client self.prefix = etcd_store_prefix if timeout is not None: self.set_timeout(timeout) if not self.prefix.endswith("/"): self.prefix += "/" def set(self, key, value): """ Write a key/value pair into ``EtcdStore``. Both key and value may be either Python ``str`` or ``bytes``. """ self.client.set(key=self.prefix + self._encode(key), value=self._encode(value)) def get(self, key) -> bytes: """ Get a value by key, possibly doing a blocking wait. If key is not immediately present, will do a blocking wait for at most ``timeout`` duration or until the key is published. Returns: value ``(bytes)`` Raises: LookupError - If key still not published after timeout """ b64_key = self.prefix + self._encode(key) kvs = self._try_wait_get([b64_key]) if kvs is None: raise LookupError(f"Key {key} not found in EtcdStore") return self._decode(kvs[b64_key]) def add(self, key, num: int) -> int: """ Atomically increment a value by an integer amount. The integer is represented as a string using base 10. If key is not present, a default value of ``0`` will be assumed. Returns: the new (incremented) value """ b64_key = self._encode(key) # c10d Store assumes value is an integer represented as a decimal string try: # Assume default value "0", if this key didn't yet: node = self.client.write( key=self.prefix + b64_key, value=self._encode(str(num)), # i.e. 0 + num prevExist=False, ) return int(self._decode(node.value)) except etcd.EtcdAlreadyExist: pass while True: # Note: c10d Store does not have a method to delete keys, so we # can be sure it's still there. node = self.client.get(key=self.prefix + b64_key) new_value = self._encode(str(int(self._decode(node.value)) + num)) try: node = self.client.test_and_set( key=node.key, value=new_value, prev_value=node.value ) return int(self._decode(node.value)) except etcd.EtcdCompareFailed: cas_delay() def wait(self, keys, override_timeout: Optional[datetime.timedelta] = None): """ Waits until all of the keys are published, or until timeout. Raises: LookupError - if timeout occurs """ b64_keys = [self.prefix + self._encode(key) for key in keys] kvs = self._try_wait_get(b64_keys, override_timeout) if kvs is None: raise LookupError("Timeout while waiting for keys in EtcdStore") # No return value on success def check(self, keys) -> bool: """ Check if all of the keys are immediately present (without waiting). """ b64_keys = [self.prefix + self._encode(key) for key in keys] kvs = self._try_wait_get( b64_keys, override_timeout=datetime.timedelta(microseconds=1), # as if no wait ) return kvs is not None # # Encode key/value data in base64, so we can store arbitrary binary data # in EtcdStore. Input can be `str` or `bytes`. # In case of `str`, utf-8 encoding is assumed. # def _encode(self, value) -> str: if type(value) == bytes: return b64encode(value).decode() elif type(value) == str: return b64encode(value.encode()).decode() raise ValueError("Value must be of type str or bytes") # # Decode a base64 string (of type `str` or `bytes`). # Return type is `bytes`, which is more convenient with the Store interface. # def _decode(self, value) -> bytes: if type(value) == bytes: return b64decode(value) elif type(value) == str: return b64decode(value.encode()) raise ValueError("Value must be of type str or bytes") # # Get all of the (base64-encoded) etcd keys at once, or wait until all the keys # are published or timeout occurs. # This is a helper method for the public interface methods. # # On success, a dictionary of {etcd key -> etcd value} is returned. # On timeout, None is returned. # def _try_wait_get(self, b64_keys, override_timeout=None): timeout = self.timeout if override_timeout is None else override_timeout # type: ignore[attr-defined] deadline = time.time() + timeout.total_seconds() while True: # Read whole directory (of keys), filter only the ones waited for all_nodes = self.client.get(key=self.prefix) req_nodes = { node.key: node.value for node in all_nodes.children if node.key in b64_keys } if len(req_nodes) == len(b64_keys): # All keys are available return req_nodes watch_timeout = deadline - time.time() if watch_timeout <= 0: return None try: self.client.watch( key=self.prefix, recursive=True, timeout=watch_timeout, index=all_nodes.etcd_index + 1, ) except etcd.EtcdWatchTimedOut: if time.time() >= deadline: return None else: continue except etcd.EtcdEventIndexCleared: continue def _create_etcd_client(params: RendezvousParameters) -> etcd.Client: """ Creates a new ``etcd.Client`` from the specified ``RendezvousParameters``. """ hostname, port = _parse_rendezvous_endpoint(params.endpoint, 2379) # The communication protocol protocol = params.config.get("protocol") if protocol is None: protocol = "http" else: if protocol != "http" and protocol != "https": raise ValueError("The etcd protocol must be HTTP or HTTPS.") # The SSL client certificate ssl_cert = params.config.get("cert") if ssl_cert is not None: cert_key = params.config.get("key") if cert_key is not None: # The etcd client expects the certificate key as the second element # of the `cert` tuple. ssl_cert = (ssl_cert, cert_key) # The root certificate ca_cert = params.config.get("cacert") return etcd.Client( hostname, port, protocol=protocol, cert=ssl_cert, ca_cert=ca_cert, allow_reconnect=True, ) # Handler for torch.distributed "static" registration def create_rdzv_handler(params: RendezvousParameters) -> RendezvousHandler: """ Usage: :: rdzv_params = RendezvousParameters( backend="etcd", endpoint="192.168.0.42:2379", run_id="123", min_nodes=4, max_nodes=8, timeout=300, last_call_timeout=30, etcd_prefix="custom_prefix", protocol="https", cacert="/etc/kubernetes/certs/ca.crt", cert="/etc/kubernetes/certs/client.crt", key="/etc/kubernetes/certs/client.key") # -- or -- rdzv_params = RendezvousParameters( backend="etcd", endpoint="192.168.0.42:2379", run_id="123", min_nodes=4, max_nodes=8) etcd_rdzv_handler = create_etcd_rendezvous_handler(rdzv_params) Where: run_id - unique id for this training job instance, min_nodes - min number of workers expected to join the rendezvous, max_nodes - max number of workers allowed to join the rendezvous, defaults to min_workers is not specified. timeout - total timeout within which next_rendezvous is expected to succeed; a RendezvousTimeoutError is raised otherwise; Defaults is 600 (10 minutes). last_call_timeout - additional wait amount ("last call") after min number of workers has been reached. Defaults to 30 seconds. etcd_prefix - path prefix (from etcd root), inside which all etcd nodes will be created. Default is "/torchelastic/p2p". protocol - http (default) or https to access etcd. cacert - CA cert to access etcd, only makes sense with https. cert - client cert to access etcd, only makes sense with https. key - client key to access etcd, only makes sense with https. """ client = _create_etcd_client(params) etcd_prefix = params.get("etcd_prefix", "/torchelastic/p2p") rdzv = EtcdRendezvous( client=client, prefix=etcd_prefix, run_id=params.run_id, num_min_workers=params.min_nodes, num_max_workers=params.max_nodes, timeout=params.get_as_int("timeout", _DEFAULT_TIMEOUT), last_call_timeout=params.get_as_int("last_call_timeout", _DEFAULT_LAST_CALL_TIMEOUT), ) return EtcdRendezvousHandler(rdzv_impl=rdzv)
datasets.py
# Dataset utils and dataloaders import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image, ExifTags from torch.utils.data import Dataset from tqdm import tqdm from utils.general import xyxy2xywh, xywh2xyxy, xywhn2xyxy, xyn2xy, segment2box, segments2boxes, resample_segments, \ clean_str from utils.torch_utils import torch_distributed_zero_first # Parameters help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data' img_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp'] # acceptable image suffixes vid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes logger = logging.getLogger(__name__) # Get orientation exif tag for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break def get_hash(files): # Returns a single hash value of a list of files return sum(os.path.getsize(f) for f in files if os.path.isfile(f)) def exif_size(img): # Returns exif-corrected PIL size s = img.size # (width, height) try: rotation = dict(img._getexif().items())[orientation] if rotation == 6: # rotation 270 s = (s[1], s[0]) elif rotation == 8: # rotation 90 s = (s[1], s[0]) except: pass return s def create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False, rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''): # Make sure only the first process in DDP process the dataset first, and the following others can use the cache with torch_distributed_zero_first(rank): dataset = LoadImagesAndLabels(path, imgsz, batch_size, augment=augment, # augment images hyp=hyp, # augmentation hyperparameters rect=rect, # rectangular training cache_images=cache, single_cls=opt.single_cls, stride=int(stride), pad=pad, image_weights=image_weights, prefix=prefix) batch_size = min(batch_size, len(dataset)) nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers]) # number of workers sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader() dataloader = loader(dataset, batch_size=batch_size, num_workers=nw, sampler=sampler, pin_memory=True, collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn) return dataloader, dataset class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader): """ Dataloader that reuses workers Uses same syntax as vanilla DataLoader """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler)) self.iterator = super().__iter__() def __len__(self): return len(self.batch_sampler.sampler) def __iter__(self): for i in range(len(self)): yield next(self.iterator) class _RepeatSampler(object): """ Sampler that repeats forever Args: sampler (Sampler) """ def __init__(self, sampler): self.sampler = sampler def __iter__(self): while True: yield from iter(self.sampler) class LoadImages: # for inference def __init__(self, path, img_size=640, stride=32): p = str(Path(path).absolute()) # os-agnostic absolute path if '*' in p: files = sorted(glob.glob(p, recursive=True)) # glob elif os.path.isdir(p): files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir elif os.path.isfile(p): files = [p] # files else: raise Exception(f'ERROR: {p} does not exist') images = [x for x in files if x.split('.')[-1].lower() in img_formats] videos = [x for x in files if x.split('.')[-1].lower() in vid_formats] ni, nv = len(images), len(videos) self.img_size = img_size self.stride = stride self.files = images + videos self.nf = ni + nv # number of files self.video_flag = [False] * ni + [True] * nv self.mode = 'image' if any(videos): self.new_video(videos[0]) # new video else: self.cap = None assert self.nf > 0, f'No images or videos found in {p}. ' \ f'Supported formats are:\nimages: {img_formats}\nvideos: {vid_formats}' def __iter__(self): self.count = 0 return self def __next__(self): if self.count == self.nf: raise StopIteration path = self.files[self.count] if self.video_flag[self.count]: # Read video self.mode = 'video' ret_val, img0 = self.cap.read() if not ret_val: self.count += 1 self.cap.release() if self.count == self.nf: # last video raise StopIteration else: path = self.files[self.count] self.new_video(path) ret_val, img0 = self.cap.read() self.frame += 1 print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.nframes}) {path}: ', end='') else: # Read image self.count += 1 img0 = cv2.imread(path) # BGR assert img0 is not None, 'Image Not Found ' + path print(f'image {self.count}/{self.nf} {path}: ', end='') # Padded resize img = letterbox(img0, self.img_size, stride=self.stride)[0] # Convert img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 img = np.ascontiguousarray(img) return path, img, img0, self.cap def new_video(self, path): self.frame = 0 self.cap = cv2.VideoCapture(path) self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) def __len__(self): return self.nf # number of files class LoadWebcam: # for inference def __init__(self, pipe='0', img_size=640, stride=32): self.img_size = img_size self.stride = stride if pipe.isnumeric(): pipe = eval(pipe) # local camera # pipe = 'rtsp://192.168.1.64/1' # IP camera # pipe = 'rtsp://username:password@192.168.1.64/1' # IP camera with login # pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera self.pipe = pipe self.cap = cv2.VideoCapture(pipe) # video capture object self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size def __iter__(self): self.count = -1 return self def __next__(self): self.count += 1 if cv2.waitKey(1) == ord('q'): # q to quit self.cap.release() cv2.destroyAllWindows() raise StopIteration # Read frame if self.pipe == 0: # local camera ret_val, img0 = self.cap.read() img0 = cv2.flip(img0, 1) # flip left-right else: # IP camera n = 0 while True: n += 1 self.cap.grab() if n % 30 == 0: # skip frames ret_val, img0 = self.cap.retrieve() if ret_val: break # Print assert ret_val, f'Camera Error {self.pipe}' img_path = 'webcam.jpg' print(f'webcam {self.count}: ', end='') # Padded resize img = letterbox(img0, self.img_size, stride=self.stride)[0] # Convert img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 img = np.ascontiguousarray(img) return img_path, img, img0, None def __len__(self): return 0 class LoadStreams: # multiple IP or RTSP cameras def __init__(self, sources='streams.txt', img_size=640, stride=32): self.mode = 'stream' self.img_size = img_size self.stride = stride if os.path.isfile(sources): with open(sources, 'r') as f: sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())] else: sources = [sources] n = len(sources) self.imgs = [None] * n self.sources = [clean_str(x) for x in sources] # clean source names for later for i, s in enumerate(sources): # Start the thread to read frames from the video stream print(f'{i + 1}/{n}: {s}... ', end='') cap = cv2.VideoCapture(eval(s) if s.isnumeric() else s) assert cap.isOpened(), f'Failed to open {s}' w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = cap.get(cv2.CAP_PROP_FPS) % 100 _, self.imgs[i] = cap.read() # guarantee first frame thread = Thread(target=self.update, args=([i, cap]), daemon=True) print(f' success ({w}x{h} at {fps:.2f} FPS).') thread.start() print('') # newline # check for common shapes s = np.stack([letterbox(x, self.img_size, stride=self.stride)[0].shape for x in self.imgs], 0) # shapes self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal if not self.rect: print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.') def update(self, index, cap): # Read next stream frame in a daemon thread n = 0 while cap.isOpened(): n += 1 # _, self.imgs[index] = cap.read() cap.grab() if n == 4: # read every 4th frame _, self.imgs[index] = cap.retrieve() n = 0 time.sleep(0.01) # wait time def __iter__(self): self.count = -1 return self def __next__(self): self.count += 1 img0 = self.imgs.copy() if cv2.waitKey(1) == ord('q'): # q to quit cv2.destroyAllWindows() raise StopIteration # Letterbox img = [letterbox(x, self.img_size, auto=self.rect, stride=self.stride)[0] for x in img0] # Stack img = np.stack(img, 0) # Convert img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416 img = np.ascontiguousarray(img) return self.sources, img, img0, None def __len__(self): return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years def img2label_paths(img_paths): # Define label paths as a function of image paths sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings return [x.replace(sa, sb, 1).replace('.' + x.split('.')[-1], '.txt') for x in img_paths] class LoadImagesAndLabels(Dataset): # for training/testing def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False, cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''): self.img_size = img_size self.augment = augment self.hyp = hyp self.image_weights = image_weights self.rect = False if image_weights else rect self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training) self.mosaic_border = [-img_size // 2, -img_size // 2] self.stride = stride self.path = path try: f = [] # image files for p in path if isinstance(path, list) else [path]: p = Path(p) # os-agnostic if p.is_dir(): # dir f += glob.glob(str(p / '**' / '*.*'), recursive=True) # f = list(p.rglob('**/*.*')) # pathlib elif p.is_file(): # file with open(p, 'r') as t: t = t.read().strip().splitlines() parent = str(p.parent) + os.sep f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib) else: raise Exception(f'{prefix}{p} does not exist') self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats]) # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib assert self.img_files, f'{prefix}No images found' except Exception as e: raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {help_url}') # Check cache self.label_files = img2label_paths(self.img_files) # labels cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels if cache_path.is_file(): cache, exists = torch.load(cache_path), True # load if cache['hash'] != get_hash(self.label_files + self.img_files) or 'version' not in cache: # changed cache, exists = self.cache_labels(cache_path, prefix), False # re-cache else: cache, exists = self.cache_labels(cache_path, prefix), False # cache # Display cache nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total if exists: d = f"Scanning '{cache_path}' for images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted" tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}' # Read cache cache.pop('hash') # remove hash cache.pop('version') # remove version labels, shapes, self.segments = zip(*cache.values()) self.labels = list(labels) self.shapes = np.array(shapes, dtype=np.float64) self.img_files = list(cache.keys()) # update self.label_files = img2label_paths(cache.keys()) # update if single_cls: for x in self.labels: x[:, 0] = 0 n = len(shapes) # number of images bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index nb = bi[-1] + 1 # number of batches self.batch = bi # batch index of image self.n = n self.indices = range(n) # Rectangular Training if self.rect: # Sort by aspect ratio s = self.shapes # wh ar = s[:, 1] / s[:, 0] # aspect ratio irect = ar.argsort() self.img_files = [self.img_files[i] for i in irect] self.label_files = [self.label_files[i] for i in irect] self.labels = [self.labels[i] for i in irect] self.shapes = s[irect] # wh ar = ar[irect] # Set training image shapes shapes = [[1, 1]] * nb for i in range(nb): ari = ar[bi == i] mini, maxi = ari.min(), ari.max() if maxi < 1: shapes[i] = [maxi, 1] elif mini > 1: shapes[i] = [1, 1 / mini] self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM) self.imgs = [None] * n if cache_images: gb = 0 # Gigabytes of cached images self.img_hw0, self.img_hw = [None] * n, [None] * n results = ThreadPool(8).imap(lambda x: load_image(*x), zip(repeat(self), range(n))) # 8 threads pbar = tqdm(enumerate(results), total=n) for i, x in pbar: self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # img, hw_original, hw_resized = load_image(self, i) gb += self.imgs[i].nbytes pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)' def cache_labels(self, path=Path('./labels.cache'), prefix=''): # Cache dataset labels, check images and read shapes x = {} # dict nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, duplicate pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files)) for i, (im_file, lb_file) in enumerate(pbar): try: # verify images im = Image.open(im_file) im.verify() # PIL verify shape = exif_size(im) # image size segments = [] # instance segments assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels' assert im.format.lower() in img_formats, f'invalid image format {im.format}' # verify labels if os.path.isfile(lb_file): nf += 1 # label found with open(lb_file, 'r') as f: l = [x.split() for x in f.read().strip().splitlines()] if any([len(x) > 8 for x in l]): # is segment classes = np.array([x[0] for x in l], dtype=np.float32) segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...) l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh) l = np.array(l, dtype=np.float32) if len(l): assert l.shape[1] == 5, 'labels require 5 columns each' assert (l >= 0).all(), 'negative labels' assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels' assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels' else: ne += 1 # label empty l = np.zeros((0, 5), dtype=np.float32) else: nm += 1 # label missing l = np.zeros((0, 5), dtype=np.float32) x[im_file] = [l, shape, segments] except Exception as e: nc += 1 print(f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}') pbar.desc = f"{prefix}Scanning '{path.parent / path.stem}' for images and labels... " \ f"{nf} found, {nm} missing, {ne} empty, {nc} corrupted" if nf == 0: print(f'{prefix}WARNING: No labels found in {path}. See {help_url}') x['hash'] = get_hash(self.label_files + self.img_files) x['results'] = nf, nm, ne, nc, i + 1 x['version'] = 0.1 # cache version torch.save(x, path) # save for next time logging.info(f'{prefix}New cache created: {path}') return x def __len__(self): return len(self.img_files) # def __iter__(self): # self.count = -1 # print('ran dataset iter') # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF) # return self def __getitem__(self, index): index = self.indices[index] # linear, shuffled, or image_weights hyp = self.hyp mosaic = self.mosaic and random.random() < hyp['mosaic'] if mosaic: # Load mosaic img, labels = load_mosaic(self, index) shapes = None # MixUp https://arxiv.org/pdf/1710.09412.pdf if random.random() < hyp['mixup']: img2, labels2 = load_mosaic(self, random.randint(0, self.n - 1)) r = np.random.beta(8.0, 8.0) # mixup ratio, alpha=beta=8.0 img = (img * r + img2 * (1 - r)).astype(np.uint8) labels = np.concatenate((labels, labels2), 0) else: # Load image img, (h0, w0), (h, w) = load_image(self, index) # Letterbox shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment) shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling labels = self.labels[index].copy() if labels.size: # normalized xywh to pixel xyxy format labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1]) if self.augment: # Augment imagespace if not mosaic: img, labels = random_perspective(img, labels, degrees=hyp['degrees'], translate=hyp['translate'], scale=hyp['scale'], shear=hyp['shear'], perspective=hyp['perspective']) # Augment colorspace augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v']) # Apply cutouts # if random.random() < 0.9: # labels = cutout(img, labels) nL = len(labels) # number of labels if nL: labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) # convert xyxy to xywh labels[:, [2, 4]] /= img.shape[0] # normalized height 0-1 labels[:, [1, 3]] /= img.shape[1] # normalized width 0-1 if self.augment: # flip up-down if random.random() < hyp['flipud']: img = np.flipud(img) if nL: labels[:, 2] = 1 - labels[:, 2] # flip left-right if random.random() < hyp['fliplr']: img = np.fliplr(img) if nL: labels[:, 1] = 1 - labels[:, 1] labels_out = torch.zeros((nL, 6)) if nL: labels_out[:, 1:] = torch.from_numpy(labels) # Convert img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 img = np.ascontiguousarray(img) return torch.from_numpy(img), labels_out, self.img_files[index], shapes @staticmethod def collate_fn(batch): img, label, path, shapes = zip(*batch) # transposed for i, l in enumerate(label): l[:, 0] = i # add target image index for build_targets() return torch.stack(img, 0), torch.cat(label, 0), path, shapes @staticmethod def collate_fn4(batch): img, label, path, shapes = zip(*batch) # transposed n = len(shapes) // 4 img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n] ho = torch.tensor([[0., 0, 0, 1, 0, 0]]) wo = torch.tensor([[0., 0, 1, 0, 0, 0]]) s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW i *= 4 if random.random() < 0.5: im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[ 0].type(img[i].type()) l = label[i] else: im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2) l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s img4.append(im) label4.append(l) for i, l in enumerate(label4): l[:, 0] = i # add target image index for build_targets() return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4 # Ancillary functions -------------------------------------------------------------------------------------------------- def load_image(self, index): # loads 1 image from dataset, returns img, original hw, resized hw img = self.imgs[index] if img is None: # not cached path = self.img_files[index] img = cv2.imread(path) # BGR assert img is not None, 'Image Not Found ' + path h0, w0 = img.shape[:2] # orig hw r = self.img_size / max(h0, w0) # resize image to img_size if r != 1: # always resize down, only resize up if training with augmentation interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp) return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized else: return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5): r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV)) dtype = img.dtype # uint8 x = np.arange(0, 256, dtype=np.int16) lut_hue = ((x * r[0]) % 180).astype(dtype) lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) lut_val = np.clip(x * r[2], 0, 255).astype(dtype) img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype) cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed def hist_equalize(img, clahe=True, bgr=False): # Equalize histogram on BGR image 'img' with img.shape(n,m,3) and range 0-255 yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV) if clahe: c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) yuv[:, :, 0] = c.apply(yuv[:, :, 0]) else: yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB def load_mosaic(self, index): # loads images in a 4-mosaic labels4, segments4 = [], [] s = self.img_size yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y indices = [index] + [self.indices[random.randint(0, self.n - 1)] for _ in range(3)] # 3 additional image indices for i, index in enumerate(indices): # Load image img, _, (h, w) = load_image(self, index) # place img in img4 if i == 0: # top left img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image) x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image) elif i == 1: # top right x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h elif i == 2: # bottom left x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h) elif i == 3: # bottom right x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] padw = x1a - x1b padh = y1a - y1b # Labels labels, segments = self.labels[index].copy(), self.segments[index].copy() if labels.size: labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format segments = [xyn2xy(x, w, h, padw, padh) for x in segments] labels4.append(labels) segments4.extend(segments) # Concat/clip labels labels4 = np.concatenate(labels4, 0) for x in (labels4[:, 1:], *segments4): np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() # img4, labels4 = replicate(img4, labels4) # replicate # Augment img4, labels4 = random_perspective(img4, labels4, segments4, degrees=self.hyp['degrees'], translate=self.hyp['translate'], scale=self.hyp['scale'], shear=self.hyp['shear'], perspective=self.hyp['perspective'], border=self.mosaic_border) # border to remove return img4, labels4 def load_mosaic9(self, index): # loads images in a 9-mosaic labels9, segments9 = [], [] s = self.img_size indices = [index] + [self.indices[random.randint(0, self.n - 1)] for _ in range(8)] # 8 additional image indices for i, index in enumerate(indices): # Load image img, _, (h, w) = load_image(self, index) # place img in img9 if i == 0: # center img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles h0, w0 = h, w c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates elif i == 1: # top c = s, s - h, s + w, s elif i == 2: # top right c = s + wp, s - h, s + wp + w, s elif i == 3: # right c = s + w0, s, s + w0 + w, s + h elif i == 4: # bottom right c = s + w0, s + hp, s + w0 + w, s + hp + h elif i == 5: # bottom c = s + w0 - w, s + h0, s + w0, s + h0 + h elif i == 6: # bottom left c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h elif i == 7: # left c = s - w, s + h0 - h, s, s + h0 elif i == 8: # top left c = s - w, s + h0 - hp - h, s, s + h0 - hp padx, pady = c[:2] x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords # Labels labels, segments = self.labels[index].copy(), self.segments[index].copy() if labels.size: labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format segments = [xyn2xy(x, w, h, padx, pady) for x in segments] labels9.append(labels) segments9.extend(segments) # Image img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax] hp, wp = h, w # height, width previous # Offset yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s] # Concat/clip labels labels9 = np.concatenate(labels9, 0) labels9[:, [1, 3]] -= xc labels9[:, [2, 4]] -= yc c = np.array([xc, yc]) # centers segments9 = [x - c for x in segments9] for x in (labels9[:, 1:], *segments9): np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() # img9, labels9 = replicate(img9, labels9) # replicate # Augment img9, labels9 = random_perspective(img9, labels9, segments9, degrees=self.hyp['degrees'], translate=self.hyp['translate'], scale=self.hyp['scale'], shear=self.hyp['shear'], perspective=self.hyp['perspective'], border=self.mosaic_border) # border to remove return img9, labels9 def replicate(img, labels): # Replicate labels h, w = img.shape[:2] boxes = labels[:, 1:].astype(int) x1, y1, x2, y2 = boxes.T s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels) for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices x1b, y1b, x2b, y2b = boxes[i] bh, bw = y2b - y1b, x2b - x1b yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh] img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0) return img, labels def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32): # Resize and pad image while meeting stride-multiple constraints shape = img.shape[:2] # current shape [height, width] if isinstance(new_shape, int): new_shape = (new_shape, new_shape) # Scale ratio (new / old) r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) if not scaleup: # only scale down, do not scale up (for better test mAP) r = min(r, 1.0) # Compute padding ratio = r, r # width, height ratios new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding if auto: # minimum rectangle dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding elif scaleFill: # stretch dw, dh = 0.0, 0.0 new_unpad = (new_shape[1], new_shape[0]) ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios dw /= 2 # divide padding into 2 sides dh /= 2 if shape[::-1] != new_unpad: # resize img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR) top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border return img, ratio, (dw, dh) def random_perspective(img, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0, border=(0, 0)): # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10)) # targets = [cls, xyxy] height = img.shape[0] + border[0] * 2 # shape(h,w,c) width = img.shape[1] + border[1] * 2 # Center C = np.eye(3) C[0, 2] = -img.shape[1] / 2 # x translation (pixels) C[1, 2] = -img.shape[0] / 2 # y translation (pixels) # Perspective P = np.eye(3) P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y) P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x) # Rotation and Scale R = np.eye(3) a = random.uniform(-degrees, degrees) # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations s = random.uniform(1 - scale, 1 + scale) # s = 2 ** random.uniform(-scale, scale) R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s) # Shear S = np.eye(3) S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg) S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg) # Translation T = np.eye(3) T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels) T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels) # Combined rotation matrix M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed if perspective: img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114)) else: # affine img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114)) # Visualize # import matplotlib.pyplot as plt # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel() # ax[0].imshow(img[:, :, ::-1]) # base # ax[1].imshow(img2[:, :, ::-1]) # warped # Transform label coordinates n = len(targets) if n: use_segments = any(x.any() for x in segments) new = np.zeros((n, 4)) if use_segments: # warp segments segments = resample_segments(segments) # upsample for i, segment in enumerate(segments): xy = np.ones((len(segment), 3)) xy[:, :2] = segment xy = xy @ M.T # transform xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine # clip new[i] = segment2box(xy, width, height) else: # warp boxes xy = np.ones((n * 4, 3)) xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1 xy = xy @ M.T # transform xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine # create new boxes x = xy[:, [0, 2, 4, 6]] y = xy[:, [1, 3, 5, 7]] new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T # clip new[:, [0, 2]] = new[:, [0, 2]].clip(0, width) new[:, [1, 3]] = new[:, [1, 3]].clip(0, height) # filter candidates i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10) targets = targets[i] targets[:, 1:5] = new[i] return img, targets def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n) # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio w1, h1 = box1[2] - box1[0], box1[3] - box1[1] w2, h2 = box2[2] - box2[0], box2[3] - box2[1] ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates def cutout(image, labels): # Applies image cutout augmentation https://arxiv.org/abs/1708.04552 h, w = image.shape[:2] def bbox_ioa(box1, box2): # Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2 box2 = box2.transpose() # Get the coordinates of bounding boxes b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] # Intersection area inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \ (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0) # box2 area box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16 # Intersection over box2 area return inter_area / box2_area # create random masks scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction for s in scales: mask_h = random.randint(1, int(h * s)) mask_w = random.randint(1, int(w * s)) # box xmin = max(0, random.randint(0, w) - mask_w // 2) ymin = max(0, random.randint(0, h) - mask_h // 2) xmax = min(w, xmin + mask_w) ymax = min(h, ymin + mask_h) # apply random color mask image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)] # return unobscured labels if len(labels) and s > 0.03: box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32) ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area labels = labels[ioa < 0.60] # remove >60% obscured labels return labels def create_folder(path='./new'): # Create folder if os.path.exists(path): shutil.rmtree(path) # delete output folder os.makedirs(path) # make new output folder def flatten_recursive(path='../coco128'): # Flatten a recursive directory by bringing all files to top level new_path = Path(path + '_flat') create_folder(new_path) for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)): shutil.copyfile(file, new_path / Path(file).name) def extract_boxes(path='../coco128/'): # from utils.datasets import *; extract_boxes('../coco128') # Convert detection dataset into classification dataset, with one directory per class path = Path(path) # images dir shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing files = list(path.rglob('*.*')) n = len(files) # number of files for im_file in tqdm(files, total=n): if im_file.suffix[1:] in img_formats: # image im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB h, w = im.shape[:2] # labels lb_file = Path(img2label_paths([str(im_file)])[0]) if Path(lb_file).exists(): with open(lb_file, 'r') as f: lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels for j, x in enumerate(lb): c = int(x[0]) # class f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename if not f.parent.is_dir(): f.parent.mkdir(parents=True) b = x[1:] * [w, h, w, h] # box # b[2:] = b[2:].max() # rectangle to square b[2:] = b[2:] * 1.2 + 3 # pad b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image b[[1, 3]] = np.clip(b[[1, 3]], 0, h) assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}' def autosplit(path='../coco128', weights=(0.9, 0.1, 0.0)): # from utils.datasets import *; autosplit('../coco128') """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files # Arguments path: Path to images directory weights: Train, val, test weights (list) """ path = Path(path) # images dir files = list(path.rglob('*.*')) n = len(files) # number of files indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files [(path / x).unlink() for x in txt if (path / x).exists()] # remove existing for i, img in tqdm(zip(indices, files), total=n): if img.suffix[1:] in img_formats: with open(path / txt[i], 'a') as f: f.write(str(img) + '\n') # add image to txt file
parallel_runner.py
from envs import REGISTRY as env_REGISTRY from functools import partial from components.episode_buffer import EpisodeBatch from multiprocessing import Pipe, Process import numpy as np import torch as th # Based (very) heavily on SubprocVecEnv from OpenAI Baselines # https://github.com/openai/baselines/blob/master/baselines/common/vec_env/subproc_vec_env.py class ParallelRunner: def __init__(self, args, logger): self.args = args self.logger = logger self.batch_size = self.args.batch_size_run # Make subprocesses for the envs self.parent_conns, self.worker_conns = zip(*[Pipe() for _ in range(self.batch_size)]) env_fn = env_REGISTRY[self.args.env] self.ps = [Process(target=env_worker, args=(worker_conn, CloudpickleWrapper(partial(env_fn, **self.args.env_args)))) for worker_conn in self.worker_conns] for p in self.ps: p.daemon = True p.start() self.parent_conns[0].send(("get_env_info", None)) self.env_info = self.parent_conns[0].recv() self.episode_limit = self.env_info["episode_limit"] self.t = 0 self.t_env = 0 self.train_returns = [] self.test_returns = [] self.train_stats = {} self.test_stats = {} self.log_train_stats_t = -100000 def setup(self, scheme, groups, preprocess, mac): self.new_batch = partial(EpisodeBatch, scheme, groups, self.batch_size, self.episode_limit + 1, preprocess=preprocess, device=self.args.device) self.mac = mac self.scheme = scheme self.groups = groups self.preprocess = preprocess def get_env_info(self): return self.env_info def save_replay(self): pass def set_learner(self, learner): return def close_env(self): for parent_conn in self.parent_conns: parent_conn.send(("close", None)) def reset(self): self.batch = self.new_batch() # Reset the envs for parent_conn in self.parent_conns: parent_conn.send(("reset", None)) pre_transition_data = { "state": [], "avail_actions": [], "obs": [] } # Get the obs, state and avail_actions back for parent_conn in self.parent_conns: data = parent_conn.recv() pre_transition_data["state"].append(data["state"]) pre_transition_data["avail_actions"].append(data["avail_actions"]) pre_transition_data["obs"].append(data["obs"]) self.batch.update(pre_transition_data, ts=0) self.t = 0 self.env_steps_this_run = 0 def run(self, test_mode=False): self.reset() all_terminated = False episode_returns = [0 for _ in range(self.batch_size)] episode_lengths = [0 for _ in range(self.batch_size)] self.mac.init_hidden(batch_size=self.batch_size) terminated = [False for _ in range(self.batch_size)] envs_not_terminated = [b_idx for b_idx, termed in enumerate(terminated) if not termed] final_env_infos = [] # may store extra stats like battle won. this is filled in ORDER OF TERMINATION while True: # Pass the entire batch of experiences up till now to the agents # Receive the actions for each agent at this timestep in a batch for each un-terminated env actions = self.mac.select_actions(self.batch, t_ep=self.t, t_env=self.t_env, bs=envs_not_terminated, test_mode=test_mode) cpu_actions = actions.to("cpu").numpy() # Update the actions taken actions_chosen = { "actions": actions.unsqueeze(1) } self.batch.update(actions_chosen, bs=envs_not_terminated, ts=self.t, mark_filled=False) # Send actions to each env action_idx = 0 for idx, parent_conn in enumerate(self.parent_conns): if idx in envs_not_terminated: # We produced actions for this env if not terminated[idx]: # Only send the actions to the env if it hasn't terminated parent_conn.send(("step", cpu_actions[action_idx])) action_idx += 1 # actions is not a list over every env # Update envs_not_terminated envs_not_terminated = [b_idx for b_idx, termed in enumerate(terminated) if not termed] all_terminated = all(terminated) if all_terminated: break # Post step data we will insert for the current timestep post_transition_data = { "reward": [], "terminated": [] } # Data for the next step we will insert in order to select an action pre_transition_data = { "state": [], "avail_actions": [], "obs": [] } # Receive data back for each unterminated env for idx, parent_conn in enumerate(self.parent_conns): if not terminated[idx]: data = parent_conn.recv() # Remaining data for this current timestep post_transition_data["reward"].append((data["reward"],)) episode_returns[idx] += data["reward"] episode_lengths[idx] += 1 if not test_mode: self.env_steps_this_run += 1 env_terminated = False if data["terminated"]: final_env_infos.append(data["info"]) if data["terminated"] and not data["info"].get("episode_limit", False): env_terminated = True terminated[idx] = data["terminated"] post_transition_data["terminated"].append((env_terminated,)) # Data for the next timestep needed to select an action pre_transition_data["state"].append(data["state"]) pre_transition_data["avail_actions"].append(data["avail_actions"]) pre_transition_data["obs"].append(data["obs"]) # Add post_transiton data into the batch self.batch.update(post_transition_data, bs=envs_not_terminated, ts=self.t, mark_filled=False) # Move onto the next timestep self.t += 1 # Add the pre-transition data self.batch.update(pre_transition_data, bs=envs_not_terminated, ts=self.t, mark_filled=True) if not test_mode: self.t_env += self.env_steps_this_run # Get stats back for each env for parent_conn in self.parent_conns: parent_conn.send(("get_stats",None)) env_stats = [] for parent_conn in self.parent_conns: env_stat = parent_conn.recv() env_stats.append(env_stat) cur_stats = self.test_stats if test_mode else self.train_stats cur_returns = self.test_returns if test_mode else self.train_returns log_prefix = "test_" if test_mode else "" infos = [cur_stats] + final_env_infos cur_stats.update({k: sum(d.get(k, 0) for d in infos) for k in set.union(*[set(d) for d in infos])}) cur_stats["n_episodes"] = self.batch_size + cur_stats.get("n_episodes", 0) cur_stats["ep_length"] = sum(episode_lengths) + cur_stats.get("ep_length", 0) cur_returns.extend(episode_returns) n_test_runs = max(1, self.args.test_nepisode // self.batch_size) * self.batch_size if test_mode and (len(self.test_returns) == n_test_runs): self._log(cur_returns, cur_stats, log_prefix) elif self.t_env - self.log_train_stats_t >= self.args.runner_log_interval: self._log(cur_returns, cur_stats, log_prefix) if hasattr(self.mac.action_selector, "epsilon"): self.logger.log_stat("epsilon", self.mac.action_selector.epsilon, self.t_env) self.log_train_stats_t = self.t_env return self.batch def _log(self, returns, stats, prefix): self.logger.log_stat(prefix + "return_mean", np.mean(returns), self.t_env) self.logger.log_stat(prefix + "return_std", np.std(returns), self.t_env) returns.clear() for k, v in stats.items(): if k != "n_episodes": self.logger.log_stat(prefix + k + "_mean" , v/stats["n_episodes"], self.t_env) stats.clear() def env_worker(remote, env_fn): # Make environment env = env_fn.x() while True: cmd, data = remote.recv() if cmd == "step": actions = data # Take a step in the environment reward, terminated, env_info = env.step(actions) # Return the observations, avail_actions and state to make the next action state = env.get_state() avail_actions = env.get_avail_actions() obs = env.get_obs() remote.send({ # Data for the next timestep needed to pick an action "state": state, "avail_actions": avail_actions, "obs": obs, # Rest of the data for the current timestep "reward": reward, "terminated": terminated, "info": env_info }) elif cmd == "reset": env.reset() remote.send({ "state": env.get_state(), "avail_actions": env.get_avail_actions(), "obs": env.get_obs() }) elif cmd == "close": env.close() remote.close() break elif cmd == "get_env_info": remote.send(env.get_env_info()) elif cmd == "get_stats": remote.send(env.get_stats()) else: raise NotImplementedError class CloudpickleWrapper(): """ Uses cloudpickle to serialize contents (otherwise multiprocessing tries to use pickle) """ def __init__(self, x): self.x = x def __getstate__(self): import cloudpickle return cloudpickle.dumps(self.x) def __setstate__(self, ob): import pickle self.x = pickle.loads(ob)
datasets.py
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Dataloaders and dataset utils """ import glob import hashlib import json import logging import os import random import shutil import time from itertools import repeat from multiprocessing.pool import Pool, ThreadPool from pathlib import Path from threading import Thread import albumentations as A import cv2 import numpy as np import torch import torch.nn.functional as F import yaml ####################################### # TODO: ImbalancedDatasetSampler, bbox-cutmix 추가 from custom.imbalanced import ImbalancedDatasetSampler from PIL import ExifTags, Image from torch.utils.data import Dataset from tqdm import tqdm from utils.augmentations import ( Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective, ) from utils.general import ( check_dataset, check_requirements, check_yaml, clean_str, segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn, ) from utils.torch_utils import torch_distributed_zero_first ####################################### # Parameters HELP_URL = "https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data" IMG_FORMATS = [ "bmp", "jpg", "jpeg", "png", "tif", "tiff", "dng", "webp", "mpo", ] # acceptable image suffixes VID_FORMATS = [ "mov", "avi", "mp4", "mpg", "mpeg", "m4v", "wmv", "mkv", ] # acceptable video suffixes NUM_THREADS = min(8, os.cpu_count()) # number of multiprocessing threads # Get orientation exif tag for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == "Orientation": break def get_hash(paths): # Returns a single hash value of a list of paths (files or dirs) size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes h = hashlib.md5(str(size).encode()) # hash sizes h.update("".join(paths).encode()) # hash paths return h.hexdigest() # return hash def exif_size(img): # Returns exif-corrected PIL size s = img.size # (width, height) try: rotation = dict(img._getexif().items())[orientation] if rotation == 6: # rotation 270 s = (s[1], s[0]) elif rotation == 8: # rotation 90 s = (s[1], s[0]) except: pass return s def exif_transpose(image): """ Transpose a PIL image accordingly if it has an EXIF Orientation tag. From https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py :param image: The image to transpose. :return: An image. """ exif = image.getexif() orientation = exif.get(0x0112, 1) # default 1 if orientation > 1: method = { 2: Image.FLIP_LEFT_RIGHT, 3: Image.ROTATE_180, 4: Image.FLIP_TOP_BOTTOM, 5: Image.TRANSPOSE, 6: Image.ROTATE_270, 7: Image.TRANSVERSE, 8: Image.ROTATE_90, }.get(orientation) if method is not None: image = image.transpose(method) del exif[0x0112] image.info["exif"] = exif.tobytes() return image def create_dataloader( path, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0, rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix="", save_dir=None, ): # Make sure only the first process in DDP process the dataset first, and the following others can use the cache with torch_distributed_zero_first(rank): dataset = LoadImagesAndLabels( path, imgsz, batch_size, augment=augment, # augment images hyp=hyp, # augmentation hyperparameters rect=rect, # rectangular training cache_images=cache, single_cls=single_cls, stride=int(stride), pad=pad, image_weights=image_weights, prefix=prefix, dist=rank, save_dir=save_dir, ) # TODO: dataset mapping # dataset.share_memory() # import torch.distributed as dist # dist.barrier() batch_size = min(batch_size, len(dataset)) nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, workers]) # number of workers ####################################### # TODO: ImbalancedDatasetSampler 추가 if hyp is None: sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None else: sampler = ( torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else ImbalancedDatasetSampler(dataset) if hyp["imbalanced"] and augment else None ) ####################################### loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader() dataloader = loader( dataset, batch_size=batch_size, num_workers=nw, sampler=sampler, pin_memory=True, collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn, ) return dataloader, dataset class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader): """Dataloader that reuses workers Uses same syntax as vanilla DataLoader """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) object.__setattr__(self, "batch_sampler", _RepeatSampler(self.batch_sampler)) self.iterator = super().__iter__() def __len__(self): return len(self.batch_sampler.sampler) def __iter__(self): for i in range(len(self)): yield next(self.iterator) class _RepeatSampler(object): """Sampler that repeats forever Args: sampler (Sampler) """ def __init__(self, sampler): self.sampler = sampler def __iter__(self): while True: yield from iter(self.sampler) class LoadImages: # for inference def __init__(self, path, img_size=640, stride=32, auto=True): p = str(Path(path).resolve()) # os-agnostic absolute path if "*" in p: files = sorted(glob.glob(p, recursive=True)) # glob elif os.path.isdir(p): files = sorted(glob.glob(os.path.join(p, "*.*"))) # dir elif os.path.isfile(p): files = [p] # files else: raise Exception(f"ERROR: {p} does not exist") images = [x for x in files if x.split(".")[-1].lower() in IMG_FORMATS] videos = [x for x in files if x.split(".")[-1].lower() in VID_FORMATS] ni, nv = len(images), len(videos) self.img_size = img_size self.stride = stride self.files = images + videos self.nf = ni + nv # number of files self.video_flag = [False] * ni + [True] * nv self.mode = "image" self.auto = auto if any(videos): self.new_video(videos[0]) # new video else: self.cap = None assert self.nf > 0, ( f"No images or videos found in {p}. " f"Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}" ) def __iter__(self): self.count = 0 return self def __next__(self): if self.count == self.nf: raise StopIteration path = self.files[self.count] if self.video_flag[self.count]: # Read video self.mode = "video" ret_val, img0 = self.cap.read() if not ret_val: self.count += 1 self.cap.release() if self.count == self.nf: # last video raise StopIteration else: path = self.files[self.count] self.new_video(path) ret_val, img0 = self.cap.read() self.frame += 1 print( f"video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ", end="" ) else: # Read image self.count += 1 img0 = cv2.imread(path) # BGR assert img0 is not None, "Image Not Found " + path print(f"image {self.count}/{self.nf} {path}: ", end="") # Padded resize img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0] # Convert img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB img = np.ascontiguousarray(img) return path, img, img0, self.cap def new_video(self, path): self.frame = 0 self.cap = cv2.VideoCapture(path) self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) def __len__(self): return self.nf # number of files class LoadWebcam: # for inference def __init__(self, pipe="0", img_size=640, stride=32): self.img_size = img_size self.stride = stride self.pipe = eval(pipe) if pipe.isnumeric() else pipe self.cap = cv2.VideoCapture(self.pipe) # video capture object self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size def __iter__(self): self.count = -1 return self def __next__(self): self.count += 1 if cv2.waitKey(1) == ord("q"): # q to quit self.cap.release() cv2.destroyAllWindows() raise StopIteration # Read frame ret_val, img0 = self.cap.read() img0 = cv2.flip(img0, 1) # flip left-right # Print assert ret_val, f"Camera Error {self.pipe}" img_path = "webcam.jpg" print(f"webcam {self.count}: ", end="") # Padded resize img = letterbox(img0, self.img_size, stride=self.stride)[0] # Convert img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB img = np.ascontiguousarray(img) return img_path, img, img0, None def __len__(self): return 0 class LoadStreams: # multiple IP or RTSP cameras def __init__(self, sources="streams.txt", img_size=640, stride=32, auto=True): self.mode = "stream" self.img_size = img_size self.stride = stride if os.path.isfile(sources): with open(sources, "r") as f: sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())] else: sources = [sources] n = len(sources) self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n self.sources = [clean_str(x) for x in sources] # clean source names for later self.auto = auto for i, s in enumerate(sources): # index, source # Start thread to read frames from video stream print(f"{i + 1}/{n}: {s}... ", end="") if "youtube.com/" in s or "youtu.be/" in s: # if source is YouTube video check_requirements(("pafy", "youtube_dl")) import pafy s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam cap = cv2.VideoCapture(s) assert cap.isOpened(), f"Failed to open {s}" w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) self.fps[i] = max(cap.get(cv2.CAP_PROP_FPS) % 100, 0) or 30.0 # 30 FPS fallback self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float( "inf" ) # infinite stream fallback _, self.imgs[i] = cap.read() # guarantee first frame self.threads[i] = Thread(target=self.update, args=([i, cap]), daemon=True) print(f" success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)") self.threads[i].start() print("") # newline # check for common shapes s = np.stack( [ letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs ] ) self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal if not self.rect: print( "WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams." ) def update(self, i, cap): # Read stream `i` frames in daemon thread n, f, read = ( 0, self.frames[i], 1, ) # frame number, frame array, inference every 'read' frame while cap.isOpened() and n < f: n += 1 # _, self.imgs[index] = cap.read() cap.grab() if n % read == 0: success, im = cap.retrieve() self.imgs[i] = im if success else self.imgs[i] * 0 time.sleep(1 / self.fps[i]) # wait time def __iter__(self): self.count = -1 return self def __next__(self): self.count += 1 if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord("q"): # q to quit cv2.destroyAllWindows() raise StopIteration # Letterbox img0 = self.imgs.copy() img = [ letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0 ] # Stack img = np.stack(img, 0) # Convert img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW img = np.ascontiguousarray(img) return self.sources, img, img0, None def __len__(self): return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years def img2label_paths(img_paths): # Define label paths as a function of image paths sa, sb = ( os.sep + "images" + os.sep, os.sep + "labels" + os.sep, ) # /images/, /labels/ substrings return [sb.join(x.rsplit(sa, 1)).rsplit(".", 1)[0] + ".txt" for x in img_paths] class LoadImagesAndLabels(Dataset): # for training/testing def __init__( self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False, cache_images=False, single_cls=False, stride=32, pad=0.0, prefix="", dist=-1, save_dir=None, ): self.img_size = img_size self.augment = augment self.hyp = hyp self.image_weights = image_weights self.rect = False if image_weights else rect self.mosaic = ( self.augment and not self.rect ) # load 4 images at a time into a mosaic (only during training) self.mosaic_border = [-img_size // 2, -img_size // 2] self.stride = stride self.path = path self.albumentations = Albumentations() if augment else None self.save_dir = save_dir try: f = [] # image files for p in path if isinstance(path, list) else [path]: p = Path(p) # os-agnostic if p.is_dir(): # dir f += glob.glob(str(p / "**" / "*.*"), recursive=True) # f = list(p.rglob('**/*.*')) # pathlib elif p.is_file(): # file with open(p, "r") as t: t = t.read().strip().splitlines() parent = str(p.parent) + os.sep f += [ x.replace("./", parent) if x.startswith("./") else x for x in t ] # local to global path # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib) else: raise Exception(f"{prefix}{p} does not exist") self.img_files = sorted( [x.replace("/", os.sep) for x in f if x.split(".")[-1].lower() in IMG_FORMATS] ) # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib assert self.img_files, f"{prefix}No images found" except Exception as e: raise Exception(f"{prefix}Error loading data from {path}: {e}\nSee {HELP_URL}") # Check cache self.label_files = img2label_paths(self.img_files) # labels cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix(".cache") ####################################### # TODO: cache 삭제 - 데이터셋 충돌 방지 if os.path.exists(cache_path): os.remove(cache_path) ####################################### try: cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict assert cache["version"] == 0.4 and cache["hash"] == get_hash( self.label_files + self.img_files ) except: cache, exists = self.cache_labels(cache_path, prefix), False # cache # Display cache nf, nm, ne, nc, n = cache.pop("results") # found, missing, empty, corrupted, total if exists: d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted" tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results if cache["msgs"]: logging.info("\n".join(cache["msgs"])) # display warnings assert ( nf > 0 or not augment ), f"{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}" # Read cache [cache.pop(k) for k in ("hash", "version", "msgs")] # remove items labels, shapes, self.segments = zip(*cache.values()) self.labels = list(labels) self.shapes = np.array(shapes, dtype=np.float64) self.img_files = list(cache.keys()) # update self.label_files = img2label_paths(cache.keys()) # update if single_cls: for x in self.labels: x[:, 0] = 0 n = len(shapes) # number of images bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index nb = bi[-1] + 1 # number of batches self.batch = bi # batch index of image self.n = n self.indices = range(n) # Rectangular Training if self.rect: # Sort by aspect ratio s = self.shapes # wh ar = s[:, 1] / s[:, 0] # aspect ratio irect = ar.argsort() self.img_files = [self.img_files[i] for i in irect] self.label_files = [self.label_files[i] for i in irect] self.labels = [self.labels[i] for i in irect] self.shapes = s[irect] # wh ar = ar[irect] # Set training image shapes shapes = [[1, 1]] * nb for i in range(nb): ari = ar[bi == i] mini, maxi = ari.min(), ari.max() if maxi < 1: shapes[i] = [maxi, 1] elif mini > 1: shapes[i] = [1, 1 / mini] self.batch_shapes = ( np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride ) # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM) self.imgs, self.img_npy = [None] * n, [None] * n if cache_images: # if cache_images == 'disk': # self.im_cache_dir = Path(Path(self.img_files[0]).parent.as_posix() + '_npy') # self.img_npy = [self.im_cache_dir / Path(f).with_suffix('.npy').name for f in self.img_files] # self.im_cache_dir.mkdir(parents=True, exist_ok=True) gb = 0 # Gigabytes of cached images self.img_hw0, self.img_hw = [None] * n, [None] * n results = ThreadPool(NUM_THREADS).imap( lambda x: load_image(*x), zip(repeat(self), range(n)) ) pbar = tqdm(enumerate(results), total=n) for i, x in pbar: if cache_images == "disk": pass # if not self.img_npy[i].exists(): # np.save(self.img_npy[i].as_posix(), x[0]) # gb += self.img_npy[i].stat().st_size else: ( self.imgs[i], self.img_hw0[i], self.img_hw[i], ) = x # im, hw_orig, hw_resized = load_image(self, i) gb += self.imgs[i].nbytes pbar.desc = f"{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})" pbar.close() def cache_labels(self, path=Path("./labels.cache"), prefix=""): # Cache dataset labels, check images and read shapes x = {} # dict nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..." with Pool(NUM_THREADS) as pool: pbar = tqdm( pool.imap_unordered( verify_image_label, zip(self.img_files, self.label_files, repeat(prefix)) ), desc=desc, total=len(self.img_files), ) for im_file, l, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar: nm += nm_f nf += nf_f ne += ne_f nc += nc_f if im_file: x[im_file] = [l, shape, segments] if msg: msgs.append(msg) pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupted" pbar.close() if msgs: logging.info("\n".join(msgs)) if nf == 0: logging.info(f"{prefix}WARNING: No labels found in {path}. See {HELP_URL}") x["hash"] = get_hash(self.label_files + self.img_files) x["results"] = nf, nm, ne, nc, len(self.img_files) x["msgs"] = msgs # warnings x["version"] = 0.4 # cache version try: np.save(path, x) # save cache for next time path.with_suffix(".cache.npy").rename(path) # remove .npy suffix logging.info(f"{prefix}New cache created: {path}") except Exception as e: logging.info( f"{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}" ) # path not writeable return x def __len__(self): return len(self.img_files) # def __iter__(self): # self.count = -1 # print('ran dataset iter') # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF) # return self def __getitem__(self, index): index = self.indices[index] # linear, shuffled, or image_weights hyp = self.hyp mosaic = self.mosaic and random.random() < hyp["mosaic"] if mosaic: # Load mosaic img, labels = load_mosaic(self, index) shapes = None # MixUp augmentation if random.random() < hyp["mixup"]: img, labels = mixup(img, labels, *load_mosaic(self, random.randint(0, self.n - 1))) else: # Load image img, (h0, w0), (h, w) = load_image(self, index) ####################################### # TODO: bbox-cutmix augmentation labels = self.labels[index].copy() if hyp is not None: if hyp["bbox_cutmix"] and self.augment: img, labels = bbox_cutmix(self, img, labels, h, w, index) ####################################### # Letterbox shape = ( self.batch_shapes[self.batch[index]] if self.rect else self.img_size ) # final letterboxed shape img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment) shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling # labels = self.labels[index].copy() if labels.size: # normalized xywh to pixel xyxy format labels[:, 1:] = xywhn2xyxy( labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1] ) if self.augment: img, labels = random_perspective( img, labels, degrees=hyp["degrees"], translate=hyp["translate"], scale=hyp["scale"], shear=hyp["shear"], perspective=hyp["perspective"], ) nl = len(labels) # number of labels if nl: labels[:, 1:5] = xyxy2xywhn( labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1e-3 ) if self.augment: # Albumentations if random.random() < hyp["more_aug"]: img, labels = self.albumentations(img, labels) nl = len(labels) # update after albumentations # HSV color-space augment_hsv(img, hgain=hyp["hsv_h"], sgain=hyp["hsv_s"], vgain=hyp["hsv_v"]) # Flip up-down if random.random() < hyp["flipud"]: img = np.flipud(img) if nl: labels[:, 2] = 1 - labels[:, 2] # Flip left-right if random.random() < hyp["fliplr"]: img = np.fliplr(img) if nl: labels[:, 1] = 1 - labels[:, 1] # Cutouts # labels = cutout(img, labels, p=0.5) labels_out = torch.zeros((nl, 6)) if nl: labels_out[:, 1:] = torch.from_numpy(labels) # Convert img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB img = np.ascontiguousarray(img) return torch.from_numpy(img), labels_out, self.img_files[index], shapes @staticmethod def collate_fn(batch): img, label, path, shapes = zip(*batch) # transposed for i, l in enumerate(label): l[:, 0] = i # add target image index for build_targets() return torch.stack(img, 0), torch.cat(label, 0), path, shapes @staticmethod def collate_fn4(batch): img, label, path, shapes = zip(*batch) # transposed n = len(shapes) // 4 img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n] ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]]) wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]]) s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]]) # scale for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW i *= 4 if random.random() < 0.5: im = F.interpolate( img[i].unsqueeze(0).float(), scale_factor=2.0, mode="bilinear", align_corners=False, )[0].type(img[i].type()) l = label[i] else: im = torch.cat( (torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2 ) l = ( torch.cat( (label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0 ) * s ) img4.append(im) label4.append(l) for i, l in enumerate(label4): l[:, 0] = i # add target image index for build_targets() return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4 # Ancillary functions -------------------------------------------------------------------------------------------------- ######################################################################### def save_image(obj, lb, name, p=None): h = obj.shape[0] w = obj.shape[1] img = obj.copy() if p is not None: for bbox in p: img = cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2) if lb is not None: for bbox in lb: bbox = [ 0, (bbox[1] - bbox[3] / 2) * w, (bbox[2] - bbox[4] / 2) * h, bbox[3] * w, bbox[4] * h, ] bbox = [int(x) for x in bbox] img = cv2.rectangle( img, (bbox[1], bbox[2]), (bbox[1] + bbox[3], bbox[2] + bbox[4]), (0, 0, 255), 2 ) else: if lb is not None: lb = [int(x) for x in lb] img = cv2.rectangle( img, (lb[1], lb[2]), (lb[1] + lb[3], lb[2] + lb[4]), (0, 0, 255), 2 ) cv2.imwrite(f"{name}.jpg", img) def bbox_cutmix(self, img, labels, h, w, index): # for logging os.makedirs(f"{self.save_dir}/img", exist_ok=True) # lables = [class, x,y,w,h] # h, w = height, width of img xmin = int(min(labels[:, 1] - labels[:, 3] / 2) * w) xmax = int(max(labels[:, 1] + labels[:, 3] / 2) * w) ymin = int(min(labels[:, 2] - labels[:, 4] / 2) * h) ymax = int(max(labels[:, 2] + labels[:, 4] / 2) * h) # crop-obj 넣을 빈 공간, 8곳 # 1 2 3 # 4 5 6 # 7 8 9 Position = [ [0, 0, xmin, ymin], # 1 [xmin, 0, xmax, ymin], # 2 [xmax, 0, w, ymin], # 3 [0, ymin, xmin, ymax], # 4 # 5는 실제 obj [xmax, ymin, w, ymax], # 6 [0, ymax, xmin, h], # 7 [xmin, ymax, xmax, h], # 8 [xmax, ymax, w, h], # 9 ] # 구역마다 이미지 넣기 for p in Position: if torch.rand(1) > 0.7: # crop aug 확률 추가 continue # 1. crop-obj 생성 load_idx = torch.randint(len(self.indices), (1,)).item() # crop할 이미지 선정 load_img, a, (h_l, w_l) = load_image(self, load_idx) try: lb = self.labels[load_idx].copy()[ torch.randint(len(self.labels[load_idx]), (1,)).item() ] except: print("-" * 30) print(">> bbox_cutmix - index error") print(f" - load index : {load_idx}") print(f" - label : {self.labels[load_idx]}") print(f" - file path : {self.img_files[load_idx]}") print("-" * 30) exit() xmin_load = int((lb[1] - lb[3] / 2) * w_l) xmax_load = int((lb[1] + lb[3] / 2) * w_l) ymin_load = int((lb[2] - lb[4] / 2) * h_l) ymax_load = int((lb[2] + lb[4] / 2) * h_l) # 랜덤 크기의 offset 생성(4방향 다 다름) offset = torch.randint( low=int(self.img_size / 40), high=int(self.img_size / 20), size=(4,) ).numpy() offset_xmin = np.clip(min(xmin_load, offset[0]), 0, offset[0]) offset_xmax = np.clip(min(w_l - xmax_load, offset[1]), 0, offset[1]) offset_ymin = np.clip(min(ymin_load, offset[2]), 0, offset[2]) offset_ymax = np.clip(min(h_l - ymax_load, offset[3]), 0, offset[3]) # normalize of load_img # 실제 crop된 이미지 cropped_object = load_img[ ymin_load - offset_ymin : ymax_load + offset_ymax, xmin_load - offset_xmin : xmax_load + offset_xmax, ].copy() # crop-object 크기 height = cropped_object.shape[0] width = cropped_object.shape[1] # crop 되기 전,후 크기 비율 곱 # class, x, y, w, h cropped_label = [ lb[0], offset_xmin, offset_ymin, xmax_load - xmin_load, ymax_load - ymin_load, ] # bbox check # self.save_image(img.copy(), None, f'img/{index}_input') # self.save_image(cropped_object, cropped_label, f'img/{load_idx}_crop_1') # 2. crop-obj albumentations # FIXME:augment 추가 여부 # crop-obj augmentation album_aug = A.Compose( [ A.HorizontalFlip(p=0.7), A.VerticalFlip(p=0.7), A.ColorJitter(p=0.7), A.ShiftScaleRotate(shift_limit=0.01, scale_limit=0.1, rotate_limit=5, p=0.7), A.RandomRotate90(p=0.7), ], bbox_params=A.BboxParams( format="coco", label_fields=["class_labels"], min_visibility=0.5 ), ) try: transformed = album_aug( image=cropped_object, bboxes=[cropped_label[1:]], class_labels=[cropped_label[0]] ) except: print("-" * 30) print(">> bbox_cutmix - aug error") print(f" - bbox coord : {cropped_label[1:]}") print(f" - bbox size(HxW) : {lb[4]*h_l} x {lb[3]*w_l}") print(f" - image size(HxW) : {height} x {width}") print(f" - label : {self.labels[load_idx]}") print(f" - file path : {self.img_files[load_idx]}") print("-" * 30) save_image(cropped_object, cropped_label, f"{self.save_dir}/img/error_{load_idx}_aug") continue if len(transformed["class_labels"]) == 0: continue # augment 된 crop-obj cropped_object = transformed["image"] # bboxes = [(x,y,w,h), (x,y,w,h), ... ] # class_labels = [ c, c, ... ] cropped_label = [transformed["class_labels"][0]] + list(transformed["bboxes"][0]) # crop-object 크기 height = cropped_object.shape[0] width = cropped_object.shape[1] # bbox check # self.save_image(cropped_object, cropped_label, f'img/{load_idx}_crop_2_album') # 3. img에 넣을 위치 정하기 x_img = int(0.5 * torch.rand((1,)).item() * (p[2] - p[0])) + p[0] y_img = int(0.5 * torch.rand((1,)).item() * (p[3] - p[1])) + p[1] # 4. crop-aug 된 img 생성 # p구역에 이미지 넣지 못 할 때 if p[2] - x_img <= width or p[3] - y_img <= height: # FIXME:threshold 값 정하기 # 최대 offset 평균 : 200(100x2), min object size : 20 # -> 200 x 200 이상인 경우에만 resize 적용 # -> self.img_size/10 x self.img_size/10 이상인 경우에만 resize 적용 if p[2] - x_img > self.img_size / 10 and p[3] - y_img > self.img_size / 10: # 더 튀어나온 방향 기준으로 scale 정함 scale_rate = min((p[2] - x_img) / width, (p[3] - y_img) / height) album_resize = A.Compose( [A.Resize(int(height * scale_rate), int(width * scale_rate))], bbox_params=A.BboxParams(format="coco", label_fields=["class_labels"]), ) try: transformed = album_resize( image=cropped_object, bboxes=[cropped_label[1:]], class_labels=[cropped_label[0]], ) except: print("-" * 30) print(">> bbox_cutmix - resize error") print(f" - crop coord : {cropped_label[1:]}") print(f" - crop size(HxW) : {cropped_label[4]} x {cropped_label[3]}") print(f" - image size(HxW) : {height} x {width}") print(f" - label : {self.labels[load_idx]}") print(f" - file path : {self.img_files[load_idx]}") print("-" * 30) save_image( cropped_object, cropped_label, f"{self.save_dir}/img/error_{load_idx}_resize", ) continue # resize 된 crop-obj cropped_object = transformed["image"] cropped_label = [transformed["class_labels"][0]] + list(transformed["bboxes"][0]) # resize 된 crop-object 크기 height = cropped_object.shape[0] width = cropped_object.shape[1] # bbox check # self.save_image(cropped_object, cropped_label, f'img/{load_idx}_crop_3_resize') # 220 x 220 이하인 경우 다음 구역으로 else: continue # 좌표 수정 # bbox_coords = [0, x_img*w+cropped_label[1], y_img*h+cropped_label[2], cropped_label[3], cropped_label[4]] cropped_label[1] = ( x_img + cropped_label[1] + cropped_label[3] / 2 ) / w # (crop 이미지 넣을 좌표 + offset 크기 + 넓이/2) cropped_label[2] = (y_img + cropped_label[2] + cropped_label[4] / 2) / h cropped_label[3] = cropped_label[3] / w cropped_label[4] = cropped_label[4] / h # label 추가 labels = np.vstack((labels, np.array([cropped_label]))) # img에 crop-obj 삽입 try: img[y_img : y_img + height, x_img : x_img + width] = cropped_object except: print("-" * 30) print(">> bbox_cutmix - paste error") print(f" - crop coord : {cropped_label[1:]}") print(f" - crop size(HxW) : {height} x {width}") print(f" - min point : ({y_img}, {x_img})") print(f" - max point : ({y_img+height}, {x_img+width})") print(f" - image size(HxW) : {img.shape[1]} x {img.shape[0]}") print(f" - label : {self.labels[load_idx]}") print(f" - crop image path : {self.img_files[load_idx]}") print(f" - file path : {self.img_files[index]}") print("-" * 30) save_image( img.copy(), labels, f"{self.save_dir}/img/error_{load_idx}_{index}_paste", p=Position, ) continue # label 추가 # labels = np.vstack((labels, np.array([cropped_label]))) # bbox check if index in range(10, 101, 10): # print("bbox check", img.shape, index) save_image(img.copy(), labels, f"{self.save_dir}/img/monitor_{index}", p=Position) return img, labels ######################################################################### def load_image(self, i): # loads 1 image from dataset index 'i', returns im, original hw, resized hw im = self.imgs[i] if im is None: # not cached in ram # npy = self.img_npy[i] # if npy and npy.exists(): # load npy # im = np.load(npy) # else: # read image # path = self.img_files[i] # im = cv2.imread(path) # BGR # assert im is not None, 'Image Not Found ' + path path = self.img_files[i] im = cv2.imread(path) # BGR assert im is not None, "Image Not Found " + path h0, w0 = im.shape[:2] # orig hw r = self.img_size / max(h0, w0) # ratio if r != 1: # if sizes are not equal im = cv2.resize( im, (int(w0 * r), int(h0 * r)), interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR, ) return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized else: return self.imgs[i].copy(), self.img_hw0[i], self.img_hw[i] # im, hw_original, hw_resized def load_mosaic(self, index): # loads images in a 4-mosaic hyp = self.hyp labels4, segments4 = [], [] s = self.img_size yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices random.shuffle(indices) for i, index in enumerate(indices): # Load image img, _, (h, w) = load_image(self, index) ####################################### # TODO: bbox-cutmix augmentation labels, segments = self.labels[index].copy(), self.segments[index].copy() if hyp is not None: if hyp["bbox_cutmix"] and self.augment: img, labels = bbox_cutmix(self, img, labels, h, w, index) ####################################### # place img in img4 if i == 0: # top left img4 = np.full( (s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8 ) # base image with 4 tiles x1a, y1a, x2a, y2a = ( max(xc - w, 0), max(yc - h, 0), xc, yc, ) # xmin, ymin, xmax, ymax (large image) x1b, y1b, x2b, y2b = ( w - (x2a - x1a), h - (y2a - y1a), w, h, ) # xmin, ymin, xmax, ymax (small image) elif i == 1: # top right x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h elif i == 2: # bottom left x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h) elif i == 3: # bottom right x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] padw = x1a - x1b padh = y1a - y1b # Labels # labels, segments = self.labels[index].copy(), self.segments[index].copy() if labels.size: labels[:, 1:] = xywhn2xyxy( labels[:, 1:], w, h, padw, padh ) # normalized xywh to pixel xyxy format segments = [xyn2xy(x, w, h, padw, padh) for x in segments] labels4.append(labels) segments4.extend(segments) # Concat/clip labels labels4 = np.concatenate(labels4, 0) for x in (labels4[:, 1:], *segments4): np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() # img4, labels4 = replicate(img4, labels4) # replicate # Augment img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp["copy_paste"]) img4, labels4 = random_perspective( img4, labels4, segments4, degrees=self.hyp["degrees"], translate=self.hyp["translate"], scale=self.hyp["scale"], shear=self.hyp["shear"], perspective=self.hyp["perspective"], border=self.mosaic_border, ) # border to remove return img4, labels4 def load_mosaic9(self, index): # loads images in a 9-mosaic hyp = self.hyp labels9, segments9 = [], [] s = self.img_size indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices random.shuffle(indices) for i, index in enumerate(indices): # Load image img, _, (h, w) = load_image(self, index) ####################################### # TODO: bbox-cutmix augmentation labels, segments = self.labels[index].copy(), self.segments[index].copy() if hyp is not None: if hyp["bbox_cutmix"] and self.augment: img, labels = bbox_cutmix(self, img, labels, h, w, index) ####################################### # place img in img9 if i == 0: # center img9 = np.full( (s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8 ) # base image with 4 tiles h0, w0 = h, w c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates elif i == 1: # top c = s, s - h, s + w, s elif i == 2: # top right c = s + wp, s - h, s + wp + w, s elif i == 3: # right c = s + w0, s, s + w0 + w, s + h elif i == 4: # bottom right c = s + w0, s + hp, s + w0 + w, s + hp + h elif i == 5: # bottom c = s + w0 - w, s + h0, s + w0, s + h0 + h elif i == 6: # bottom left c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h elif i == 7: # left c = s - w, s + h0 - h, s, s + h0 elif i == 8: # top left c = s - w, s + h0 - hp - h, s, s + h0 - hp padx, pady = c[:2] x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords # Labels # labels, segments = self.labels[index].copy(), self.segments[index].copy() if labels.size: labels[:, 1:] = xywhn2xyxy( labels[:, 1:], w, h, padx, pady ) # normalized xywh to pixel xyxy format segments = [xyn2xy(x, w, h, padx, pady) for x in segments] labels9.append(labels) segments9.extend(segments) # Image img9[y1:y2, x1:x2] = img[y1 - pady :, x1 - padx :] # img9[ymin:ymax, xmin:xmax] hp, wp = h, w # height, width previous # Offset yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y img9 = img9[yc : yc + 2 * s, xc : xc + 2 * s] # Concat/clip labels labels9 = np.concatenate(labels9, 0) labels9[:, [1, 3]] -= xc labels9[:, [2, 4]] -= yc c = np.array([xc, yc]) # centers segments9 = [x - c for x in segments9] for x in (labels9[:, 1:], *segments9): np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() # img9, labels9 = replicate(img9, labels9) # replicate # Augment img9, labels9 = random_perspective( img9, labels9, segments9, degrees=self.hyp["degrees"], translate=self.hyp["translate"], scale=self.hyp["scale"], shear=self.hyp["shear"], perspective=self.hyp["perspective"], border=self.mosaic_border, ) # border to remove return img9, labels9 def create_folder(path="./new"): # Create folder if os.path.exists(path): shutil.rmtree(path) # delete output folder os.makedirs(path) # make new output folder def flatten_recursive(path="../datasets/coco128"): # Flatten a recursive directory by bringing all files to top level new_path = Path(path + "_flat") create_folder(new_path) for file in tqdm(glob.glob(str(Path(path)) + "/**/*.*", recursive=True)): shutil.copyfile(file, new_path / Path(file).name) def extract_boxes(path="../datasets/coco128"): # from utils.datasets import *; extract_boxes() # Convert detection dataset into classification dataset, with one directory per class path = Path(path) # images dir shutil.rmtree(path / "classifier") if ( path / "classifier" ).is_dir() else None # remove existing files = list(path.rglob("*.*")) n = len(files) # number of files for im_file in tqdm(files, total=n): if im_file.suffix[1:] in IMG_FORMATS: # image im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB h, w = im.shape[:2] # labels lb_file = Path(img2label_paths([str(im_file)])[0]) if Path(lb_file).exists(): with open(lb_file, "r") as f: lb = np.array( [x.split() for x in f.read().strip().splitlines()], dtype=np.float32 ) # labels for j, x in enumerate(lb): c = int(x[0]) # class f = ( (path / "classifier") / f"{c}" / f"{path.stem}_{im_file.stem}_{j}.jpg" ) # new filename if not f.parent.is_dir(): f.parent.mkdir(parents=True) b = x[1:] * [w, h, w, h] # box # b[2:] = b[2:].max() # rectangle to square b[2:] = b[2:] * 1.2 + 3 # pad b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image b[[1, 3]] = np.clip(b[[1, 3]], 0, h) assert cv2.imwrite(str(f), im[b[1] : b[3], b[0] : b[2]]), f"box failure in {f}" def autosplit(path="../datasets/coco128/images", weights=(0.9, 0.1, 0.0), annotated_only=False): """Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files Usage: from utils.datasets import *; autosplit() Arguments path: Path to images directory weights: Train, val, test weights (list, tuple) annotated_only: Only use images with an annotated txt file """ path = Path(path) # images dir files = sum( [list(path.rglob(f"*.{img_ext}")) for img_ext in IMG_FORMATS], [] ) # image files only n = len(files) # number of files random.seed(0) # for reproducibility indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split txt = ["autosplit_train.txt", "autosplit_val.txt", "autosplit_test.txt"] # 3 txt files [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing print( f"Autosplitting images from {path}" + ", using *.txt labeled images only" * annotated_only ) for i, img in tqdm(zip(indices, files), total=n): if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label with open(path.parent / txt[i], "a") as f: f.write( "./" + img.relative_to(path.parent).as_posix() + "\n" ) # add image to txt file def verify_image_label(args): # Verify one image-label pair im_file, lb_file, prefix = args nm, nf, ne, nc, msg, segments = ( 0, 0, 0, 0, "", [], ) # number (missing, found, empty, corrupt), message, segments try: # verify images im = Image.open(im_file) im.verify() # PIL verify shape = exif_size(im) # image size assert (shape[0] > 9) & (shape[1] > 9), f"image size {shape} <10 pixels" assert im.format.lower() in IMG_FORMATS, f"invalid image format {im.format}" if im.format.lower() in ("jpg", "jpeg"): with open(im_file, "rb") as f: f.seek(-2, 2) if f.read() != b"\xff\xd9": # corrupt JPEG pass # Image.open(im_file).save(im_file, format='JPEG', subsampling=0, quality=100) # re-save image # msg = f'{prefix}WARNING: corrupt JPEG restored and saved {im_file}' # verify labels if os.path.isfile(lb_file): nf = 1 # label found with open(lb_file, "r") as f: l = [x.split() for x in f.read().strip().splitlines() if len(x)] if any([len(x) > 8 for x in l]): # is segment classes = np.array([x[0] for x in l], dtype=np.float32) segments = [ np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l ] # (cls, xy1...) l = np.concatenate( (classes.reshape(-1, 1), segments2boxes(segments)), 1 ) # (cls, xywh) l = np.array(l, dtype=np.float32) if len(l): assert l.shape[1] == 5, "labels require 5 columns each" assert (l >= 0).all(), "negative labels" assert (l[:, 1:] <= 1).all(), "non-normalized or out of bounds coordinate labels" assert np.unique(l, axis=0).shape[0] == l.shape[0], "duplicate labels" else: ne = 1 # label empty l = np.zeros((0, 5), dtype=np.float32) else: nm = 1 # label missing l = np.zeros((0, 5), dtype=np.float32) return im_file, l, shape, segments, nm, nf, ne, nc, msg except Exception as e: nc = 1 msg = f"{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}" return [None, None, None, None, nm, nf, ne, nc, msg] def dataset_stats( path="coco128.yaml", autodownload=False, verbose=False, profile=False, hub=False ): """Return dataset statistics dictionary with images and instances counts per split per class To run in parent directory: export PYTHONPATH="$PWD/yolov5" Usage1: from utils.datasets import *; dataset_stats('coco128.yaml', autodownload=True) Usage2: from utils.datasets import *; dataset_stats('../datasets/coco128_with_yaml.zip') Arguments path: Path to data.yaml or data.zip (with data.yaml inside data.zip) autodownload: Attempt to download dataset if not found locally verbose: Print stats dictionary """ def round_labels(labels): # Update labels to integer class and 6 decimal place floats return [[int(c), *[round(x, 4) for x in points]] for c, *points in labels] def unzip(path): # Unzip data.zip TODO: CONSTRAINT: path/to/abc.zip MUST unzip to 'path/to/abc/' if str(path).endswith(".zip"): # path is data.zip assert Path(path).is_file(), f"Error unzipping {path}, file not found" assert os.system(f"unzip -q {path} -d {path.parent}") == 0, f"Error unzipping {path}" dir = path.with_suffix("") # dataset directory return True, str(dir), next(dir.rglob("*.yaml")) # zipped, data_dir, yaml_path else: # path is data.yaml return False, None, path def hub_ops(f, max_dim=1920): # HUB ops for 1 image 'f' im = Image.open(f) r = max_dim / max(im.height, im.width) # ratio if r < 1.0: # image too large im = im.resize((int(im.width * r), int(im.height * r))) im.save(im_dir / Path(f).name, quality=75) # save zipped, data_dir, yaml_path = unzip(Path(path)) with open(check_yaml(yaml_path), errors="ignore") as f: data = yaml.safe_load(f) # data dict if zipped: data["path"] = data_dir # TODO: should this be dir.resolve()? check_dataset(data, autodownload) # download dataset if missing hub_dir = Path(data["path"] + ("-hub" if hub else "")) stats = {"nc": data["nc"], "names": data["names"]} # statistics dictionary for split in "train", "val", "test": if data.get(split) is None: stats[split] = None # i.e. no test set continue x = [] dataset = LoadImagesAndLabels(data[split]) # load dataset for label in tqdm(dataset.labels, total=dataset.n, desc="Statistics"): x.append(np.bincount(label[:, 0].astype(int), minlength=data["nc"])) x = np.array(x) # shape(128x80) stats[split] = { "instance_stats": {"total": int(x.sum()), "per_class": x.sum(0).tolist()}, "image_stats": { "total": dataset.n, "unlabelled": int(np.all(x == 0, 1).sum()), "per_class": (x > 0).sum(0).tolist(), }, "labels": [ {str(Path(k).name): round_labels(v.tolist())} for k, v in zip(dataset.img_files, dataset.labels) ], } if hub: im_dir = hub_dir / "images" im_dir.mkdir(parents=True, exist_ok=True) for _ in tqdm( ThreadPool(NUM_THREADS).imap(hub_ops, dataset.img_files), total=dataset.n, desc="HUB Ops", ): pass # Profile stats_path = hub_dir / "stats.json" if profile: for _ in range(1): file = stats_path.with_suffix(".npy") t1 = time.time() np.save(file, stats) t2 = time.time() x = np.load(file, allow_pickle=True) print(f"stats.npy times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write") file = stats_path.with_suffix(".json") t1 = time.time() with open(file, "w") as f: json.dump(stats, f) # save stats *.json t2 = time.time() with open(file, "r") as f: x = json.load(f) # load hyps dict print(f"stats.json times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write") # Save, print and return if hub: print(f"Saving {stats_path.resolve()}...") with open(stats_path, "w") as f: json.dump(stats, f) # save stats.json if verbose: print(json.dumps(stats, indent=2, sort_keys=False)) return stats
tcr.py
# -*- coding: utf-8 -*- print("You can generate token Here") print("http://101.255.95.249:6969") print("CREATED BY TCR AND FIXED BY RIOBITHUB") import SOURCE from SOURCE.libapi.ttypes import * from datetime import datetime import time,random,sys,json,codecs,threading,glob,re cl = SOURCE.LINE() #cl.login(qr=False) cl.login(token='') cl.loginResult() ki = kk = kc = cl print "login success" reload(sys) sys.setdefaultencoding('utf-8') helpMessage =""" TCR Bot [Id︎] [Mid] [Me︎] [TL︎:「Text」] [Mc 「mid」] [K on/off] [Join︎ on/off] [Gcancel:︎「Number of people」] [Group cancelalll︎] [Leave︎ on/off] [Add on/off] [Share on/off] [Message change:「text」] [Message check] [Confirm] [Jam on/off] [Change clock:「name」] [Up] [Cv join] [*] Command in the groups [*] [Curl] [Ourl] [url] [url:「Group ID」] [Invite:「mid」] [Kick:「mid」] [Ginfo] [jointicket] [Cancel] [Gn 「group name」] [Nk 「name」] [*] Command kicker only [*] [Bye] [Kill ban] [Kill 「@」] [Ban 「@」] By Tag [Unban 「@」] By Tag [Ban︎] Share Contact [Unban︎] Share Contact [Banlist︎] [Cek ban] [Cv mid] [Cv ︎invite:「mid」] [Cv ︎rename:「name」] [Cv ︎gift] [Respo︎n] [Bot cancel] [Title:] """ KAC=[cl,ki,kk,kc] mid = cl.getProfile().mid Amid = ki.getProfile().mid Bmid = kk.getProfile().mid Cmid = kc.getProfile().mid Bots=[mid,Amid,Bmid,Cmid] admin=["YOUR_MID_HERE"] wait = { 'contact':True, 'autoJoin':True, 'autoCancel':{"on":True,"members":1}, 'leaveRoom':True, 'timeline':True, 'autoAdd':True, 'message':"Thanks for add me", "lang":"JP", "comment":"Thanks for add me", "commentOn":False, "commentBlack":{}, "wblack":False, "dblack":False, "clock":True, "cName":"Chivas ", "blacklist":{}, "wblacklist":False, "dblacklist":False, "protectionOn":True, "atjointicket":False } wait2 = { 'readPoint':{}, 'readMember':{}, 'setTime':{}, 'ROM':{} } setTime = {} setTime = wait2['setTime'] def sendMessage(to, text, contentMetadata={}, contentType=0): mes = Message() mes.to, mes.from_ = to, profile.mid mes.text = text mes.contentType, mes.contentMetadata = contentType, contentMetadata if to not in messageReq: messageReq[to] = -1 messageReq[to] += 1 def NOTIFIED_READ_MESSAGE(op): try: if op.param1 in wait2['readPoint']: Name = cl.getContact(op.param2).displayName if Name in wait2['readMember'][op.param1]: pass else: wait2['readMember'][op.param1] += "\n・" + Name wait2['ROM'][op.param1][op.param2] = "・" + Name else: pass except: pass def bot(op): try: if op.type == 0: return if op.type == 5: if wait["autoAdd"] == True: cl.findAndAddContactsByMid(op.param1) if (wait["message"] in [""," ","\n",None]): pass else: cl.sendText(op.param1,str(wait["message"])) if op.type == 13: if op.param3 in mid: if op.param2 in Amid: G = ki.getGroup(op.param1) G.preventJoinByTicket = False ki.updateGroup(G) Ticket = ki.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ticket) G.preventJoinByTicket = True ki.updateGroup(G) Ticket = ki.reissueGroupTicket(op.param1) if op.param3 in Amid: if op.param2 in Bmid: X = kk.getGroup(op.param1) X.preventJoinByTicket = False kk.updateGroup(X) Ti = kk.reissueGroupTicket(op.param1) ki.acceptGroupInvitationByTicket(op.param1,Ti) X.preventJoinByTicket = True kk.updateGroup(X) Ti = kk.reissueGroupTicket(op.param1) if op.param3 in Bmid: if op.param2 in Cmid: X = kc.getGroup(op.param1) X.preventJoinByTicket = False kc.updateGroup(X) Ti = kc.reissueGroupTicket(op.param1) kk.acceptGroupInvitationByTicket(op.param1,Ti) X.preventJoinByTicket = True kc.updateGroup(X) Ti = kc.reissueGroupTicket(op.param1) if op.param3 in Cmid: if op.param2 in mid: X = cl.getGroup(op.param1) X.preventJoinByTicket = False cl.updateGroup(X) Ti = cl.reissueGroupTicket(op.param1) kc.acceptGroupInvitationByTicket(op.param1,Ti) X.preventJoinByTicket = True cl.updateGroup(X) Ti = cl.reissueGroupTicket(op.param1) if op.type == 13: print op.param1 print op.param2 print op.param3 if mid in op.param3: G = cl.getGroup(op.param1) if wait["autoJoin"] == True: if wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: cl.rejectGroupInvitation(op.param1) else: cl.acceptGroupInvitation(op.param1) else: cl.acceptGroupInvitation(op.param1) elif wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: cl.rejectGroupInvitation(op.param1) else: Inviter = op.param3.replace("",',') InviterX = Inviter.split(",") matched_list = [] for tag in wait["blacklist"]: matched_list+=filter(lambda str: str == tag, InviterX) if matched_list == []: pass else: cl.cancelGroupInvitation(op.param1, matched_list) if op.type == 19: if mid in op.param3: if op.param2 in Bots: pass try: ki.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("client Kick regulation or Because it does not exist in the group、\n["+op.param1+"]\nの\n["+op.param2+"]\nを蹴る事ができませんでした。\nブラックリストに追加します。") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True G = ki.getGroup(op.param1) G.preventJoinByTicket = False ki.updateGroup(G) Ti = ki.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) X = cl.getGroup(op.param1) X.preventJoinByTicket = True cl.updateGroup(X) Ti = cl.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if Amid in op.param3: if op.param2 in Bots: pass try: kk.kickoutFromGroup(op.param1,[op.param2]) kc.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("clientが蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nを蹴る事ができませんでした。\nブラックリストに追加します。") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True X = kk.getGroup(op.param1) X.preventJoinByTicket = False cl.updateGroup(X) Ti = kk.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) G = ki.getGroup(op.param1) G.preventJoinByTicket = True ki.updateGroup(G) Ticket = ki.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if Bmid in op.param3: if op.param2 in Bots: pass try: kc.kickoutFromGroup(op.param1,[op.param2]) kk.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("clientが蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nを蹴る事ができませんでした。\nブラックリストに追加します。") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True X = kc.getGroup(op.param1) X.preventJoinByTicket = False kc.updateGroup(X) Ti = kc.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) G = kk.getGroup(op.param1) G.preventJoinByTicket = True kk.updateGroup(G) Ticket = kk.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if Cmid in op.param3: if op.param2 in Bots: pass try: cl.kickoutFromGroup(op.param1,[op.param2]) kk.kickoutFromGroup(op.param1,[op.param2]) except: try: random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) except: print ("clientが蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nを蹴る事ができませんでした。\nブラックリストに追加します。") if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True X = cl.getGroup(op.param1) X.preventJoinByTicket = False cl.updateGroup(X) Ti = cl.reissueGroupTicket(op.param1) cl.acceptGroupInvitationByTicket(op.param1,Ti) ki.acceptGroupInvitationByTicket(op.param1,Ti) kk.acceptGroupInvitationByTicket(op.param1,Ti) kc.acceptGroupInvitationByTicket(op.param1,Ti) G = kc.getGroup(op.param1) G.preventJoinByTicket = True kc.updateGroup(G) Ticket = kc.reissueGroupTicket(op.param1) if op.param2 in wait["blacklist"]: pass if op.param2 in wait["whitelist"]: pass else: wait["blacklist"][op.param2] = True if op.type == 13: if mid in op.param3: G = cl.getGroup(op.param1) if wait["autoJoin"] == True: if wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: cl.rejectGroupInvitation(op.param1) else: cl.acceptGroupInvitation(op.param1) else: cl.acceptGroupInvitation(op.param1) elif wait["autoCancel"]["on"] == True: if len(G.members) <= wait["autoCancel"]["members"]: cl.rejectGroupInvitation(op.param1) else: Inviter = op.param3.replace("",',') InviterX = Inviter.split(",") matched_list = [] for tag in wait["blacklist"]: matched_list+=filter(lambda str: str == tag, InviterX) if matched_list == []: pass else: cl.cancelGroupInvitation(op.param1, matched_list) if op.type == 22: if wait["leaveRoom"] == True: cl.leaveRoom(op.param1) if op.type == 24: if wait["leaveRoom"] == True: cl.leaveRoom(op.param1) if op.type == 26: msg = op.message if msg.toType == 0: msg.to = msg.from_ if msg.from_ == profile.mid: if "join:" in msg.text: list_ = msg.text.split(":") try: cl.acceptGroupInvitationByTicket(list_[1],list_[2]) X = cl.getGroup(list_[1]) X.preventJoinByTicket = True cl.updateGroup(X) except: cl.sendText(msg.to,"error") if msg.toType == 1: if wait["leaveRoom"] == True: cl.leaveRoom(msg.to) if msg.contentType == 16: url = msg.contentMetadata("line://home/post?userMid="+mid+"&postId="+"new_post") cl.like(url[25:58], url[66:], likeType=1001) if op.type == 26: msg = op.message if msg.contentType == 13: if wait["wblack"] == True: if msg.contentMetadata["mid"] in wait["commentBlack"]: cl.sendText(msg.to,"already") wait["wblack"] = False else: wait["commentBlack"][msg.contentMetadata["mid"]] = True wait["wblack"] = False cl.sendText(msg.to,"decided not to comment") elif wait["dblack"] == True: if msg.contentMetadata["mid"] in wait["commentBlack"]: del wait["commentBlack"][msg.contentMetadata["mid"]] cl.sendText(msg.to,"deleted") ki.sendText(msg.to,"deleted") kk.sendText(msg.to,"deleted") kc.sendText(msg.to,"deleted") wait["dblack"] = False else: wait["dblack"] = False cl.sendText(msg.to,"It is not in the black list") ki.sendText(msg.to,"It is not in the black list") kk.sendText(msg.to,"It is not in the black list") kc.sendText(msg.to,"It is not in the black list") elif wait["wblacklist"] == True: if msg.contentMetadata["mid"] in wait["blacklist"]: cl.sendText(msg.to,"already") ki.sendText(msg.to,"already") kk.sendText(msg.to,"already") kc.sendText(msg.to,"already") wait["wblacklist"] = False else: wait["blacklist"][msg.contentMetadata["mid"]] = True wait["wblacklist"] = False cl.sendText(msg.to,"aded") ki.sendText(msg.to,"aded") kk.sendText(msg.to,"aded") kc.sendText(msg.to,"aded") elif wait["dblacklist"] == True: if msg.contentMetadata["mid"] in wait["blacklist"]: del wait["blacklist"][msg.contentMetadata["mid"]] cl.sendText(msg.to,"deleted") ki.sendText(msg.to,"deleted") kk.sendText(msg.to,"deleted") kc.sendText(msg.to,"deleted") wait["dblacklist"] = False else: wait["dblacklist"] = False cl.sendText(msg.to,"It is not in the black list") ki.sendText(msg.to,"It is not in the black list") kk.sendText(msg.to,"It is not in the black list") kc.sendText(msg.to,"It is not in the black list") elif wait["contact"] == True: msg.contentType = 0 cl.sendText(msg.to,msg.contentMetadata["mid"]) if 'displayName' in msg.contentMetadata: contact = cl.getContact(msg.contentMetadata["mid"]) try: cu = cl.channel.getCover(msg.contentMetadata["mid"]) except: cu = "" cl.sendText(msg.to,"[displayName]:\n" + msg.contentMetadata["displayName"] + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu)) else: contact = cl.getContact(msg.contentMetadata["mid"]) try: cu = cl.channel.getCover(msg.contentMetadata["mid"]) except: cu = "" cl.sendText(msg.to,"[displayName]:\n" + contact.displayName + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu)) elif msg.contentType == 16: if wait["timeline"] == True: msg.contentType = 0 if wait["lang"] == "JP": msg.text = "post URL\n" + msg.contentMetadata["postEndUrl"] else: msg.text = "URL→\n" + msg.contentMetadata["postEndUrl"] cl.sendText(msg.to,msg.text) elif msg.text is None: return elif msg.text in ["Key","help","Help"]: if wait["lang"] == "JP": cl.sendText(msg.to,helpMessage) else: cl.sendText(msg.to,helpt) elif ("Gn " in msg.text): if msg.toType == 2: X = cl.getGroup(msg.to) X.name = msg.text.replace("Gn ","") cl.updateGroup(X) else: cl.sendText(msg.to,"It can't be used besides the group.") elif ("Cv1 gn " in msg.text): if msg.toType == 2: X = cl.getGroup(msg.to) X.name = msg.text.replace("Cv1 gn ","") ki.updateGroup(X) else: ki.sendText(msg.to,"It can't be used besides the group.") elif ("Cv2 gn " in msg.text): if msg.toType == 2: X = cl.getGroup(msg.to) X.name = msg.text.replace("Cv2 gn ","") kk.updateGroup(X) else: kk.sendText(msg.to,"It can't be used besides the group.") elif ("Cv3 gn " in msg.text): if msg.toType == 2: X = cl.getGroup(msg.to) X.name = msg.text.replace("Cv3 gn ","") kc.updateGroup(X) else: kc.sendText(msg.to,"It can't be used besides the group.") elif "Kick " in msg.text: midd = msg.text.replace("Kick ","") cl.kickoutFromGroup(msg.to,[midd]) elif "Cv1 kick " in msg.text: midd = msg.text.replace("Cv1 kick ","") ki.kickoutFromGroup(msg.to,[midd]) elif "Cv2 kick " in msg.text: midd = msg.text.replace("Cv2 kick ","") kk.kickoutFromGroup(msg.to,[midd]) elif "Cv3 kick " in msg.text: midd = msg.text.replace("Cv3 kick ","") kc.kickoutFromGroup(msg.to,[midd]) elif "Invite " in msg.text: midd = msg.text.replace("Invite ","") cl.findAndAddContactsByMid(midd) cl.inviteIntoGroup(msg.to,[midd]) elif "Cv1 invite " in msg.text: midd = msg.text.replace("Cv1 invite ","") ki.findAndAddContactsByMid(midd) ki.inviteIntoGroup(msg.to,[midd]) elif "Cv2 invite " in msg.text: midd = msg.text.replace("Cv2 invite ","") kk.findAndAddContactsByMid(midd) kk.inviteIntoGroup(msg.to,[midd]) elif "Cv3 invite " in msg.text: midd = msg.text.replace("Cv3 invite ","") kc.findAndAddContactsByMid(midd) kc.inviteIntoGroup(msg.to,[midd]) elif msg.text in ["Me"]: msg.contentType = 13 msg.contentMetadata = {'mid': mid} cl.sendMessage(msg) elif msg.text in ["Cv1"]: msg.contentType = 13 msg.contentMetadata = {'mid': Amid} ki.sendMessage(msg) elif msg.text in ["Cv2"]: msg.contentType = 13 msg.contentMetadata = {'mid': Bmid} kk.sendMessage(msg) elif msg.text in ["愛のプレゼント","Gift"]: msg.contentType = 9 msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '5'} msg.text = None cl.sendMessage(msg) elif msg.text in ["愛のプレゼント","Cv1 gift"]: msg.contentType = 9 msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '6'} msg.text = None ki.sendMessage(msg) elif msg.text in ["愛のプレゼント","Cv2 gift"]: msg.contentType = 9 msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '8'} msg.text = None kk.sendMessage(msg) elif msg.text in ["愛のプレゼント","Cv3 gift"]: msg.contentType = 9 msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '10'} msg.text = None kc.sendMessage(msg) elif msg.text in ["愛のプレゼント","All gift"]: msg.contentType = 9 msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '12'} msg.text = None ki.sendMessage(msg) kk.sendMessage(msg) kc.sendMessage(msg) elif msg.text in ["cancel","Cancel"]: if msg.toType == 2: X = cl.getGroup(msg.to) if X.invitee is not None: gInviMids = [contact.mid for contact in X.invitee] cl.cancelGroupInvitation(msg.to, gInviMids) else: if wait["lang"] == "JP": cl.sendText(msg.to,"No one is inviting") else: cl.sendText(msg.to,"Sorry, nobody absent") else: if wait["lang"] == "JP": cl.sendText(msg.to,"Can not be used outside the group") else: cl.sendText(msg.to,"Not for use less than group") elif msg.text in ["Cv cancel","Bot cancel"]: if msg.toType == 2: G = k3.getGroup(msg.to) if G.invitee is not None: gInviMids = [contact.mid for contact in G.invitee] k3.cancelGroupInvitation(msg.to, gInviMids) else: if wait["lang"] == "JP": k3.sendText(msg.to,"No one is inviting") else: k3.sendText(msg.to,"Sorry, nobody absent") else: if wait["lang"] == "JP": k3.sendText(msg.to,"Can not be used outside the group") else: k3.sendText(msg.to,"Not for use less than group") #elif "gurl" == msg.text: #print cl.getGroup(msg.to) ##cl.sendMessage(msg) elif msg.text in ["Ourl","Link on"]: if msg.toType == 2: X = cl.getGroup(msg.to) X.preventJoinByTicket = False cl.updateGroup(X) if wait["lang"] == "JP": cl.sendText(msg.to,"Done") else: cl.sendText(msg.to,"already open") else: if wait["lang"] == "JP": cl.sendText(msg.to,"Can not be used outside the group") else: cl.sendText(msg.to,"Not for use less than group") elif msg.text in ["Cv1 ourl","Cv1 link on"]: if msg.toType == 2: X = cl.getGroup(msg.to) X.preventJoinByTicket = False ki.updateGroup(X) if wait["lang"] == "JP": ki.sendText(msg.to,"Done Chivas") else: ki.sendText(msg.to,"already open") else: if wait["lang"] == "JP": cl.sendText(msg.to,"Can not be used outside the group") else: cl.sendText(msg.to,"Not for use less than group") elif msg.text in ["Cv2 ourl","Cv2 link on"]: if msg.toType == 2: X = kk.getGroup(msg.to) X.preventJoinByTicket = False kk.updateGroup(X) if wait["lang"] == "JP": kk.sendText(msg.to,"Done Chivas") else: kk.sendText(msg.to,"already open") else: if wait["lang"] == "JP": kk.sendText(msg.to,"Can not be used outside the group") else: kk.sendText(msg.to,"Not for use less than group") elif msg.text in ["Cv3 ourl","Cv3 link on"]: if msg.toType == 2: X = kc.getGroup(msg.to) X.preventJoinByTicket = False kc.updateGroup(X) if wait["lang"] == "JP": kc.sendText(msg.to,"Done Chivas") else: kc.sendText(msg.to,"already open") else: if wait["lang"] == "JP": kc.sendText(msg.to,"Can not be used outside the group") else: kc.sendText(msg.to,"Not for use less than group") elif msg.text in ["Curl","Link off"]: if msg.toType == 2: X = cl.getGroup(msg.to) X.preventJoinByTicket = True cl.updateGroup(X) if wait["lang"] == "JP": cl.sendText(msg.to,"Done") else: cl.sendText(msg.to,"already close") else: if wait["lang"] == "JP": cl.sendText(msg.to,"Can not be used outside the group") else: cl.sendText(msg.to,"Not for use less than group") elif msg.text in ["Cv1 curl","Cv1 link off"]: if msg.toType == 2: X = ki.getGroup(msg.to) X.preventJoinByTicket = True ki.updateGroup(X) if wait["lang"] == "JP": ki.sendText(msg.to,"Done Chivas") else: ki.sendText(msg.to,"already close") else: if wait["lang"] == "JP": ki.sendText(msg.to,"Can not be used outside the group") else: ki.sendText(msg.to,"Not for use less than group") elif msg.text in ["Cv2 curl","Cv2 link off"]: if msg.toType == 2: X = kk.getGroup(msg.to) X.preventJoinByTicket = True kk.updateGroup(X) if wait["lang"] == "JP": kk.sendText(msg.to,"Done Chivas") else: kk.sendText(msg.to,"already close") else: if wait["lang"] == "JP": kk.sendText(msg.to,"Can not be used outside the group") else: kk.sendText(msg.to,"Not for use less than group") elif msg.text in ["Cv3 curl","Cv3 link off"]: if msg.toType == 2: X = kc.getGroup(msg.to) X.preventJoinByTicket = True kc.updateGroup(X) if wait["lang"] == "JP": kc.sendText(msg.to,"Done Chivas") else: kc.sendText(msg.to,"already close") else: if wait["lang"] == "JP": kc.sendText(msg.to,"Can not be used outside the group") else: kc.sendText(msg.to,"Not for use less than group") elif "jointicket " in msg.text.lower(): rplace=msg.text.lower().replace("jointicket ") if rplace == "on": wait["atjointicket"]=True elif rplace == "off": wait["atjointicket"]=False cl.sendText(msg.to,"Auto Join Group by Ticket is %s" % str(wait["atjointicket"])) elif '/ti/g/' in msg.text.lower(): link_re = re.compile('(?:line\:\/|line\.me\/R)\/ti\/g\/([a-zA-Z0-9_-]+)?') links = link_re.findall(msg.text) n_links=[] for l in links: if l not in n_links: n_links.append(l) for ticket_id in n_links: if wait["atjointicket"] == True: group=cl.findGroupByTicket(ticket_id) cl.acceptGroupInvitationByTicket(group.id,ticket_id) cl.sendText(msg.to,"Sukses join ke grup %s" % str(group.name)) elif msg.text == "Ginfo": if msg.toType == 2: ginfo = cl.getGroup(msg.to) try: gCreator = ginfo.creator.displayName except: gCreator = "Error" if wait["lang"] == "JP": if ginfo.invitee is None: sinvitee = "0" else: sinvitee = str(len(ginfo.invitee)) if ginfo.preventJoinByTicket == True: u = "close" else: u = "open" cl.sendText(msg.to,"[group name]\n" + str(ginfo.name) + "\n[gid]\n" + msg.to + "\n[group creator]\n" + gCreator + "\n[profile status]\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus + "\nmembers:" + str(len(ginfo.members)) + "members\npending:" + sinvitee + "people\nURL:" + u + "it is inside") else: cl.sendText(msg.to,"[group name]\n" + str(ginfo.name) + "\n[gid]\n" + msg.to + "\n[group creator]\n" + gCreator + "\n[profile status]\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus) else: if wait["lang"] == "JP": cl.sendText(msg.to,"Can not be used outside the group") else: cl.sendText(msg.to,"Not for use less than group") elif "Id" == msg.text: cl.sendText(msg.to,msg.to) elif "All mid" == msg.text: cl.sendText(msg.to,mid) ki.sendText(msg.to,Amid) kk.sendText(msg.to,Bmid) kc.sendText(msg.to,Cmid) elif "Mid" == msg.text: cl.sendText(msg.to,mid) elif "Cv1 mid" == msg.text: ki.sendText(msg.to,Amid) elif "Cv2 mid" == msg.text: kk.sendText(msg.to,Bmid) elif "Cv3 mid" == msg.text: kc.sendText(msg.to,Cmid) elif msg.text in ["Wkwk"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "100", "STKPKGID": "1", "STKVER": "100" } ki.sendMessage(msg) kk.sendMessage(msg) elif msg.text in ["Hehehe"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "10", "STKPKGID": "1", "STKVER": "100" } ki.sendMessage(msg) kk.sendMessage(msg) elif msg.text in ["Galon"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "9", "STKPKGID": "1", "STKVER": "100" } ki.sendMessage(msg) kk.sendMessage(msg) elif msg.text in ["You"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "7", "STKPKGID": "1", "STKVER": "100" } ki.sendMessage(msg) kk.sendMessage(msg) elif msg.text in ["Hadeuh"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "6", "STKPKGID": "1", "STKVER": "100" } ki.sendMessage(msg) kk.sendMessage(msg) elif msg.text in ["Please"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "4", "STKPKGID": "1", "STKVER": "100" } ki.sendMessage(msg) kk.sendMessage(msg) elif msg.text in ["Haaa"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "3", "STKPKGID": "1", "STKVER": "100" } ki.sendMessage(msg) kk.sendMessage(msg) elif msg.text in ["Lol"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "110", "STKPKGID": "1", "STKVER": "100" } ki.sendMessage(msg) kk.sendMessage(msg) elif msg.text in ["Hmmm"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "101", "STKPKGID": "1", "STKVER": "100" } ki.sendMessage(msg) elif msg.text in ["Welcome"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "247", "STKPKGID": "3", "STKVER": "100" } ki.sendMessage(msg) kk.sendMessage(msg) elif msg.text in ["TL:"]: tl_text = msg.text.replace("TL:","") cl.sendText(msg.to,"line://home/post?userMid="+mid+"&postId="+cl.new_post(tl_text)["result"]["post"]["postInfo"]["postId"]) elif msg.text in ["Cn "]: string = msg.text.replace("Cn ","") if len(string.decode('utf-8')) <= 20: profile = cl.getProfile() profile.displayName = string cl.updateProfile(profile) cl.sendText(msg.to,"name " + string + " done") elif msg.text in ["Cv1 rename "]: string = msg.text.replace("Cv1 rename ","") if len(string.decode('utf-8')) <= 20: profile_B = ki.getProfile() profile_B.displayName = string ki.updateProfile(profile_B) ki.sendText(msg.to,"name " + string + " done") elif msg.text in ["Cv2 rename "]: string = msg.text.replace("Cv2 rename ","") if len(string.decode('utf-8')) <= 20: profile_B = kk.getProfile() profile_B.displayName = string kk.updateProfile(profile_B) kk.sendText(msg.to,"name " + string + " done") elif msg.text in ["Mc "]: mmid = msg.text.replace("Mc ","") msg.contentType = 13 msg.contentMetadata = {"mid":mmid} cl.sendMessage(msg) elif msg.text in ["連絡先:オン","K on","Contact on","顯示:開"]: if wait["contact"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"already on") else: cl.sendText(msg.to,"done") else: wait["contact"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"already on") else: cl.sendText(msg.to,"done") elif msg.text in ["連絡先:オフ","K off","Contact off","顯示:關"]: if wait["contact"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"already off") else: cl.sendText(msg.to,"done ") else: wait["contact"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"already off") else: cl.sendText(msg.to,"done") elif msg.text in ["è‡ªå‹•å‚åŠ :オン","Join on","Auto join:on","è‡ªå‹•åƒåŠ ï¼šé–‹"]: if wait["autoJoin"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"already on") else: cl.sendText(msg.to,"done") else: wait["autoJoin"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"already on") else: cl.sendText(msg.to,"done") elif msg.text in ["è‡ªå‹•å‚åŠ :オフ","Join off","Auto join:off","è‡ªå‹•åƒåŠ ï¼šé—œ"]: if wait["autoJoin"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"already off") else: cl.sendText(msg.to,"done") else: wait["autoJoin"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"already off") else: cl.sendText(msg.to,"done") elif msg.text in ["Gcancel:"]: try: strnum = msg.text.replace("Gcancel:","") if strnum == "off": wait["autoCancel"]["on"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Invitation refused turned off\nTo turn on please specify the number of people and send") else: cl.sendText(msg.to,"关了邀请拒绝。要时开请指定人数发送") else: num = int(strnum) wait["autoCancel"]["on"] = True if wait["lang"] == "JP": cl.sendText(msg.to,strnum + "The group of people and below decided to automatically refuse invitation") else: cl.sendText(msg.to,strnum + "使人以下的小组用自动邀请拒绝") except: if wait["lang"] == "JP": cl.sendText(msg.to,"Value is wrong") else: cl.sendText(msg.to,"Bizarre ratings") elif msg.text in ["強制自動退出:オン","Leave on","Auto leave:on","強制自動退出:開"]: if wait["leaveRoom"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"already on") else: cl.sendText(msg.to,"done") else: wait["leaveRoom"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"done") else: cl.sendText(msg.to,"要了开。") elif msg.text in ["強制自動退出:オフ","Leave off","Auto leave:off","強制自動退出:關"]: if wait["leaveRoom"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"already off") else: cl.sendText(msg.to,"done") else: wait["leaveRoom"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"done") else: cl.sendText(msg.to,"already") elif msg.text in ["共有:オン","Share on","Share on"]: if wait["timeline"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"already on") else: cl.sendText(msg.to,"done") else: wait["timeline"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"done") else: cl.sendText(msg.to,"要了开。") elif msg.text in ["共有:オフ","Share off","Share off"]: if wait["timeline"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"already off") else: cl.sendText(msg.to,"done") else: wait["timeline"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"done") else: cl.sendText(msg.to,"要了关断。") elif msg.text in ["Set"]: md = "" if wait["contact"] == True: md+=" Contact : on\n" else: md+=" Contact : off\n" if wait["autoJoin"] == True: md+=" Auto join : on\n" else: md +=" Auto join : off\n" if wait["autoCancel"]["on"] == True:md+=" Group cancel :" + str(wait["autoCancel"]["members"]) + "\n" else: md+= " Group cancel : off\n" if wait["leaveRoom"] == True: md+=" Auto leave : on\n" else: md+=" Auto leave : off\n" if wait["timeline"] == True: md+=" Share : on\n" else:md+=" Share : off\n" if wait["autoAdd"] == True: md+=" Auto add : on\n" else:md+=" Auto add : off\n" if wait["commentOn"] == True: md+=" Comment : on\n" else:md+=" Comment : off\n" if wait["atjointicket"] == True: md+=" Auto Join Group by Ticket : on\n" else:md+=" Auto Join Group by Ticket : off\n" cl.sendText(msg.to,md) elif "album merit " in msg.text: gid = msg.text.replace("album merit ","") album = cl.getAlbum(gid) if album["result"]["items"] == []: if wait["lang"] == "JP": cl.sendText(msg.to,"There is no album") else: cl.sendText(msg.to,"相册没在。") else: if wait["lang"] == "JP": mg = "The following is the target album" else: mg = "以下是对象的相册" for y in album["result"]["items"]: if "photoCount" in y: mg += str(y["title"]) + ":" + str(y["photoCount"]) + "sheet\n" else: mg += str(y["title"]) + ":0sheet\n" cl.sendText(msg.to,mg) elif "album " in msg.text: gid = msg.text.replace("album ","") album = cl.getAlbum(gid) if album["result"]["items"] == []: if wait["lang"] == "JP": cl.sendText(msg.to,"There is no album") else: cl.sendText(msg.to,"相册没在。") else: if wait["lang"] == "JP": mg = "The following is the target album" else: mg = "以下是对象的相册" for y in album["result"]["items"]: if "photoCount" in y: mg += str(y["title"]) + ":" + str(y["photoCount"]) + "sheet\n" else: mg += str(y["title"]) + ":0sheet\n" elif "album remove " in msg.text: gid = msg.text.replace("album remove ","") albums = cl.getAlbum(gid)["result"]["items"] i = 0 if albums != []: for album in albums: cl.deleteAlbum(gid,album["id"]) i += 1 if wait["lang"] == "JP": cl.sendText(msg.to,str(i) + "Deleted albums") else: cl.sendText(msg.to,str(i) + "åˆ é™¤äº†äº‹çš„ç›¸å†Œã€‚") elif msg.text in ["Group id","群組全id"]: gid = cl.getGroupIdsJoined() h = "" for i in gid: h += "[%s]:%s\n" % (cl.getGroup(i).name,i) cl.sendText(msg.to,h) elif msg.text in ["Cancelall"]: gid = cl.getGroupIdsInvited() for i in gid: cl.rejectGroupInvitation(i) if wait["lang"] == "JP": cl.sendText(msg.to,"All invitations have been refused") else: cl.sendText(msg.to,"拒绝了全部的邀请。") elif "album remove→" in msg.text: gid = msg.text.replace("album remove→","") albums = cl.getAlbum(gid)["result"]["items"] i = 0 if albums != []: for album in albums: cl.deleteAlbum(gid,album["id"]) i += 1 if wait["lang"] == "JP": cl.sendText(msg.to,str(i) + "Albums deleted") else: cl.sendText(msg.to,str(i) + "åˆ é™¤äº†äº‹çš„ç›¸å†Œã€‚") elif msg.text in ["è‡ªå‹•è¿½åŠ :オン","Add on","Auto add:on","è‡ªå‹•è¿½åŠ ï¼šé–‹"]: if wait["autoAdd"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"already on") else: cl.sendText(msg.to,"done") else: wait["autoAdd"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"done") else: cl.sendText(msg.to,"要了开。") elif msg.text in ["è‡ªå‹•è¿½åŠ :オフ","Add off","Auto add:off","è‡ªå‹•è¿½åŠ ï¼šé—œ"]: if wait["autoAdd"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"already off") else: cl.sendText(msg.to,"done") else: wait["autoAdd"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"done") else: cl.sendText(msg.to,"要了关断。") elif "Message change: " in msg.text: wait["message"] = msg.text.replace("Message change: ","") cl.sendText(msg.to,"message changed") elif "Message add: " in msg.text: wait["message"] = msg.text.replace("Message add: ","") if wait["lang"] == "JP": cl.sendText(msg.to,"message changed") else: cl.sendText(msg.to,"done。") elif msg.text in ["Message","è‡ªå‹•è¿½åŠ å•å€™èªžç¢ºèª"]: if wait["lang"] == "JP": cl.sendText(msg.to,"message change to\n\n" + wait["message"]) else: cl.sendText(msg.to,"The automatic appending information is set as follows。\n\n" + wait["message"]) elif "Comment:" in msg.text: c = msg.text.replace("Comment:","") if c in [""," ","\n",None]: cl.sendText(msg.to,"message changed") else: wait["comment"] = c cl.sendText(msg.to,"changed\n\n" + c) elif "Add comment:" in msg.text: c = msg.text.replace("Add comment:","") if c in [""," ","\n",None]: cl.sendText(msg.to,"String that can not be changed") else: wait["comment"] = c cl.sendText(msg.to,"changed\n\n" + c) elif msg.text in ["コメント:オン","Comment on","Comment:on","è‡ªå‹•é¦–é ç•™è¨€ï¼šé–‹"]: if wait["commentOn"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"done") else: cl.sendText(msg.to,"already on") else: wait["commentOn"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"done") else: cl.sendText(msg.to,"要了开。") elif msg.text in ["コメント:オフ","Comment on","Comment off","è‡ªå‹•é¦–é ç•™è¨€ï¼šé—œ"]: if wait["commentOn"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"done") else: cl.sendText(msg.to,"already off") else: wait["commentOn"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"done") else: cl.sendText(msg.to,"要了关断。") elif msg.text in ["Comment","留言確認"]: cl.sendText(msg.to,"message changed to\n\n" + str(wait["comment"])) elif msg.text in ["Gurl"]: if msg.toType == 2: x = cl.getGroup(msg.to) if x.preventJoinByTicket == True: x.preventJoinByTicket = False cl.updateGroup(x) gurl = cl.reissueGroupTicket(msg.to) cl.sendText(msg.to,"line://ti/g/" + gurl) else: if wait["lang"] == "JP": cl.sendText(msg.to,"Can't be used outside the group") else: cl.sendText(msg.to,"Not for use less than group") elif msg.text in ["Cv1 gurl"]: if msg.toType == 2: x = cl.getGroup(msg.to) if x.preventJoinByTicket == True: x.preventJoinByTicket = False ki.updateGroup(x) gurl = ki.reissueGroupTicket(msg.to) ki.sendText(msg.to,"line://ti/g/" + gurl) else: if wait["lang"] == "JP": cl.sendText(msg.to,"Can't be used outside the group") else: cl.sendText(msg.to,"Not for use less than group") elif msg.text in ["Cv2 gurl"]: if msg.toType == 2: x = cl.getGroup(msg.to) if x.preventJoinByTicket == True: x.preventJoinByTicket = False kk.updateGroup(x) gurl = kk.reissueGroupTicket(msg.to) kk.sendText(msg.to,"line://ti/g/" + gurl) else: if wait["lang"] == "JP": cl.sendText(msg.to,"Can't be used outside the group") else: cl.sendText(msg.to,"Not for use less than group") elif msg.text in ["Cv3 gurl"]: if msg.toType == 2: x = cl.getGroup(msg.to) if x.preventJoinByTicket == True: x.preventJoinByTicket = False kc.updateGroup(x) gurl = kc.reissueGroupTicket(msg.to) kc.sendText(msg.to,"line://ti/g/" + gurl) else: if wait["lang"] == "JP": cl.sendText(msg.to,"Can't be used outside the group") else: cl.sendText(msg.to,"Not for use less than group") elif msg.text in ["Comment bl "]: wait["wblack"] = True cl.sendText(msg.to,"add to comment bl") elif msg.text in ["Comment wl "]: wait["dblack"] = True cl.sendText(msg.to,"wl to comment bl") elif msg.text in ["Comment bl confirm"]: if wait["commentBlack"] == {}: cl.sendText(msg.to,"confirmed") else: cl.sendText(msg.to,"Blacklist") mc = "" for mi_d in wait["commentBlack"]: mc += "" +cl.getContact(mi_d).displayName + "\n" cl.sendText(msg.to,mc) elif msg.text in ["Jam on"]: if wait["clock"] == True: cl.sendText(msg.to,"already on") else: wait["clock"] = True now2 = datetime.now() nowT = datetime.strftime(now2,"(%H:%M)") profile = cl.getProfile() profile.displayName = wait["cName"] + nowT cl.updateProfile(profile) cl.sendText(msg.to,"done") elif msg.text in ["Jam off"]: if wait["clock"] == False: cl.sendText(msg.to,"already off") else: wait["clock"] = False cl.sendText(msg.to,"done") elif msg.text in ["Change clock "]: n = msg.text.replace("Change clock ","") if len(n.decode("utf-8")) > 13: cl.sendText(msg.to,"changed") else: wait["cName"] = n cl.sendText(msg.to,"changed to\n\n" + n) elif msg.text in ["Up"]: if wait["clock"] == True: now2 = datetime.now() nowT = datetime.strftime(now2,"(%H:%M)") profile = cl.getProfile() profile.displayName = wait["cName"] + nowT cl.updateProfile(profile) cl.sendText(msg.to,"Jam Update") else: cl.sendText(msg.to,"Please turn on the name clock") elif msg.text == "$set": cl.sendText(msg.to, "Check sider") ki.sendText(msg.to, "Check sider") kk.sendText(msg.to, "Check sider") kc.sendText(msg.to, "Check sider") try: del wait2['readPoint'][msg.to] del wait2['readMember'][msg.to] except: pass wait2['readPoint'][msg.to] = msg.id wait2['readMember'][msg.to] = "" wait2['ROM'][msg.to] = {} print wait2 elif msg.text == "$read": if msg.to in wait2['readPoint']: if wait2["ROM"][msg.to].items() == []: chiya = "" else: chiya = "" for rom in wait2["ROM"][msg.to].items(): print rom chiya += rom[1] + "\n" cl.sendText(msg.to, "People who readed %s\nthat's it\n\nPeople who have ignored reads\n%sIt is abnormal ♪\n\nReading point creation date n time:\n[%s]" % (wait2['readMember'][msg.to],chiya,setTime[msg.to])) else: cl.sendText(msg.to, "An already read point has not been set.\n「set」you can send ♪ read point will be created ♪") #----------------------------------------------- #----------------------------------------------- elif msg.text in ["All join"]: G = cl.getGroup(msg.to) ginfo = cl.getGroup(msg.to) G.preventJoinByTicket = False cl.updateGroup(G) invsend = 0 Ticket = cl.reissueGroupTicket(msg.to) ki.acceptGroupInvitationByTicket(msg.to,Ticket) time.sleep(0.2) kk.acceptGroupInvitationByTicket(msg.to,Ticket) time.sleep(0.2) kc.acceptGroupInvitationByTicket(msg.to,Ticket) time.sleep(0.2) G = cl.getGroup(msg.to) G.preventJoinByTicket = True ki.updateGroup(G) print "kicker ok" G.preventJoinByTicket(G) ki.updateGroup(G) elif msg.text in ["Cv1 join"]: X = cl.getGroup(msg.to) X.preventJoinByTicket = False cl.updateGroup(X) invsend = 0 Ti = cl.reissueGroupTicket(msg.to) ki.acceptGroupInvitationByTicket(msg.to,Ti) G = kk.getGroup(msg.to) G.preventJoinByTicket = True ki.updateGroup(G) Ticket = kk.reissueGroupTicket(msg.to) elif msg.text in ["Cv2 join"]: X = cl.getGroup(msg.to) X.preventJoinByTicket = False cl.updateGroup(X) invsend = 0 Ti = cl.reissueGroupTicket(msg.to) kk.acceptGroupInvitationByTicket(msg.to,Ti) G = ki.getGroup(msg.to) G.preventJoinByTicket = True kk.updateGroup(G) Ticket = kk.reissueGroupTicket(msg.to) #----------------------------------------------- #.acceptGroupInvitationByTicket(msg.to,Ticket) elif msg.text in ["Cv3 join"]: G = cl.getGroup(msg.to) ginfo = cl.getGroup(msg.to) G.preventJoinByTicket = False cl.updateGroup(G) invsend = 0 Ticket = cl.reissueGroupTicket(msg.to) kc.acceptGroupInvitationByTicket(msg.to,Ticket) print "kicker ok" G.preventJoinByTicket = True kc.updateGroup(G) #----------------------------------------------- elif msg.text in ["Bye all"]: if msg.toType == 2: ginfo = cl.getGroup(msg.to) try: ki.leaveGroup(msg.to) kk.leaveGroup(msg.to) kc.leaveGroup(msg.to) except: pass elif msg.text in ["Bye 1"]: if msg.toType == 2: ginfo = cl.getGroup(msg.to) try: ki.leaveGroup(msg.to) except: pass elif msg.text in ["Bye 2"]: if msg.toType == 2: ginfo = cl.getGroup(msg.to) try: ki.leaveGroup(msg.to) kk.leaveGroup(msg.to) except: pass elif msg.text in ["Cv1 @bye"]: if msg.toType == 2: ginfo = cl.getGroup(msg.to) try: ki.leaveGroup(msg.to) except: pass elif msg.text in ["Cv2 @bye"]: if msg.toType == 2: ginfo = cl.getGroup(msg.to) try: kk.leaveGroup(msg.to) except: pass elif msg.text in ["Cv3 @bye"]: if msg.toType == 2: ginfo = cl.getGroup(msg.to) try: kc.leaveGroup(msg.to) except: pass #----------------------------------------------- elif msg.text in ["Tg","Tag all"]: group = cl.getGroup(msg.to) jw = [contact.mid for contact in group.members] cb = "" cb2 = "" strt = int(0) akh = int(0) for rs in jw: xname = cl.getContact(rs).displayName xlen = int(len('x')+1) akh = akh + xlen cb += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(rs)+"},""" strt = strt + int(len('x')+3) akh = akh + 2 cb2 += "@x \n" cb = (cb[:int(len(cb)-1)]) msg.contentType = 0 msg.text = cb2 msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+cb+']}','EMTVER':'d'} try: cl.sendMessage(msg) except Exception as error: print error #----------------------------------------------- elif msg.text in ["Kill"]: if msg.toType == 2: group = ki.getGroup(msg.to) gMembMids = [contact.mid for contact in group.members] matched_list = [] for tag in wait["blacklist"]: matched_list+=filter(lambda str: str == tag, gMembMids) if matched_list == []: kk.sendText(msg.to,"Fuck You") kc.sendText(msg.to,"Fuck You") return for jj in matched_list: try: klist=[ki,kk,kc] kicker=random.choice(klist) kicker.kickoutFromGroup(msg.to,[jj]) print (msg.to,[jj]) except: pass elif "Cleanse" in msg.text: if msg.toType == 2: print "ok" _name = msg.text.replace("Cleanse","") gs = ki.getGroup(msg.to) gs = kk.getGroup(msg.to) gs = kc.getGroup(msg.to) ki.sendText(msg.to,"Just some casual cleansing ô") kk.sendText(msg.to,"Group cleansed.") kc.sendText(msg.to,"Fuck You All") targets = [] for g in gs.members: if _name in g.displayName: targets.append(g.mid) if targets == []: ki.sendText(msg.to,"Not found.") kk.sendText(msg.to,"Not found.") kc.sendText(msg.to,"Not found.") else: for target in targets: try: klist=[ki,kk,kc] kicker=random.choice(klist) kicker.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except: ki.sendText(msg.to,"Group cleanse") kk.sendText(msg.to,"Group cleanse") kc.sendText(msg.to,"Group cleanse") elif "Nk " in msg.text: if msg.from_ in admin: nk0 = msg.text.replace("Nk ","") nk1 = nk0.lstrip() nk2 = nk1.replace("@","") nk3 = nk2.rstrip() _name = nk3 gs = cl.getGroup(msg.to) targets = [] for s in gs.members: if _name in s.displayName: targets.append(s.mid) if targets == []: sendMessage(msg.to,"user does not exist") pass else: for target in targets: try: klist=[cl,ki,kk,kc] kicker=random.choice(klist) kicker.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except: ki.sendText(msg.to,"Succes Cv") kk.sendText(msg.to,"Fuck You") elif "Blacklist @ " in msg.text: _name = msg.text.replace("Blacklist @ ","") _kicktarget = _name.rstrip(' ') gs = ki2.getGroup(msg.to) targets = [] for g in gs.members: if _kicktarget == g.displayName: targets.append(g.mid) if targets == []: cl.sendText(msg.to,"Not found") else: for target in targets: try: wait["blacklist"][target] = True f=codecs.open('st2__b.json','w','utf-8') json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False) k3.sendText(msg.to,"Succes Cv") except: ki.sendText(msg.to,"error") elif "Ban @" in msg.text: if msg.toType == 2: print "[Ban]ok" _name = msg.text.replace("Ban @","") _nametarget = _name.rstrip(' ') gs = ki.getGroup(msg.to) gs = kk.getGroup(msg.to) gs = kc.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: ki.sendText(msg.to,"Not found Cv") kk.sendText(msg.to,"Not found Cv") kc.sendText(msg.to,"Not found Cv") else: for target in targets: try: wait["blacklist"][target] = True f=codecs.open('st2__b.json','w','utf-8') json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False) cl.sendText(msg.to,"Succes Cv") ki.sendText(msg.to,"Succes Cv") kk.sendText(msg.to,"Succes Cv") kc.sendText(msg.to,"Succes Cv") except: ki.sendText(msg.to,"Error") kk.sendText(msg.to,"Error") kc.sendText(msg.to,"Error") elif "Unban @" in msg.text: if msg.toType == 2: print "[Unban]ok" _name = msg.text.replace("Unban @","") _nametarget = _name.rstrip(' ') gs = ki.getGroup(msg.to) gs = kk.getGroup(msg.to) gs = kc.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: ki.sendText(msg.to,"Not found Cv") kk.sendText(msg.to,"Not found Cv") kc.sendText(msg.to,"Not found Cv") else: for target in targets: try: del wait["blacklist"][target] f=codecs.open('st2__b.json','w','utf-8') json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False) cl.sendText(msg.to,"Succes Cv") ki.sendText(msg.to,"Succes Cv") kk.sendText(msg.to,"Succes Cv") kc.sendText(msg.to,"Succes Cv") except: ki.sendText(msg.to,"Succes Cv") kk.sendText(msg.to,"Succes Cv") kc.sendText(msg.to,"Succes Cv") #----------------------------------------------- elif msg.text in ["Test"]: ki.sendText(msg.to,"Ok Cv 􀨁􀄻double thumbs up􏿿") kk.sendText(msg.to,"Ok Cv 􀨁􀄻double thumbs up􏿿") kc.sendText(msg.to,"Ok Cv 􀨁􀄻double thumbs up􏿿") #----------------------------------------------- elif "Bc " in msg.text: bctxt = msg.text.replace("Bc ","") ki.sendText(msg.to,(bctxt)) kk.sendText(msg.to,(bctxt)) kc.sendText(msg.to,(bctxt)) #----------------------------------------------- elif msg.text in ["Cv say hi"]: ki.sendText(msg.to,"Hi buddy 􀜁􀅔Har Har􏿿") kk.sendText(msg.to,"Hi buddy 􀜁􀅔Har Har􏿿") kc.sendText(msg.to,"Hi buddy 􀜁􀅔Har Har􏿿") #----------------------------------------------- elif msg.text in ["Cv say hinata pekok"]: ki.sendText(msg.to,"Hinata pekok 􀜁􀅔Har Har􏿿") kk.sendText(msg.to,"Hinata pekok 􀜁􀅔Har Har􏿿") kc.sendText(msg.to,"Hinata pekok 􀜁􀅔Har Har􏿿") elif msg.text in ["Cv say didik pekok"]: ki.sendText(msg.to,"Didik pekok 􀜁􀅔Har Har􏿿") kk.sendText(msg.to,"Didik pekok 􀜁􀅔Har Har􏿿") kc.sendText(msg.to,"Didik pekok 􀜁􀅔Har Har􏿿") elif msg.text in ["Cv say bobo ah","Bobo dulu ah"]: ki.sendText(msg.to,"Have a nice dream Cv 􀜁􀅔Har Har􏿿") kk.sendText(msg.to,"Have a nice dream Cv 􀜁􀅔Har Har􏿿") kc.sendText(msg.to,"Have a nice dream Cv 􀜁􀅔Har Har􏿿") elif msg.text in ["Cv say chomel pekok"]: ki.sendText(msg.to,"Chomel pekok 􀜁􀅔Har Har􏿿") kk.sendText(msg.to,"Chomel pekok 􀜁􀅔Har Har􏿿") kc.sendText(msg.to,"Chomel pekok 􀜁􀅔Har Har􏿿") elif msg.text in ["#welcome"]: ki.sendText(msg.to,"Selamat datang di Chivas Family Room") kk.sendText(msg.to,"Jangan nakal ok!") #----------------------------------------------- elif msg.text in ["PING","Ping","ping"]: ki.sendText(msg.to,"PONG 􀨁􀄻double thumbs up􏿿􀜁􀅔Har Har􏿿") kk.sendText(msg.to,"PONG 􀨁􀄻double thumbs up􏿿􀜁􀅔Har Har􏿿") kc.sendText(msg.to,"PONG 􀨁􀄻double thumbs up􏿿􀜁􀅔Har Har􏿿") #----------------------------------------------- elif msg.text in ["Respon","respon"]: ki.sendText(msg.to,"Cv1") kk.sendText(msg.to,"Cv2") kc.sendText(msg.to,"Cv3") #----------------------------------------------- elif msg.text in ["Sp","Speed","speed"]: start = time.time() cl.sendText(msg.to, "Progress...") elapsed_time = time.time() - start cl.sendText(msg.to, "%sseconds" % (elapsed_time)) ki.sendText(msg.to, "%sseconds" % (elapsed_time)) kk.sendText(msg.to, "%sseconds" % (elapsed_time)) kc.sendText(msg.to, "%sseconds" % (elapsed_time)) #------------------------------------------------------------------ elif "Steal home @" in msg.text: print "[Command]dp executing" _name = msg.text.replace("Steal home @","") _nametarget = _name.rstrip(' ') gs = cl.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: ki.sendText(msg.to,"Contact not found") else: for target in targets: try: contact = cl.getContact(target) cu = cl.channel.getCover(target) path = str(cu) cl.sendImageWithURL(msg.to, path) except: pass print "[Command]dp executed" #------------------------------------------------------------------ elif "Steal dp @" in msg.text: print "[Command]dp executing" _name = msg.text.replace("Steal dp @","") _nametarget = _name.rstrip(' ') gs = cl.getGroup(msg.to) targets = [] for g in gs.members: if _nametarget == g.displayName: targets.append(g.mid) if targets == []: ki.sendText(msg.to,"Contact not found") else: for target in targets: try: contact = cl.getContact(target) path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus cl.sendImageWithURL(msg.to, path) except: pass print "[Command]dp executed" #------------------------------------------------------------------ elif msg.text in ["Ban"]: wait["wblacklist"] = True cl.sendText(msg.to,"send contact") ki.sendText(msg.to,"send contact") kk.sendText(msg.to,"send contact") kc.sendText(msg.to,"send contact") elif msg.text in ["Unban"]: wait["dblacklist"] = True cl.sendText(msg.to,"send contact") ki.sendText(msg.to,"send contact") kk.sendText(msg.to,"send contact") kc.sendText(msg.to,"send contact") elif msg.text in ["Banlist"]: if wait["blacklist"] == {}: cl.sendText(msg.to,"nothing") ki.sendText(msg.to,"nothing") kk.sendText(msg.to,"nothing") kc.sendText(msg.to,"nothing") else: cl.sendText(msg.to,"Blacklist user") mc = "" for mi_d in wait["blacklist"]: mc += "->" +cl.getContact(mi_d).displayName + "\n" cl.sendText(msg.to,mc) ki.sendText(msg.to,mc) kk.sendText(msg.to,mc) kc.sendText(msg.to,mc) elif msg.text in ["Cek ban"]: if msg.toType == 2: group = cl.getGroup(msg.to) gMembMids = [contact.mid for contact in group.members] matched_list = [] for tag in wait["blacklist"]: matched_list+=filter(lambda str: str == tag, gMembMids) cocoa = "" for mm in matched_list: cocoa += mm + "\n" cl.sendText(msg.to,cocoa + "") elif msg.text in ["Kill ban"]: if msg.toType == 2: group = cl.getGroup(msg.to) gMembMids = [contact.mid for contact in group.members] matched_list = [] for tag in wait["blacklist"]: matched_list+=filter(lambda str: str == tag, gMembMids) if matched_list == []: cl.sendText(msg.to,"There was no blacklist user") ki.sendText(msg.to,"There was no blacklist user") kk.sendText(msg.to,"There was no blacklist user") kc.sendText(msg.to,"There was no blacklist user") return for jj in matched_list: cl.kickoutFromGroup(msg.to,[jj]) ki.kickoutFromGroup(msg.to,[jj]) kk.kickoutFromGroup(msg.to,[jj]) kc.kickoutFromGroup(msg.to,[jj]) cl.sendText(msg.to,"Blacklist emang pantas tuk di usir") ki.sendText(msg.to,"Blacklist emang pantas tuk di usir") kk.sendText(msg.to,"Blacklist emang pantas tuk di usir") kc.sendText(msg.to,"Blacklist emang pantas tuk di usir") elif msg.text in ["Clear"]: if msg.toType == 2: group = cl.getGroup(msg.to) gMembMids = [contact.mid for contact in group.invitee] for _mid in gMembMids: cl.cancelGroupInvitation(msg.to,[_mid]) cl.sendText(msg.to,"I pretended to cancel and canceled.") elif "random:" in msg.text: if msg.toType == 2: strnum = msg.text.replace("random:","") source_str = 'abcdefghijklmnopqrstuvwxyz1234567890@:;./_][!&%$#)(=~^|' try: num = int(strnum) group = cl.getGroup(msg.to) for var in range(0,num): name = "".join([random.choice(source_str) for x in xrange(10)]) time.sleep(0.01) group.name = name cl.updateGroup(group) except: cl.sendText(msg.to,"Error") elif "album→" in msg.text: try: albumtags = msg.text.replace("album→","") gid = albumtags[:6] name = albumtags.replace(albumtags[:34],"") cl.createAlbum(gid,name) cl.sendText(msg.to,name + "created an album") except: cl.sendText(msg.to,"Error") elif "fakec→" in msg.text: try: source_str = 'abcdefghijklmnopqrstuvwxyz1234567890@:;./_][!&%$#)(=~^|' name = "".join([random.choice(source_str) for x in xrange(10)]) anu = msg.text.replace("fakec→","") cl.sendText(msg.to,str(cl.channel.createAlbum(msg.to,name,anu))) except Exception as e: try: cl.sendText(msg.to,str(e)) except: pass if op.type == 59: print op except Exception as error: print error def a2(): now2 = datetime.now() nowT = datetime.strftime(now2,"%M") if nowT[14:] in ["10","20","30","40","50","00"]: return False else: return True def nameUpdate(): while True: try: #while a2(): #pass if wait["clock"] == True: now2 = datetime.now() nowT = datetime.strftime(now2,"(%H:%M)") profile = cl.getProfile() profile.displayName = wait["cName"] + nowT cl.updateProfile(profile) time.sleep(600) except: pass thread2 = threading.Thread(target=nameUpdate) thread2.daemon = True thread2.start() while True: try: Ops = cl.fetchOps(cl.Poll.rev, 5) except EOFError: raise Exception("It might be wrong revision\n" + str(cl.Poll.rev)) for Op in Ops: if (Op.type != OpType.END_OF_OPERATION): cl.Poll.rev = max(cl.Poll.rev, Op.revision) bot(Op)
webserver.py
from flask import Flask from threading import Thread app = Flask('') @app.route('/') def home(): return "auto dank is alive made by aditya codez 🔥" def run(): app.run(host='0.0.0.0',port=8080) def keep_alive(): t = Thread(target=run) t.start()
manager.py
"""插件管理器类""" import logging from threading import Thread from types import ModuleType from typing import NoReturn, Dict, Iterable, Optional from collections import namedtuple from importlib import reload as pyreload from . import error from . import settings from ..core.tools import file from ..core.abstract.plugin import Plugin # 载入模块的返回值 LoadedPlugin = namedtuple("LoadedPlugin", ("plugin", "module")) logger = logging.getLogger("leaf.plugins") class Manager: """ 插件管理器类: start: 启动一个插件 stop: 停止一个插件 unload: 卸载一个插件 reload: 重载一个插件 scan: 扫描是否有新的插件 clean: 清理已经失效的插件 """ def __repr__(self) -> str: """返回 repr 信息""" return "<Leaf PluginManager with directory '%s'>" % self.__directory def __init__(self, directory: str): """ 插件注册器类构造函数 directory: 要扫描的插件目录 """ # 扫描插件的目录 self.__directory: str = directory # 插件 ID 与 import 之后 module 的映射 self.__modules: Dict[str, ModuleType] = dict() # 插件 ID 与 生成的插件实例的映射 self.__plugins: Dict[str, Plugin] = dict() # 插件 ID 与载入目录 catalog 的映射 self.__catalogs: Dict[str, str] = dict() # 插件 ID 与对应顶级域 domain 的映射 self.__domains: Dict[str, Plugin] = dict() @staticmethod def __load(catalog: str) -> LoadedPlugin: """ 尝试从一个目录载入插件: catalog: 要尝试的插件目录 LoadedPlugin.plugin - 载入的插件 LoadedPlugin.module - 载入的模块 """ try: # __import__ 函数的 level 设置为 1 可以不污染全局目录 module = __import__(catalog, globals(), locals(), [], 1) plugin = module.plugin result = LoadedPlugin(plugin, module) except ImportError as _error: # 当有载入错误时 raise error.PluginImportError(_error) except AttributeError as _error: # 当插件不符合规范时 raise error.PluginInitError(_error) except Exception as _error: # 插件运行期间错误 raise error.PluginRuntimeError(_error) return result @staticmethod def __reload(module: ModuleType) -> ModuleType: """ 重新载入一个模块并返回: module: 需要重新载入的模块 """ newmodule = pyreload(module) del module return newmodule @staticmethod def __scandirs(target: str, skipped: set) -> set: """ 目录扫描函数: target: 要扫描的文件夹地址 skipped: 要跳过扫描的地址 """ result = set() catalogs = file.dirs(target) for catalog in catalogs: # 跳过不要扫描的地址 if catalog in skipped: continue result.add(catalog) return result def register(self, plugin: Plugin, domains: Iterable) -> NoReturn: """ 向管理器注册插件的顶级域: pluginid: 插件的 id domains: 要注册的顶级域列表 """ for domain in domains: self.__domains[domain] = plugin def domain(self, domain: str) -> Plugin: """ 根据传入的顶级域返回对应的插件: domain: 要搜索的顶级域字符串 *注意: 当找不到对应插件时会返回 None 当传入顶级域对应的插件已经停止运行时仍然会返回 None """ plugin: Plugin = self.__domains.get(domain) if plugin and plugin.status is True: return plugin return None def id(self, pluginid: str) -> Plugin: """ 返回 id 对应的插件 pluginid: 要搜索的插件 id *注意: 当找不到对应插件时会返回 None """ return self.__plugins.get(pluginid) def status(self) -> dict: """ 返回所有插件 id 及其对应的状态 -> { "absd1234edfaa11100": False, "...": True, ... } """ result: Dict[str, Plugin] = dict() for id_, plugin in self.__plugins.items(): result[id_] = plugin.status return result def start(self, pluginid: str) -> NoReturn: """ 尝试启动一个插件: plguinid: 要启动的插件 ID """ # 尝试获取插件实例 - 当不存在时报错 plugin: Plugin = self.__plugins.get(pluginid) if plugin is None: raise error.PluginNotFound(pluginid) # 如果插件的状态为已经启动 - 不进行操作 if plugin.status is True: return # 尝试在新线程中运行插件的启动函数 _start = Thread(target=plugin.start) _start.setDaemon(True) _start.start() plugin.status = True def unload(self, plguinid: str) -> NoReturn: """ 从注册表中删除一个插件的实例及信息 pluginid: 插件的id """ # 首先停止插件的运行 self.stop(plguinid) # 从注册表中剔除 plugin = self.__plugins.pop(plguinid, None) _catalog = self.__catalogs.pop(plguinid, None) module = self.__modules.pop(plugin, None) if plugin and module: del plugin del module def reload(self, pluginid: str) -> NoReturn: """ 从原来的目录位置重新载入模块和插件并重启: pluginid: 要操作的插件 ID *reload 之后的插件 id 将不会变化 """ # 首先停止插件 self.stop(pluginid) # 重新载入模块 module = self.__modules.get(pluginid) if not module: return newmodule = self.__reload(module) newplugin: Plugin = newmodule.plguin # 恢复插件原来的 id newplugin.id = pluginid # 更新内部的插件信息 self.__modules[pluginid] = newmodule self.__plugins[pluginid] = newplugin # 启动插件 newplugin.start() def stop(self, pluginid: str) -> NoReturn: """ 尝试停止一个插件: plguinid: 要启动的插件 ID """ # 尝试获取插件实例 - 当不存在时报错 plugin: Plugin = self.__plugins.get(pluginid) if plugin is None: raise error.PluginNotFound(pluginid) # 如果插件的状态为已经暂停 - 不进行操作 if plugin.status is False: return # 尝试调用插件的停止函数 plugin.stop() plugin.status = False def clean(self) -> NoReturn: """ 清理不存在的插件: 从 self.__catalogs 中遍历目录 当目录不在当前已知的目录中时判定插件已经删除 对插件执行 stop + unload 操作 """ # 遍历目录 catalogs: set = self.__scandirs(self.__directory, settings.skipped) exists: set = set(self.__catalogs.values()) # 反转目录注册表用于查询插件id _reversed = {v: k for k, v in self.__catalogs.items()} # 检查是否有不存在的并删除 for catalog in exists: if not catalog in catalogs: pluginid: str = _reversed.get(catalog) self.unload(pluginid) def scan(self, autorun: Optional[bool] = False) -> NoReturn: """ 尝试扫描指定的父目录并从中载入所有的插件: 根据 settings.skipped 设定跳过扫描插件 """ # 载入目录后遍历查询 - 跳过已经载入的和不用载入的 skipping: set = settings.skipped or set(self.__catalogs.values()) catalogs: set = self.__scandirs(self.__directory, skipping) for catalog in catalogs: # 尝试载入插件 - 失败后放弃 try: loaded = self.__load(catalog) except error.Error as _error: logger.error(_error) continue plugin: Plugin = loaded.plugin module: ModuleType = loaded.module # 保存信息 self.__catalogs[plugin.id] = catalog self.__modules[plugin.id] = module self.__plugins[plugin.id] = plugin # 检测是否自动启动 if autorun: self.start(plugin.id) def stopall(self) -> NoReturn: """ 停止所有函数 用于在框架退出时执行所有插件的停止函数 释放插件所使用的资源 """ for pluginid, _plugin in self.__plugins.items(): self.stop(pluginid) def startall(self) -> NoReturn: """ 启动所有的插件 使用 gunicorn 时使用 preload 模式预加载之后 startall """ for pluginid, _plugin in self.__plugins.items(): self.start(pluginid)
sigprotect.py
#!/usr/bin/python # # Copyright (c) SAS Institute Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from testrunner import testhelp import os, signal from conary.lib import sigprotect class CallFlag: def __call__(self): self.called = True def wasCalled(self, reset = True): rc = self.called if reset: self.called = False return rc def __init__(self): self.called = False class SignalsTest(testhelp.TestCase): def testDecorator(self): def killself(sig): os.kill(os.getpid(), sig) def createHandler(c): def handler(*args): c() return handler def _test(sigNum, c, reraise = False): try: killself(sigNum) except sigprotect.SignalException, e: assert(e.sigNum == sigNum) c() if reraise: raise @sigprotect.sigprotect(signal.SIGTERM, signal.SIGUSR2) def catchTermUsr2(*args, **kwargs): return _test(*args, **kwargs) @sigprotect.sigprotect() def catchAll(*args, **kwargs): return _test(*args, **kwargs) sigCalled = CallFlag() handlerCalled = CallFlag() catchTermUsr2(signal.SIGUSR2, sigCalled) assert(sigCalled.wasCalled()) signal.signal(signal.SIGTERM, createHandler(handlerCalled)) catchTermUsr2(signal.SIGTERM, sigCalled, reraise = True) assert(handlerCalled.wasCalled()) assert(sigCalled.wasCalled()) signal.signal(signal.SIGTERM, signal.SIG_DFL) for sigNum in sigprotect.catchableSignals: catchAll(sigNum, sigCalled) assert(sigCalled.wasCalled()) def testCatchableList(self): l = [] for name, sigNum in sorted(signal.__dict__.items()): if not name.startswith('SIG'): continue if name.startswith('SIG_'): continue # catching SIGCHLD is evil; we don't want death of a child turning # into exceptions if name in [ 'SIGBUS', 'SIGSEGV', 'SIGCHLD', 'SIGCLD', 'SIGCONT' ]: catchable = False else: try: signal.signal(signal.__dict__[name], signal.SIG_IGN) except RuntimeError: catchable = False else: catchable = True signal.signal(signal.__dict__[name], signal.SIG_DFL) if catchable and sigNum not in sigprotect.catchableSignals: l.append(name) raise AssertionError('signal %s is catchable but is not in ' 'catchable list' % name) elif not catchable and sigNum in sigprotect.catchableSignals: raise AssertionError('signal %s is not catchable but is in ' 'catchable list' % name) def testSignalException(self): e = sigprotect.SignalException(signal.SIGHUP) assert(str(e) == 'SignalException: signal SIGHUP received') e = sigprotect.SignalException(signal.NSIG) assert(str(e) == 'SignalException: signal %d received' % signal.NSIG) def testThreading(self): @sigprotect.sigprotect() def runme(): pass import threading thread = threading.Thread(target = runme) thread.start() thread.join()
recognition_picture_20190422.py
import sys import os from random import randint from collections import OrderedDict import time import multiprocessing import threading import zmq import params from zmq.utils.monitor import recv_monitor_message sys.path.append(os.getcwd()) import torch from torch.autograd import Variable import utils import dataset from PIL import Image import models.crnn as crnn import alphabets from io import BytesIO str1 = alphabets.alphabet HEARTBEAT_LIVENESS = 5 HEARTBEAT_INTERVAL = 1.0 INTERVAL_INIT = 1 INTERVAL_MAX = 32 PPP_READY = b"\x01" NBR_WORKERS = 1 crnn_model_path = '/home/cad488/crnn_scene_recognition_kinds_36/expr/crnn_no_IO_4_56371.pth' FRONTEND_HOST = "tcp://*:5678" BACKEND_HOST= "tcp://*:5679" alphabet = str1 nclass = len(alphabet)+1 model = None # crnn文本信息识别 EVENT_MAP = {} print("Event names:") for name in dir(zmq): if name.startswith('EVENT_'): value = getattr(zmq, name) print("%21s : %4i" % (name, value)) EVENT_MAP[value] = name def event_monitor(monitor): while monitor.poll(): evt = recv_monitor_message(monitor) evt.update({'description': EVENT_MAP[evt['event']]}) print("Event: {}".format(evt)) if evt['event'] == zmq.EVENT_MONITOR_STOPPED: break monitor.close() print() print("event monitor thread done!") def crnn_recognition(cropped_image, model): converter = utils.strLabelConverter(alphabet) image = cropped_image.convert('L') ## w = int(image.size[0] / (280 * 1.0 / params.imgW)) transformer = dataset.resizeNormalize((w, 32)) image = transformer(image) #if torch.cuda.is_available(): #image = image.cuda() image = image.view(1, *image.size()) image = Variable(image) model.eval() preds = model(image) _, preds = preds.max(2) preds = preds.transpose(1, 0).contiguous().view(-1) preds_size = Variable(torch.IntTensor([preds.size(0)])) #raw_pred = converter.decode(preds.data, preds_size.data, raw=True) sim_pred = converter.decode(preds.data, preds_size.data, raw=False) #print('%-20s => %-20s' % (raw_pred, sim_preda print('result:{0}'.format(sim_pred)) return ('{0}'.format(sim_pred)) class Worker(object): def __init__(self, address): self.address = address self.expiry = time.time() + HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS class WorkerQueue(object): def __init__(self): self.queue = OrderedDict() def ready(self, worker): self.queue.pop(worker.address, None) self.queue[worker.address] = worker def purge(self): """Look for & kill expired workers.""" t = time.time() expired = [] for address,worker in self.queue.items(): if t > worker.expiry: # Worker expired expired.append(address) for address in expired: print ("expired worker: %s" % address) self.queue.pop(address, None) def next(self): address, worker = self.queue.popitem(False) return address def worker_task(worker_url,ident): #receive the request from the client or send the message to backend context = zmq.Context(1) worker = context.socket(zmq.DEALER) worker.identity = u"{}-{}".format(randint(0, 0x10000), randint(0, 0x10000)).encode("ascii") worker.connect(worker_url) # Tell broker we're ready for work worker.send(PPP_READY) poll_worker = zmq.Poller() poll_worker.register(worker, zmq.POLLIN) while True: socks = dict(poll_worker.poll(HEARTBEAT_INTERVAL * 1000)) #frames = worker.recv_multipart() # format:[b'client',b'',message_body] print("{}".format(worker.identity.decode("ascii"))) if socks.get(worker) == zmq.POLLIN: frames = worker.recv_multipart() #print("worker gets:",frames) if not frames: break # Interrupted if len(frames) == 3: print ("I: Normal reply") t1 = time.time() image = Image.open(BytesIO(frames[2])) result = crnn_recognition(image, model) t2 = time.time()-t1 print("recogition time:", t2) image.save("/home/cad488/test_images/"+ time.asctime(time.localtime(time.time()))+".jpg") worker.send_multipart([frames[0], b"", result.encode("ascii")]) else: print ("E: Invalid message: %s" % frames) def main(): """Load balancer main loop.""" # Prepare context and sockets url_worker = "tcp://localhost:5679" context = zmq.Context(1) frontend = context.socket(zmq.ROUTER) backend = context.socket(zmq.ROUTER) front_monitor = frontend.get_monitor_socket() back_monitor = backend.get_monitor_socket() frontend.bind(FRONTEND_HOST) backend.bind(BACKEND_HOST) # Start background tasks def start(task, *args): process = multiprocessing.Process(target=task, args=args)#多进程,每个进程需要自己的context #process = threading.Thread(target=task,args=args) #多线程,参数中的变量每个线程各自拥有 process.daemon = True process.start() for i in range(NBR_WORKERS): start(worker_task, url_worker,i) t = threading.Thread(target=event_monitor, args=(front_monitor,)) t.start() t2 = threading.Thread(target=event_monitor, args=(back_monitor,)) t2.start() start(event_monitor,front_monitor) start(event_monitor,back_monitor) # Initialize main loop state workers = WorkerQueue() poller = zmq.Poller() # Only poll for requests from backend until workers are available poll_workers = zmq.Poller() poll_workers.register(backend, zmq.POLLIN) poll_both = zmq.Poller() poll_both.register(frontend, zmq.POLLIN) poll_both.register(backend, zmq.POLLIN) while True: if len(workers.queue) > 0: poller = poll_both else: poller = poll_workers sockets = dict(poller.poll(HEARTBEAT_INTERVAL * 1000)) print("sockets=:",sockets) print("sockets backend:",sockets.get(backend)) print("sockets frontend:",sockets.get(frontend)) #print(zmq.POLLIN) if backend in sockets: # Handle worker activity on the backend frames = backend.recv_multipart() print("get from workers:",frames) if not frames: break address = frames[0] print("length socks:",len(workers.queue)) print("workers queue:",workers.queue) #if len(workers.queue) == 0: #poller.register(frontend, zmq.POLLIN) workers.ready(Worker(address)) msg = frames[1:] if len(msg) == 1: if msg[0] not in (PPP_READY): print("E: Invaild message from worker: %s" %msg) else: frontend.send_multipart(msg) if frontend in sockets: frames = frontend.recv_multipart() print("get from clients") if not frames: break frames.insert(0,workers.next()) #frames = [workes.next, ''] + frames backend.send_multipart(frames) #if len(workers.queue) == 0: #poller.unregister(frontend) #workers.purge() # Clean up backend.close() frontend.close() context.term() if __name__ == '__main__': # crnn network model = crnn.CRNN(32, 1, nclass, 256) #if torch.cuda.is_available(): #model = model.cuda() print('loading pretrained model from {0}'.format(crnn_model_path)) # 导入已经训练好的crnn模型 model.load_state_dict(torch.load(crnn_model_path,map_location=torch.device('cpu'))) main()
handlers.py
# Copyright 2001-2016 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ Additional handlers for the logging package for Python. The core package is based on PEP 282 and comments thereto in comp.lang.python. Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved. To use, simply 'import logging.handlers' and log away! """ import logging, socket, os, pickle, struct, time, re from stat import ST_DEV, ST_INO, ST_MTIME import queue import threading # # Some constants... # DEFAULT_TCP_LOGGING_PORT = 9020 DEFAULT_UDP_LOGGING_PORT = 9021 DEFAULT_HTTP_LOGGING_PORT = 9022 DEFAULT_SOAP_LOGGING_PORT = 9023 SYSLOG_UDP_PORT = 514 SYSLOG_TCP_PORT = 514 _MIDNIGHT = 24 * 60 * 60 # number of seconds in a day class BaseRotatingHandler(logging.FileHandler): """ Base class for handlers that rotate log files at a certain point. Not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler. """ def __init__(self, filename, mode, encoding=None, delay=False): """ Use the specified filename for streamed logging """ logging.FileHandler.__init__(self, filename, mode, encoding, delay) self.mode = mode self.encoding = encoding self.namer = None self.rotator = None def emit(self, record): """ Emit a record. Output the record to the file, catering for rollover as described in doRollover(). """ try: if self.shouldRollover(record): self.doRollover() logging.FileHandler.emit(self, record) except Exception: self.handleError(record) def rotation_filename(self, default_name): """ Modify the filename of a log file when rotating. This is provided so that a custom filename can be provided. The default implementation calls the 'namer' attribute of the handler, if it's callable, passing the default name to it. If the attribute isn't callable (the default is None), the name is returned unchanged. :param default_name: The default name for the log file. """ if not callable(self.namer): result = default_name else: result = self.namer(default_name) return result def rotate(self, source, dest): """ When rotating, rotate the current log. The default implementation calls the 'rotator' attribute of the handler, if it's callable, passing the source and dest arguments to it. If the attribute isn't callable (the default is None), the source is simply renamed to the destination. :param source: The source filename. This is normally the base filename, e.g. 'test.log' :param dest: The destination filename. This is normally what the source is rotated to, e.g. 'test.log.1'. """ if not callable(self.rotator): # Issue 18940: A file may not have been created if delay is True. if os.path.exists(source): os.rename(source, dest) else: self.rotator(source, dest) class RotatingFileHandler(BaseRotatingHandler): """ Handler for logging to a set of files, which switches from one file to the next when the current file reaches a certain size. """ def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False): """ Open the specified file and use it as the stream for logging. By default, the file grows indefinitely. You can specify particular values of maxBytes and backupCount to allow the file to rollover at a predetermined size. Rollover occurs whenever the current log file is nearly maxBytes in length. If backupCount is >= 1, the system will successively create new files with the same pathname as the base file, but with extensions ".1", ".2" etc. appended to it. For example, with a backupCount of 5 and a base file name of "app.log", you would get "app.log", "app.log.1", "app.log.2", ... through to "app.log.5". The file being written to is always "app.log" - when it gets filled up, it is closed and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc. exist, then they are renamed to "app.log.2", "app.log.3" etc. respectively. If maxBytes is zero, rollover never occurs. """ # If rotation/rollover is wanted, it doesn't make sense to use another # mode. If for example 'w' were specified, then if there were multiple # runs of the calling application, the logs from previous runs would be # lost if the 'w' is respected, because the log file would be truncated # on each run. if maxBytes > 0: mode = 'a' BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) self.maxBytes = maxBytes self.backupCount = backupCount def doRollover(self): """ Do a rollover, as described in __init__(). """ if self.stream: self.stream.close() self.stream = None if self.backupCount > 0: for i in range(self.backupCount - 1, 0, -1): sfn = self.rotation_filename("%s.%d" % (self.baseFilename, i)) dfn = self.rotation_filename("%s.%d" % (self.baseFilename, i + 1)) if os.path.exists(sfn): if os.path.exists(dfn): os.remove(dfn) os.rename(sfn, dfn) dfn = self.rotation_filename(self.baseFilename + ".1") if os.path.exists(dfn): os.remove(dfn) self.rotate(self.baseFilename, dfn) if not self.delay: self.stream = self._open() def shouldRollover(self, record): """ Determine if rollover should occur. Basically, see if the supplied record would cause the file to exceed the size limit we have. """ if self.stream is None: # delay was set... self.stream = self._open() if self.maxBytes > 0: # are we rolling over? msg = "%s\n" % self.format(record) self.stream.seek(0, 2) #due to non-posix-compliant Windows feature if self.stream.tell() + len(msg) >= self.maxBytes: return 1 return 0 class TimedRotatingFileHandler(BaseRotatingHandler): """ Handler for logging to a file, rotating the log file at certain timed intervals. If backupCount is > 0, when rollover is done, no more than backupCount files are kept - the oldest ones are deleted. """ def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None): BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay) self.when = when.upper() self.backupCount = backupCount self.utc = utc self.atTime = atTime # Calculate the real rollover interval, which is just the number of # seconds between rollovers. Also set the filename suffix used when # a rollover occurs. Current 'when' events supported: # S - Seconds # M - Minutes # H - Hours # D - Days # midnight - roll over at midnight # W{0-6} - roll over on a certain day; 0 - Monday # # Case of the 'when' specifier is not important; lower or upper case # will work. if self.when == 'S': self.interval = 1 # one second self.suffix = "%Y-%m-%d_%H-%M-%S" self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\w+)?$" elif self.when == 'M': self.interval = 60 # one minute self.suffix = "%Y-%m-%d_%H-%M" self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}(\.\w+)?$" elif self.when == 'H': self.interval = 60 * 60 # one hour self.suffix = "%Y-%m-%d_%H" self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}(\.\w+)?$" elif self.when == 'D' or self.when == 'MIDNIGHT': self.interval = 60 * 60 * 24 # one day self.suffix = "%Y-%m-%d" self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$" elif self.when.startswith('W'): self.interval = 60 * 60 * 24 * 7 # one week if len(self.when) != 2: raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when) if self.when[1] < '0' or self.when[1] > '6': raise ValueError("Invalid day specified for weekly rollover: %s" % self.when) self.dayOfWeek = int(self.when[1]) self.suffix = "%Y-%m-%d" self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$" else: raise ValueError("Invalid rollover interval specified: %s" % self.when) self.extMatch = re.compile(self.extMatch, re.ASCII) self.interval = self.interval * interval # multiply by units requested # The following line added because the filename passed in could be a # path object (see Issue #27493), but self.baseFilename will be a string filename = self.baseFilename if os.path.exists(filename): t = os.stat(filename)[ST_MTIME] else: t = int(time.time()) self.rolloverAt = self.computeRollover(t) def computeRollover(self, currentTime): """ Work out the rollover time based on the specified time. """ result = currentTime + self.interval # If we are rolling over at midnight or weekly, then the interval is already known. # What we need to figure out is WHEN the next interval is. In other words, # if you are rolling over at midnight, then your base interval is 1 day, # but you want to start that one day clock at midnight, not now. So, we # have to fudge the rolloverAt value in order to trigger the first rollover # at the right time. After that, the regular interval will take care of # the rest. Note that this code doesn't care about leap seconds. :) if self.when == 'MIDNIGHT' or self.when.startswith('W'): # This could be done with less code, but I wanted it to be clear if self.utc: t = time.gmtime(currentTime) else: t = time.localtime(currentTime) currentHour = t[3] currentMinute = t[4] currentSecond = t[5] currentDay = t[6] # r is the number of seconds left between now and the next rotation if self.atTime is None: rotate_ts = _MIDNIGHT else: rotate_ts = ((self.atTime.hour * 60 + self.atTime.minute)*60 + self.atTime.second) r = rotate_ts - ((currentHour * 60 + currentMinute) * 60 + currentSecond) if r < 0: # Rotate time is before the current time (for example when # self.rotateAt is 13:45 and it now 14:15), rotation is # tomorrow. r += _MIDNIGHT currentDay = (currentDay + 1) % 7 result = currentTime + r # If we are rolling over on a certain day, add in the number of days until # the next rollover, but offset by 1 since we just calculated the time # until the next day starts. There are three cases: # Case 1) The day to rollover is today; in this case, do nothing # Case 2) The day to rollover is further in the interval (i.e., today is # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to # next rollover is simply 6 - 2 - 1, or 3. # Case 3) The day to rollover is behind us in the interval (i.e., today # is day 5 (Saturday) and rollover is on day 3 (Thursday). # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the # number of days left in the current week (1) plus the number # of days in the next week until the rollover day (3). # The calculations described in 2) and 3) above need to have a day added. # This is because the above time calculation takes us to midnight on this # day, i.e. the start of the next day. if self.when.startswith('W'): day = currentDay # 0 is Monday if day != self.dayOfWeek: if day < self.dayOfWeek: daysToWait = self.dayOfWeek - day else: daysToWait = 6 - day + self.dayOfWeek + 1 newRolloverAt = result + (daysToWait * (60 * 60 * 24)) if not self.utc: dstNow = t[-1] dstAtRollover = time.localtime(newRolloverAt)[-1] if dstNow != dstAtRollover: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour addend = -3600 else: # DST bows out before next rollover, so we need to add an hour addend = 3600 newRolloverAt += addend result = newRolloverAt return result def shouldRollover(self, record): """ Determine if rollover should occur. record is not used, as we are just comparing times, but it is needed so the method signatures are the same """ t = int(time.time()) if t >= self.rolloverAt: return 1 return 0 def getFilesToDelete(self): """ Determine the files to delete when rolling over. More specific than the earlier method, which just used glob.glob(). """ dirName, baseName = os.path.split(self.baseFilename) fileNames = os.listdir(dirName) result = [] prefix = baseName + "." plen = len(prefix) for fileName in fileNames: if fileName[:plen] == prefix: suffix = fileName[plen:] if self.extMatch.match(suffix): result.append(os.path.join(dirName, fileName)) result.sort() if len(result) < self.backupCount: result = [] else: result = result[:len(result) - self.backupCount] return result def doRollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest suffix. """ if self.stream: self.stream.close() self.stream = None # get the time that this sequence started at and make it a TimeTuple currentTime = int(time.time()) dstNow = time.localtime(currentTime)[-1] t = self.rolloverAt - self.interval if self.utc: timeTuple = time.gmtime(t) else: timeTuple = time.localtime(t) dstThen = timeTuple[-1] if dstNow != dstThen: if dstNow: addend = 3600 else: addend = -3600 timeTuple = time.localtime(t + addend) dfn = self.rotation_filename(self.baseFilename + "." + time.strftime(self.suffix, timeTuple)) if os.path.exists(dfn): os.remove(dfn) self.rotate(self.baseFilename, dfn) if self.backupCount > 0: for s in self.getFilesToDelete(): os.remove(s) if not self.delay: self.stream = self._open() newRolloverAt = self.computeRollover(currentTime) while newRolloverAt <= currentTime: newRolloverAt = newRolloverAt + self.interval #If DST changes and midnight or weekly rollover, adjust for this. if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc: dstAtRollover = time.localtime(newRolloverAt)[-1] if dstNow != dstAtRollover: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour addend = -3600 else: # DST bows out before next rollover, so we need to add an hour addend = 3600 newRolloverAt += addend self.rolloverAt = newRolloverAt class WatchedFileHandler(logging.FileHandler): """ A handler for logging to a file, which watches the file to see if it has changed while in use. This can happen because of usage of programs such as newsyslog and logrotate which perform log file rotation. This handler, intended for use under Unix, watches the file to see if it has changed since the last emit. (A file has changed if its device or inode have changed.) If it has changed, the old file stream is closed, and the file opened to get a new stream. This handler is not appropriate for use under Windows, because under Windows open files cannot be moved or renamed - logging opens the files with exclusive locks - and so there is no need for such a handler. Furthermore, ST_INO is not supported under Windows; stat always returns zero for this value. This handler is based on a suggestion and patch by Chad J. Schroeder. """ def __init__(self, filename, mode='a', encoding=None, delay=False): logging.FileHandler.__init__(self, filename, mode, encoding, delay) self.dev, self.ino = -1, -1 self._statstream() def _statstream(self): if self.stream: sres = os.fstat(self.stream.fileno()) self.dev, self.ino = sres[ST_DEV], sres[ST_INO] def reopenIfNeeded(self): """ Reopen log file if needed. Checks if the underlying file has changed, and if it has, close the old stream and reopen the file to get the current stream. """ # Reduce the chance of race conditions by stat'ing by path only # once and then fstat'ing our new fd if we opened a new log stream. # See issue #14632: Thanks to John Mulligan for the problem report # and patch. try: # stat the file by path, checking for existence sres = os.stat(self.baseFilename) except FileNotFoundError: sres = None # compare file system stat with that of our stream file handle if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino: if self.stream is not None: # we have an open file handle, clean it up self.stream.flush() self.stream.close() self.stream = None # See Issue #21742: _open () might fail. # open a new file handle and get new stat info from that fd self.stream = self._open() self._statstream() def emit(self, record): """ Emit a record. If underlying file has changed, reopen the file before emitting the record to it. """ self.reopenIfNeeded() logging.FileHandler.emit(self, record) class SocketHandler(logging.Handler): """ A handler class which writes logging records, in pickle format, to a streaming socket. The socket is kept open across logging calls. If the peer resets it, an attempt is made to reconnect on the next call. The pickle which is sent is that of the LogRecord's attribute dictionary (__dict__), so that the receiver does not need to have the logging module installed in order to process the logging event. To unpickle the record at the receiving end into a LogRecord, use the makeLogRecord function. """ def __init__(self, host, port): """ Initializes the handler with a specific host address and port. When the attribute *closeOnError* is set to True - if a socket error occurs, the socket is silently closed and then reopened on the next logging call. """ logging.Handler.__init__(self) self.host = host self.port = port if port is None: self.address = host else: self.address = (host, port) self.sock = None self.closeOnError = False self.retryTime = None # # Exponential backoff parameters. # self.retryStart = 1.0 self.retryMax = 30.0 self.retryFactor = 2.0 def makeSocket(self, timeout=1): """ A factory method which allows subclasses to define the precise type of socket they want. """ if self.port is not None: result = socket.create_connection(self.address, timeout=timeout) else: result = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) result.settimeout(timeout) try: result.connect(self.address) except OSError: result.close() # Issue 19182 raise return result def createSocket(self): """ Try to create a socket, using an exponential backoff with a max retry time. Thanks to Robert Olson for the original patch (SF #815911) which has been slightly refactored. """ now = time.time() # Either retryTime is None, in which case this # is the first time back after a disconnect, or # we've waited long enough. if self.retryTime is None: attempt = True else: attempt = (now >= self.retryTime) if attempt: try: self.sock = self.makeSocket() self.retryTime = None # next time, no delay before trying except OSError: #Creation failed, so set the retry time and return. if self.retryTime is None: self.retryPeriod = self.retryStart else: self.retryPeriod = self.retryPeriod * self.retryFactor if self.retryPeriod > self.retryMax: self.retryPeriod = self.retryMax self.retryTime = now + self.retryPeriod def send(self, s): """ Send a pickled string to the socket. This function allows for partial sends which can happen when the network is busy. """ if self.sock is None: self.createSocket() #self.sock can be None either because we haven't reached the retry #time yet, or because we have reached the retry time and retried, #but are still unable to connect. if self.sock: try: self.sock.sendall(s) except OSError: #pragma: no cover self.sock.close() self.sock = None # so we can call createSocket next time def makePickle(self, record): """ Pickles the record in binary format with a length prefix, and returns it ready for transmission across the socket. """ ei = record.exc_info if ei: # just to get traceback text into record.exc_text ... dummy = self.format(record) # See issue #14436: If msg or args are objects, they may not be # available on the receiving end. So we convert the msg % args # to a string, save it as msg and zap the args. d = dict(record.__dict__) d['msg'] = record.getMessage() d['args'] = None d['exc_info'] = None # Issue #25685: delete 'message' if present: redundant with 'msg' d.pop('message', None) s = pickle.dumps(d, 1) slen = struct.pack(">L", len(s)) return slen + s def handleError(self, record): """ Handle an error during logging. An error has occurred during logging. Most likely cause - connection lost. Close the socket so that we can retry on the next event. """ if self.closeOnError and self.sock: self.sock.close() self.sock = None #try to reconnect next time else: logging.Handler.handleError(self, record) def emit(self, record): """ Emit a record. Pickles the record and writes it to the socket in binary format. If there is an error with the socket, silently drop the packet. If there was a problem with the socket, re-establishes the socket. """ try: s = self.makePickle(record) self.send(s) except Exception: self.handleError(record) def close(self): """ Closes the socket. """ self.acquire() try: sock = self.sock if sock: self.sock = None sock.close() logging.Handler.close(self) finally: self.release() class DatagramHandler(SocketHandler): """ A handler class which writes logging records, in pickle format, to a datagram socket. The pickle which is sent is that of the LogRecord's attribute dictionary (__dict__), so that the receiver does not need to have the logging module installed in order to process the logging event. To unpickle the record at the receiving end into a LogRecord, use the makeLogRecord function. """ def __init__(self, host, port): """ Initializes the handler with a specific host address and port. """ SocketHandler.__init__(self, host, port) self.closeOnError = False def makeSocket(self): """ The factory method of SocketHandler is here overridden to create a UDP socket (SOCK_DGRAM). """ if self.port is None: family = socket.AF_UNIX else: family = socket.AF_INET s = socket.socket(family, socket.SOCK_DGRAM) return s def send(self, s): """ Send a pickled string to a socket. This function no longer allows for partial sends which can happen when the network is busy - UDP does not guarantee delivery and can deliver packets out of sequence. """ if self.sock is None: self.createSocket() self.sock.sendto(s, self.address) class SysLogHandler(logging.Handler): """ A handler class which sends formatted logging records to a syslog server. Based on Sam Rushing's syslog module: http://www.nightmare.com/squirl/python-ext/misc/syslog.py Contributed by Nicolas Untz (after which minor refactoring changes have been made). """ # from <linux/sys/syslog.h>: # ====================================================================== # priorities/facilities are encoded into a single 32-bit quantity, where # the bottom 3 bits are the priority (0-7) and the top 28 bits are the # facility (0-big number). Both the priorities and the facilities map # roughly one-to-one to strings in the syslogd(8) source code. This # mapping is included in this file. # # priorities (these are ordered) LOG_EMERG = 0 # system is unusable LOG_ALERT = 1 # action must be taken immediately LOG_CRIT = 2 # critical conditions LOG_ERR = 3 # error conditions LOG_WARNING = 4 # warning conditions LOG_NOTICE = 5 # normal but significant condition LOG_INFO = 6 # informational LOG_DEBUG = 7 # debug-level messages # facility codes LOG_KERN = 0 # kernel messages LOG_USER = 1 # random user-level messages LOG_MAIL = 2 # mail system LOG_DAEMON = 3 # system daemons LOG_AUTH = 4 # security/authorization messages LOG_SYSLOG = 5 # messages generated internally by syslogd LOG_LPR = 6 # line printer subsystem LOG_NEWS = 7 # network news subsystem LOG_UUCP = 8 # UUCP subsystem LOG_CRON = 9 # clock daemon LOG_AUTHPRIV = 10 # security/authorization messages (private) LOG_FTP = 11 # FTP daemon # other codes through 15 reserved for system use LOG_LOCAL0 = 16 # reserved for local use LOG_LOCAL1 = 17 # reserved for local use LOG_LOCAL2 = 18 # reserved for local use LOG_LOCAL3 = 19 # reserved for local use LOG_LOCAL4 = 20 # reserved for local use LOG_LOCAL5 = 21 # reserved for local use LOG_LOCAL6 = 22 # reserved for local use LOG_LOCAL7 = 23 # reserved for local use priority_names = { "alert": LOG_ALERT, "crit": LOG_CRIT, "critical": LOG_CRIT, "debug": LOG_DEBUG, "emerg": LOG_EMERG, "err": LOG_ERR, "error": LOG_ERR, # DEPRECATED "info": LOG_INFO, "notice": LOG_NOTICE, "panic": LOG_EMERG, # DEPRECATED "warn": LOG_WARNING, # DEPRECATED "warning": LOG_WARNING, } facility_names = { "auth": LOG_AUTH, "authpriv": LOG_AUTHPRIV, "cron": LOG_CRON, "daemon": LOG_DAEMON, "ftp": LOG_FTP, "kern": LOG_KERN, "lpr": LOG_LPR, "mail": LOG_MAIL, "news": LOG_NEWS, "security": LOG_AUTH, # DEPRECATED "syslog": LOG_SYSLOG, "user": LOG_USER, "uucp": LOG_UUCP, "local0": LOG_LOCAL0, "local1": LOG_LOCAL1, "local2": LOG_LOCAL2, "local3": LOG_LOCAL3, "local4": LOG_LOCAL4, "local5": LOG_LOCAL5, "local6": LOG_LOCAL6, "local7": LOG_LOCAL7, } #The map below appears to be trivially lowercasing the key. However, #there's more to it than meets the eye - in some locales, lowercasing #gives unexpected results. See SF #1524081: in the Turkish locale, #"INFO".lower() != "info" priority_map = { "DEBUG" : "debug", "INFO" : "info", "WARNING" : "warning", "ERROR" : "error", "CRITICAL" : "critical" } def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=None): """ Initialize a handler. If address is specified as a string, a UNIX socket is used. To log to a local syslogd, "SysLogHandler(address="/dev/log")" can be used. If facility is not specified, LOG_USER is used. If socktype is specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific socket type will be used. For Unix sockets, you can also specify a socktype of None, in which case socket.SOCK_DGRAM will be used, falling back to socket.SOCK_STREAM. """ logging.Handler.__init__(self) self.address = address self.facility = facility self.socktype = socktype if isinstance(address, str): self.unixsocket = True # Syslog server may be unavailable during handler initialisation. # C's openlog() function also ignores connection errors. # Moreover, we ignore these errors while logging, so it not worse # to ignore it also here. try: self._connect_unixsocket(address) except OSError: pass else: self.unixsocket = False if socktype is None: socktype = socket.SOCK_DGRAM host, port = address ress = socket.getaddrinfo(host, port, 0, socktype) if not ress: raise OSError("getaddrinfo returns an empty list") for res in ress: af, socktype, proto, _, sa = res err = sock = None try: sock = socket.socket(af, socktype, proto) if socktype == socket.SOCK_STREAM: sock.connect(sa) break except OSError as exc: err = exc if sock is not None: sock.close() if err is not None: raise err self.socket = sock self.socktype = socktype def _connect_unixsocket(self, address): use_socktype = self.socktype if use_socktype is None: use_socktype = socket.SOCK_DGRAM self.socket = socket.socket(socket.AF_UNIX, use_socktype) try: self.socket.connect(address) # it worked, so set self.socktype to the used type self.socktype = use_socktype except OSError: self.socket.close() if self.socktype is not None: # user didn't specify falling back, so fail raise use_socktype = socket.SOCK_STREAM self.socket = socket.socket(socket.AF_UNIX, use_socktype) try: self.socket.connect(address) # it worked, so set self.socktype to the used type self.socktype = use_socktype except OSError: self.socket.close() raise def encodePriority(self, facility, priority): """ Encode the facility and priority. You can pass in strings or integers - if strings are passed, the facility_names and priority_names mapping dictionaries are used to convert them to integers. """ if isinstance(facility, str): facility = self.facility_names[facility] if isinstance(priority, str): priority = self.priority_names[priority] return (facility << 3) | priority def close(self): """ Closes the socket. """ self.acquire() try: self.socket.close() logging.Handler.close(self) finally: self.release() def mapPriority(self, levelName): """ Map a logging level name to a key in the priority_names map. This is useful in two scenarios: when custom levels are being used, and in the case where you can't do a straightforward mapping by lowercasing the logging level name because of locale- specific issues (see SF #1524081). """ return self.priority_map.get(levelName, "warning") ident = '' # prepended to all messages append_nul = True # some old syslog daemons expect a NUL terminator def emit(self, record): """ Emit a record. The record is formatted, and then sent to the syslog server. If exception information is present, it is NOT sent to the server. """ try: msg = self.format(record) if self.ident: msg = self.ident + msg if self.append_nul: msg += '\000' # We need to convert record level to lowercase, maybe this will # change in the future. prio = '<%d>' % self.encodePriority(self.facility, self.mapPriority(record.levelname)) prio = prio.encode('utf-8') # Message is a string. Convert to bytes as required by RFC 5424 msg = msg.encode('utf-8') msg = prio + msg if self.unixsocket: try: self.socket.send(msg) except OSError: self.socket.close() self._connect_unixsocket(self.address) self.socket.send(msg) elif self.socktype == socket.SOCK_DGRAM: self.socket.sendto(msg, self.address) else: self.socket.sendall(msg) except Exception: self.handleError(record) class SMTPHandler(logging.Handler): """ A handler class which sends an SMTP email for each logging event. """ def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=5.0): """ Initialize the handler. Initialize the instance with the from and to addresses and subject line of the email. To specify a non-standard SMTP port, use the (host, port) tuple format for the mailhost argument. To specify authentication credentials, supply a (username, password) tuple for the credentials argument. To specify the use of a secure protocol (TLS), pass in a tuple for the secure argument. This will only be used when authentication credentials are supplied. The tuple will be either an empty tuple, or a single-value tuple with the name of a keyfile, or a 2-value tuple with the names of the keyfile and certificate file. (This tuple is passed to the `starttls` method). A timeout in seconds can be specified for the SMTP connection (the default is one second). """ logging.Handler.__init__(self) if isinstance(mailhost, (list, tuple)): self.mailhost, self.mailport = mailhost else: self.mailhost, self.mailport = mailhost, None if isinstance(credentials, (list, tuple)): self.username, self.password = credentials else: self.username = None self.fromaddr = fromaddr if isinstance(toaddrs, str): toaddrs = [toaddrs] self.toaddrs = toaddrs self.subject = subject self.secure = secure self.timeout = timeout def getSubject(self, record): """ Determine the subject for the email. If you want to specify a subject line which is record-dependent, override this method. """ return self.subject def emit(self, record): """ Emit a record. Format the record and send it to the specified addressees. """ try: import smtplib from email.message import EmailMessage import email.utils port = self.mailport if not port: port = smtplib.SMTP_PORT smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout) msg = EmailMessage() msg['From'] = self.fromaddr msg['To'] = ','.join(self.toaddrs) msg['Subject'] = self.getSubject(record) msg['Date'] = email.utils.localtime() msg.set_content(self.format(record)) if self.username: if self.secure is not None: smtp.ehlo() smtp.starttls(*self.secure) smtp.ehlo() smtp.login(self.username, self.password) smtp.send_message(msg) smtp.quit() except Exception: self.handleError(record) class NTEventLogHandler(logging.Handler): """ A handler class which sends events to the NT Event Log. Adds a registry entry for the specified application name. If no dllname is provided, win32service.pyd (which contains some basic message placeholders) is used. Note that use of these placeholders will make your event logs big, as the entire message source is held in the log. If you want slimmer logs, you have to pass in the name of your own DLL which contains the message definitions you want to use in the event log. """ def __init__(self, appname, dllname=None, logtype="Application"): logging.Handler.__init__(self) try: import win32evtlogutil, win32evtlog self.appname = appname self._welu = win32evtlogutil if not dllname: dllname = os.path.split(self._welu.__file__) dllname = os.path.split(dllname[0]) dllname = os.path.join(dllname[0], r'win32service.pyd') self.dllname = dllname self.logtype = logtype self._welu.AddSourceToRegistry(appname, dllname, logtype) self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE self.typemap = { logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE, logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE, logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE, logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE, logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, } except ImportError: print("The Python Win32 extensions for NT (service, event "\ "logging) appear not to be available.") self._welu = None def getMessageID(self, record): """ Return the message ID for the event record. If you are using your own messages, you could do this by having the msg passed to the logger being an ID rather than a formatting string. Then, in here, you could use a dictionary lookup to get the message ID. This version returns 1, which is the base message ID in win32service.pyd. """ return 1 def getEventCategory(self, record): """ Return the event category for the record. Override this if you want to specify your own categories. This version returns 0. """ return 0 def getEventType(self, record): """ Return the event type for the record. Override this if you want to specify your own types. This version does a mapping using the handler's typemap attribute, which is set up in __init__() to a dictionary which contains mappings for DEBUG, INFO, WARNING, ERROR and CRITICAL. If you are using your own levels you will either need to override this method or place a suitable dictionary in the handler's typemap attribute. """ return self.typemap.get(record.levelno, self.deftype) def emit(self, record): """ Emit a record. Determine the message ID, event category and event type. Then log the message in the NT event log. """ if self._welu: try: id = self.getMessageID(record) cat = self.getEventCategory(record) type = self.getEventType(record) msg = self.format(record) self._welu.ReportEvent(self.appname, id, cat, type, [msg]) except Exception: self.handleError(record) def close(self): """ Clean up this handler. You can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the DLL name. """ #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype) logging.Handler.close(self) class HTTPHandler(logging.Handler): """ A class which sends records to a Web server, using either GET or POST semantics. """ def __init__(self, host, url, method="GET", secure=False, credentials=None, context=None): """ Initialize the instance with the host, the request URL, and the method ("GET" or "POST") """ logging.Handler.__init__(self) method = method.upper() if method not in ["GET", "POST"]: raise ValueError("method must be GET or POST") if not secure and context is not None: raise ValueError("context parameter only makes sense " "with secure=True") self.host = host self.url = url self.method = method self.secure = secure self.credentials = credentials self.context = context def mapLogRecord(self, record): """ Default implementation of mapping the log record into a dict that is sent as the CGI data. Overwrite in your class. Contributed by Franz Glasner. """ return record.__dict__ def emit(self, record): """ Emit a record. Send the record to the Web server as a percent-encoded dictionary """ try: import http.client, urllib.parse host = self.host if self.secure: h = http.client.HTTPSConnection(host, context=self.context) else: h = http.client.HTTPConnection(host) url = self.url data = urllib.parse.urlencode(self.mapLogRecord(record)) if self.method == "GET": if (url.find('?') >= 0): sep = '&' else: sep = '?' url = url + "%c%s" % (sep, data) h.putrequest(self.method, url) # support multiple hosts on one IP address... # need to strip optional :port from host, if present i = host.find(":") if i >= 0: host = host[:i] h.putheader("Host", host) if self.method == "POST": h.putheader("Content-type", "application/x-www-form-urlencoded") h.putheader("Content-length", str(len(data))) if self.credentials: import base64 s = ('%s:%s' % self.credentials).encode('utf-8') s = 'Basic ' + base64.b64encode(s).strip().decode('ascii') h.putheader('Authorization', s) h.endheaders() if self.method == "POST": h.send(data.encode('utf-8')) h.getresponse() #can't do anything with the result except Exception: self.handleError(record) class BufferingHandler(logging.Handler): """ A handler class which buffers logging records in memory. Whenever each record is added to the buffer, a check is made to see if the buffer should be flushed. If it should, then flush() is expected to do what's needed. """ def __init__(self, capacity): """ Initialize the handler with the buffer size. """ logging.Handler.__init__(self) self.capacity = capacity self.buffer = [] def shouldFlush(self, record): """ Should the handler flush its buffer? Returns true if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies. """ return (len(self.buffer) >= self.capacity) def emit(self, record): """ Emit a record. Append the record. If shouldFlush() tells us to, call flush() to process the buffer. """ self.buffer.append(record) if self.shouldFlush(record): self.flush() def flush(self): """ Override to implement custom flushing behaviour. This version just zaps the buffer to empty. """ self.acquire() try: self.buffer = [] finally: self.release() def close(self): """ Close the handler. This version just flushes and chains to the parent class' close(). """ try: self.flush() finally: logging.Handler.close(self) class MemoryHandler(BufferingHandler): """ A handler class which buffers logging records in memory, periodically flushing them to a target handler. Flushing occurs whenever the buffer is full, or when an event of a certain severity or greater is seen. """ def __init__(self, capacity, flushLevel=logging.ERROR, target=None, flushOnClose=True): """ Initialize the handler with the buffer size, the level at which flushing should occur and an optional target. Note that without a target being set either here or via setTarget(), a MemoryHandler is no use to anyone! The ``flushOnClose`` argument is ``True`` for backward compatibility reasons - the old behaviour is that when the handler is closed, the buffer is flushed, even if the flush level hasn't been exceeded nor the capacity exceeded. To prevent this, set ``flushOnClose`` to ``False``. """ BufferingHandler.__init__(self, capacity) self.flushLevel = flushLevel self.target = target # See Issue #26559 for why this has been added self.flushOnClose = flushOnClose def shouldFlush(self, record): """ Check for buffer full or a record at the flushLevel or higher. """ return (len(self.buffer) >= self.capacity) or \ (record.levelno >= self.flushLevel) def setTarget(self, target): """ Set the target handler for this handler. """ self.target = target def flush(self): """ For a MemoryHandler, flushing means just sending the buffered records to the target, if there is one. Override if you want different behaviour. The record buffer is also cleared by this operation. """ self.acquire() try: if self.target: for record in self.buffer: self.target.handle(record) self.buffer = [] finally: self.release() def close(self): """ Flush, if appropriately configured, set the target to None and lose the buffer. """ try: if self.flushOnClose: self.flush() finally: self.acquire() try: self.target = None BufferingHandler.close(self) finally: self.release() class QueueHandler(logging.Handler): """ This handler sends events to a queue. Typically, it would be used together with a multiprocessing Queue to centralise logging to file in one process (in a multi-process application), so as to avoid file write contention between processes. This code is new in Python 3.2, but this class can be copy pasted into user code for use with earlier Python versions. """ def __init__(self, queue): """ Initialise an instance, using the passed queue. """ logging.Handler.__init__(self) self.queue = queue def enqueue(self, record): """ Enqueue a record. The base implementation uses put_nowait. You may want to override this method if you want to use blocking, timeouts or custom queue implementations. """ self.queue.put_nowait(record) def prepare(self, record): """ Prepares a record for queuing. The object returned by this method is enqueued. The base implementation formats the record to merge the message and arguments, and removes unpickleable items from the record in-place. You might want to override this method if you want to convert the record to a dict or JSON string, or send a modified copy of the record while leaving the original intact. """ # The format operation gets traceback text into record.exc_text # (if there's exception data), and also returns the formatted # message. We can then use this to replace the original # msg + args, as these might be unpickleable. We also zap the # exc_info attribute, as it's no longer needed and, if not None, # will typically not be pickleable. msg = self.format(record) record.message = msg record.msg = msg record.args = None record.exc_info = None return record def emit(self, record): """ Emit a record. Writes the LogRecord to the queue, preparing it for pickling first. """ try: self.enqueue(self.prepare(record)) except Exception: self.handleError(record) class QueueListener(object): """ This class implements an internal threaded listener which watches for LogRecords being added to a queue, removes them and passes them to a list of handlers for processing. """ _sentinel = None def __init__(self, queue, *handlers, respect_handler_level=False): """ Initialise an instance with the specified queue and handlers. """ self.queue = queue self.handlers = handlers self._thread = None self.respect_handler_level = respect_handler_level def dequeue(self, block): """ Dequeue a record and return it, optionally blocking. The base implementation uses get. You may want to override this method if you want to use timeouts or work with custom queue implementations. """ return self.queue.get(block) def start(self): """ Start the listener. This starts up a background thread to monitor the queue for LogRecords to process. """ self._thread = t = threading.Thread(target=self._monitor) t.daemon = True t.start() def prepare(self , record): """ Prepare a record for handling. This method just returns the passed-in record. You may want to override this method if you need to do any custom marshalling or manipulation of the record before passing it to the handlers. """ return record def handle(self, record): """ Handle a record. This just loops through the handlers offering them the record to handle. """ record = self.prepare(record) for handler in self.handlers: if not self.respect_handler_level: process = True else: process = record.levelno >= handler.level if process: handler.handle(record) def _monitor(self): """ Monitor the queue for records, and ask the handler to deal with them. This method runs on a separate, internal thread. The thread will terminate if it sees a sentinel object in the queue. """ q = self.queue has_task_done = hasattr(q, 'task_done') while True: try: record = self.dequeue(True) if record is self._sentinel: break self.handle(record) if has_task_done: q.task_done() except queue.Empty: break def enqueue_sentinel(self): """ This is used to enqueue the sentinel record. The base implementation uses put_nowait. You may want to override this method if you want to use timeouts or work with custom queue implementations. """ self.queue.put_nowait(self._sentinel) def stop(self): """ Stop the listener. This asks the thread to terminate, and then waits for it to do so. Note that if you don't call this before your application exits, there may be some records still left on the queue, which won't be processed. """ self.enqueue_sentinel() self._thread.join() self._thread = None
awsrepo.py
import threading from threading import Thread import logging from utilities.response import post_error import boto3 from config import aws_access_key, aws_secret_key, aws_bucket_name,aws_link_prefix,download_folder import os log = logging.getLogger('file') class AwsFileRepo(): #uploading file to S3 bucket def upload_file_to_s3(self,file_path, file_name,folder): s3_file_name =folder+"/"+ file_name s3_client = boto3.client('s3', aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key) log.info(f'Pushing {file_path} to S3 at {s3_file_name} on a new fork......') persister = threading.Thread(target=self.upload_file, args=(s3_client,file_path,s3_file_name)) persister.start() return f'{aws_link_prefix}{s3_file_name}' #downloading file from S3 bucket def download_file_from_s3(self, s3_file_name): s3_client = boto3.client('s3', aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key) output_filepath = os.path.join( download_folder, s3_file_name) try: log.info("\nDownloading file to \n\t" + output_filepath) s3_client.download_file(aws_bucket_name, s3_file_name,output_filepath) return output_filepath except Exception as e: log.exception(e) return post_error("Service Exception",f"Exception occurred:{e}") #removing file from S3 bucket def remove_file_from_s3(self, s3_file_name): log.info(f'Deleting {s3_file_name} from S3......') s3_client = boto3.client('s3', aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key) try: objects = [{"Key": s3_file_name}] response = s3_client.delete_objects(Bucket=aws_bucket_name, Delete={"Objects": objects}) return response except Exception as e: log.exception(e) return False def upload_file(self,s3_client,file_path,s3_file_name): try: s3_client.upload_file(file_path, aws_bucket_name, s3_file_name) os.remove(file_path) except Exception as e: log.exception(f'Exception while pushing to s3: {e}', e)
saltmod.py
# -*- coding: utf-8 -*- ''' Control the Salt command interface ================================== This state is intended for use from the Salt Master. It provides access to sending commands down to minions as well as access to executing master-side modules. These state functions wrap Salt's :ref:`Python API <python-api>`. .. versionadded: 2016.11.0 Support for masterless minions was added to the ``salt.state`` function, so they can run orchestration sls files. This is particularly useful when the rendering of a state is dependent on the execution of another state. Orchestration will render and execute each orchestration block independently, while honoring requisites to ensure the states are applied in the correct order. .. seealso:: More Orchestrate documentation * :ref:`Full Orchestrate Tutorial <orchestrate-runner>` * :py:func:`The Orchestrate runner <salt.runners.state.orchestrate>` ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import fnmatch import logging import sys import threading import time # Import salt libs import salt.syspaths import salt.exceptions import salt.output import salt.utils.data import salt.utils.event from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'salt' def __virtual__(): ''' Named salt ''' return __virtualname__ def _fire_args(tag_data): try: salt.utils.event.fire_args(__opts__, __orchestration_jid__, tag_data, 'run') except NameError: log.debug( 'Unable to fire args event due to missing __orchestration_jid__' ) def _parallel_map(func, inputs): ''' Applies a function to each element of a list, returning the resulting list. A separate thread is created for each element in the input list and the passed function is called for each of the elements. When all threads have finished execution a list with the results corresponding to the inputs is returned. If one of the threads fails (because the function throws an exception), that exception is reraised. If more than one thread fails, the exception from the first thread (according to the index of the input element) is reraised. func: function that is applied on each input element. inputs: list of elements that shall be processed. The length of this list also defines the number of threads created. ''' outputs = len(inputs) * [None] errors = len(inputs) * [None] def create_thread(index): def run_thread(): try: outputs[index] = func(inputs[index]) except: # pylint: disable=bare-except errors[index] = sys.exc_info() thread = threading.Thread(target=run_thread) thread.start() return thread threads = list(six.moves.map(create_thread, six.moves.range(len(inputs)))) for thread in threads: thread.join() for error in errors: if error is not None: exc_type, exc_value, exc_traceback = error six.reraise(exc_type, exc_value, exc_traceback) return outputs def state(name, tgt, ssh=False, tgt_type='glob', ret='', ret_config=None, ret_kwargs=None, highstate=None, sls=None, top=None, saltenv=None, test=None, pillar=None, pillarenv=None, expect_minions=True, fail_minions=None, allow_fail=0, concurrent=False, timeout=None, batch=None, queue=False, subset=None, orchestration_jid=None, **kwargs): ''' Invoke a state run on a given target name An arbitrary name used to track the state execution tgt The target specification for the state run. .. versionadded: 2016.11.0 Masterless support: When running on a masterless minion, the ``tgt`` is ignored and will always be the local minion. tgt_type The target type to resolve, defaults to ``glob`` ret Optionally set a single or a list of returners to use ret_config Use an alternative returner configuration ret_kwargs Override individual returner configuration items highstate Defaults to None, if set to True the target systems will ignore any sls references specified in the sls option and call state.highstate on the targeted minions top Should be the name of a top file. If set state.top is called with this top file instead of state.sls. sls A group of sls files to execute. This can be defined as a single string containing a single sls file, or a list of sls files test Pass ``test=true`` or ``test=false`` through to the state function. This can be used to overide a test mode set in the minion's config file. If left as the default of None and the 'test' mode is supplied on the command line, that value is passed instead. pillar Pass the ``pillar`` kwarg through to the state function pillarenv The pillar environment to grab pillars from .. versionadded:: 2017.7.0 saltenv The default salt environment to pull sls files from ssh Set to `True` to use the ssh client instead of the standard salt client roster In the event of using salt-ssh, a roster system can be set expect_minions An optional boolean for failing if some minions do not respond fail_minions An optional list of targeted minions where failure is an option allow_fail Pass in the number of minions to allow for failure before setting the result of the execution to False concurrent Allow multiple state runs to occur at once. WARNING: This flag is potentially dangerous. It is designed for use when multiple state runs can safely be run at the same Do not use this flag for performance optimization. queue Pass ``queue=true`` through to the state function batch Execute the command :ref:`in batches <targeting-batch>`. E.g.: ``10%``. .. versionadded:: 2016.3.0 subset Number of minions from the targeted set to randomly use .. versionadded:: 2017.7.0 Examples: Run a list of sls files via :py:func:`state.sls <salt.state.sls>` on target minions: .. code-block:: yaml webservers: salt.state: - tgt: 'web*' - sls: - apache - django - core - saltenv: prod Run a full :py:func:`state.highstate <salt.state.highstate>` on target mininons. .. code-block:: yaml databases: salt.state: - tgt: role:database - tgt_type: grain - highstate: True ''' cmd_kw = {'arg': [], 'kwarg': {}, 'ret': ret, 'timeout': timeout} if ret_config: cmd_kw['ret_config'] = ret_config if ret_kwargs: cmd_kw['ret_kwargs'] = ret_kwargs state_ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} try: allow_fail = int(allow_fail) except ValueError: state_ret['result'] = False state_ret['comment'] = 'Passed invalid value for \'allow_fail\', must be an int' return state_ret cmd_kw['tgt_type'] = tgt_type cmd_kw['ssh'] = ssh cmd_kw['expect_minions'] = expect_minions if highstate: fun = 'state.highstate' elif top: fun = 'state.top' cmd_kw['arg'].append(top) elif sls: fun = 'state.sls' if isinstance(sls, list): sls = ','.join(sls) cmd_kw['arg'].append(sls) else: state_ret['comment'] = 'No highstate or sls specified, no execution made' state_ret['result'] = False return state_ret if test is not None or __opts__.get('test'): cmd_kw['kwarg']['test'] = test if test is not None else __opts__.get('test') if pillar: cmd_kw['kwarg']['pillar'] = pillar if pillarenv is not None: cmd_kw['kwarg']['pillarenv'] = pillarenv if saltenv is not None: cmd_kw['kwarg']['saltenv'] = saltenv cmd_kw['kwarg']['queue'] = queue if isinstance(concurrent, bool): cmd_kw['kwarg']['concurrent'] = concurrent else: state_ret['comment'] = ('Must pass in boolean for value of \'concurrent\'') state_ret['result'] = False return state_ret if batch is not None: cmd_kw['batch'] = six.text_type(batch) if subset is not None: cmd_kw['subset'] = subset masterless = __opts__['__role'] == 'minion' and \ __opts__['file_client'] == 'local' if not masterless: _fire_args({'type': 'state', 'tgt': tgt, 'name': name, 'args': cmd_kw}) cmd_ret = __salt__['saltutil.cmd'](tgt, fun, **cmd_kw) else: if top: cmd_kw['topfn'] = ''.join(cmd_kw.pop('arg')) elif sls: cmd_kw['mods'] = ''.join(cmd_kw.pop('arg')) cmd_kw.update(cmd_kw.pop('kwarg')) tmp_ret = __salt__[fun](**cmd_kw) cmd_ret = {__opts__['id']: { 'ret': tmp_ret, 'out': tmp_ret.get('out', 'highstate') if isinstance(tmp_ret, dict) else 'highstate' }} try: state_ret['__jid__'] = cmd_ret[next(iter(cmd_ret))]['jid'] except (StopIteration, KeyError): pass changes = {} fail = set() no_change = set() if fail_minions is None: fail_minions = () elif isinstance(fail_minions, six.string_types): fail_minions = [minion.strip() for minion in fail_minions.split(',')] elif not isinstance(fail_minions, list): state_ret.setdefault('warnings', []).append( '\'fail_minions\' needs to be a list or a comma separated ' 'string. Ignored.' ) fail_minions = () if not cmd_ret and expect_minions: state_ret['result'] = False state_ret['comment'] = 'No minions returned' return state_ret for minion, mdata in six.iteritems(cmd_ret): if mdata.get('out', '') != 'highstate': log.warning('Output from salt state not highstate') m_ret = False if 'return' in mdata and 'ret' not in mdata: mdata['ret'] = mdata.pop('return') m_state = True if mdata.get('failed', False): m_state = False else: try: m_ret = mdata['ret'] except KeyError: m_state = False if m_state: m_state = __utils__['state.check_result'](m_ret, recurse=True) if not m_state: if minion not in fail_minions: fail.add(minion) changes[minion] = m_ret continue try: for state_item in six.itervalues(m_ret): if isinstance(state_item, dict): if 'changes' in state_item and state_item['changes']: changes[minion] = m_ret break else: no_change.add(minion) except AttributeError: log.error("m_ret did not have changes %s %s", type(m_ret), m_ret) no_change.add(minion) if changes: state_ret['changes'] = {'out': 'highstate', 'ret': changes} if len(fail) > allow_fail: state_ret['result'] = False state_ret['comment'] = 'Run failed on minions: {0}'.format(', '.join(fail)) else: state_ret['comment'] = 'States ran successfully.' if changes: state_ret['comment'] += ' Updating {0}.'.format(', '.join(changes)) if no_change: state_ret['comment'] += ' No changes made to {0}.'.format(', '.join(no_change)) if test or __opts__.get('test'): if state_ret['changes'] and state_ret['result'] is True: # Test mode with changes is the only case where result should ever be none state_ret['result'] = None return state_ret def function( name, tgt, ssh=False, tgt_type='glob', ret='', ret_config=None, ret_kwargs=None, expect_minions=False, fail_minions=None, fail_function=None, arg=None, kwarg=None, timeout=None, batch=None, subset=None): ''' Execute a single module function on a remote minion via salt or salt-ssh name The name of the function to run, aka cmd.run or pkg.install tgt The target specification, aka '*' for all minions tgt_type The target type, defaults to ``glob`` arg The list of arguments to pass into the function kwarg The dict (not a list) of keyword arguments to pass into the function ret Optionally set a single or a list of returners to use ret_config Use an alternative returner configuration ret_kwargs Override individual returner configuration items expect_minions An optional boolean for failing if some minions do not respond fail_minions An optional list of targeted minions where failure is an option fail_function An optional string that points to a salt module that returns True or False based on the returned data dict for individual minions ssh Set to `True` to use the ssh client instead of the standard salt client batch Execute the command :ref:`in batches <targeting-batch>`. E.g.: ``10%``. subset Number of minions from the targeted set to randomly use .. versionadded:: 2017.7.0 ''' func_ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if kwarg is None: kwarg = {} if isinstance(arg, six.string_types): func_ret['warnings'] = ['Please specify \'arg\' as a list, not a string. ' 'Modifying in place, but please update SLS file ' 'to remove this warning.'] arg = arg.split() cmd_kw = {'arg': arg or [], 'kwarg': kwarg, 'ret': ret, 'timeout': timeout} if batch is not None: cmd_kw['batch'] = six.text_type(batch) if subset is not None: cmd_kw['subset'] = subset cmd_kw['tgt_type'] = tgt_type cmd_kw['ssh'] = ssh cmd_kw['expect_minions'] = expect_minions cmd_kw['_cmd_meta'] = True if ret_config: cmd_kw['ret_config'] = ret_config if ret_kwargs: cmd_kw['ret_kwargs'] = ret_kwargs fun = name if __opts__['test'] is True: func_ret['comment'] = ( 'Function {0} will be executed on target {1} as test={2}' ).format(fun, tgt, six.text_type(False)) func_ret['result'] = None return func_ret try: _fire_args({'type': 'function', 'tgt': tgt, 'name': name, 'args': cmd_kw}) cmd_ret = __salt__['saltutil.cmd'](tgt, fun, **cmd_kw) except Exception as exc: func_ret['result'] = False func_ret['comment'] = six.text_type(exc) return func_ret try: func_ret['__jid__'] = cmd_ret[next(iter(cmd_ret))]['jid'] except (StopIteration, KeyError): pass changes = {} fail = set() if fail_minions is None: fail_minions = () elif isinstance(fail_minions, six.string_types): fail_minions = [minion.strip() for minion in fail_minions.split(',')] elif not isinstance(fail_minions, list): func_ret.setdefault('warnings', []).append( '\'fail_minions\' needs to be a list or a comma separated ' 'string. Ignored.' ) fail_minions = () for minion, mdata in six.iteritems(cmd_ret): m_ret = False if mdata.get('retcode'): func_ret['result'] = False fail.add(minion) if mdata.get('failed', False): m_func = False else: if 'return' in mdata and 'ret' not in mdata: mdata['ret'] = mdata.pop('return') m_ret = mdata['ret'] m_func = (not fail_function and True) or __salt__[fail_function](m_ret) if m_ret is False: m_func = False if not m_func: if minion not in fail_minions: fail.add(minion) changes[minion] = m_ret if not cmd_ret: func_ret['result'] = False func_ret['command'] = 'No minions responded' else: if changes: func_ret['changes'] = {'out': 'highstate', 'ret': changes} if fail: func_ret['result'] = False func_ret['comment'] = 'Running function {0} failed on minions: {1}'.format(name, ', '.join(fail)) else: func_ret['comment'] = 'Function ran successfully.' if changes: func_ret['comment'] += ' Function {0} ran on {1}.'.format(name, ', '.join(changes)) return func_ret def wait_for_event( name, id_list, event_id='id', timeout=300, node='master'): ''' Watch Salt's event bus and block until a condition is met .. versionadded:: 2014.7.0 name An event tag to watch for; supports Reactor-style globbing. id_list A list of event identifiers to watch for -- usually the minion ID. Each time an event tag is matched the event data is inspected for ``event_id``, if found it is removed from ``id_list``. When ``id_list`` is empty this function returns success. event_id : id The name of a key in the event data. Default is ``id`` for the minion ID, another common value is ``name`` for use with orchestrating salt-cloud events. timeout : 300 The maximum time in seconds to wait before failing. The following example blocks until all the listed minions complete a restart and reconnect to the Salt master: .. code-block:: yaml reboot_all_minions: salt.function: - name: system.reboot - tgt: '*' wait_for_reboots: salt.wait_for_event: - name: salt/minion/*/start - id_list: - jerry - stuart - dave - phil - kevin - mike - require: - salt: reboot_all_minions ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} if __opts__.get('test'): ret['comment'] = \ 'Orchestration would wait for event \'{0}\''.format(name) ret['result'] = None return ret sevent = salt.utils.event.get_event( node, __opts__['sock_dir'], __opts__['transport'], opts=__opts__, listen=True) del_counter = 0 starttime = time.time() timelimit = starttime + timeout while True: event = sevent.get_event(full=True) is_timedout = time.time() > timelimit if event is None and not is_timedout: log.trace("wait_for_event: No event data; waiting.") continue elif event is None and is_timedout: ret['comment'] = 'Timeout value reached.' return ret if fnmatch.fnmatch(event['tag'], name): val = event['data'].get(event_id) if val is None and 'data' in event['data']: val = event['data']['data'].get(event_id) if val is not None: try: val_idx = id_list.index(val) except ValueError: log.trace("wait_for_event: Event identifier '%s' not in " "id_list; skipping.", event_id) else: del id_list[val_idx] del_counter += 1 minions_seen = ret['changes'].setdefault('minions_seen', []) minions_seen.append(val) log.debug("wait_for_event: Event identifier '%s' removed " "from id_list; %s items remaining.", val, len(id_list)) else: log.trace("wait_for_event: Event identifier '%s' not in event " "'%s'; skipping.", event_id, event['tag']) else: log.debug("wait_for_event: Skipping unmatched event '%s'", event['tag']) if len(id_list) == 0: ret['result'] = True ret['comment'] = 'All events seen in {0} seconds.'.format( time.time() - starttime) return ret if is_timedout: ret['comment'] = 'Timeout value reached.' return ret def runner(name, **kwargs): ''' Execute a runner module on the master .. versionadded:: 2014.7.0 name The name of the function to run kwargs Any keyword arguments to pass to the runner function .. code-block:: yaml run-manage-up: salt.runner: - name: manage.up ''' try: jid = __orchestration_jid__ except NameError: log.debug( 'Unable to fire args event due to missing __orchestration_jid__' ) jid = None if __opts__.get('test', False): ret = { 'name': name, 'result': None, 'changes': {}, 'comment': "Runner function '{0}' would be executed.".format(name) } return ret out = __salt__['saltutil.runner'](name, __orchestration_jid__=jid, __env__=__env__, full_return=True, **kwargs) runner_return = out.get('return') if isinstance(runner_return, dict) and 'Error' in runner_return: out['success'] = False success = out.get('success', True) ret = {'name': name, 'changes': {'return': runner_return}, 'result': success} ret['comment'] = "Runner function '{0}' {1}.".format( name, 'executed' if success else 'failed', ) ret['__orchestration__'] = True if 'jid' in out: ret['__jid__'] = out['jid'] return ret def parallel_runners(name, runners): ''' Executes multiple runner modules on the master in parallel. .. versionadded:: 2017.x.0 (Nitrogen) A separate thread is spawned for each runner. This state is intended to be used with the orchestrate runner in place of the ``saltmod.runner`` state when different tasks should be run in parallel. In general, Salt states are not safe when used concurrently, so ensure that they are used in a safe way (e.g. by only targeting separate minions in parallel tasks). name: name identifying this state. The name is provided as part of the output, but not used for anything else. runners: list of runners that should be run in parallel. Each element of the list has to be a dictionary. This dictionary's name entry stores the name of the runner function that shall be invoked. The optional kwarg entry stores a dictionary of named arguments that are passed to the runner function. .. code-block:: yaml parallel-state: salt.parallel_runners: - runners: my_runner_1: - name: state.orchestrate - kwarg: mods: orchestrate_state_1 my_runner_2: - name: state.orchestrate - kwarg: mods: orchestrate_state_2 ''' # For the sake of consistency, we treat a single string in the same way as # a key without a value. This allows something like # salt.parallel_runners: # - runners: # state.orchestrate # Obviously, this will only work if the specified runner does not need any # arguments. if isinstance(runners, six.string_types): runners = {runners: [{name: runners}]} # If the runners argument is not a string, it must be a dict. Everything # else is considered an error. if not isinstance(runners, dict): return { 'name': name, 'result': False, 'changes': {}, 'comment': 'The runners parameter must be a string or dict.' } # The configuration for each runner is given as a list of key-value pairs. # This is not very useful for what we want to do, but it is the typical # style used in Salt. For further processing, we convert each of these # lists to a dict. This also makes it easier to check whether a name has # been specified explicitly. for runner_id, runner_config in six.iteritems(runners): if runner_config is None: runner_config = {} else: runner_config = salt.utils.data.repack_dictlist(runner_config) if 'name' not in runner_config: runner_config['name'] = runner_id runners[runner_id] = runner_config try: jid = __orchestration_jid__ except NameError: log.debug( 'Unable to fire args event due to missing __orchestration_jid__') jid = None def call_runner(runner_config): return __salt__['saltutil.runner'](runner_config['name'], __orchestration_jid__=jid, __env__=__env__, full_return=True, **(runner_config.get('kwarg', {}))) try: outputs = _parallel_map(call_runner, list(six.itervalues(runners))) except salt.exceptions.SaltException as exc: return { 'name': name, 'result': False, 'success': False, 'changes': {}, 'comment': 'One of the runners raised an exception: {0}'.format( exc) } # We bundle the results of the runners with the IDs of the runners so that # we can easily identify which output belongs to which runner. At the same # time we exctract the actual return value of the runner (saltutil.runner # adds some extra information that is not interesting to us). outputs = { runner_id: out['return']for runner_id, out in six.moves.zip(six.iterkeys(runners), outputs) } # If each of the runners returned its output in the format compatible with # the 'highstate' outputter, we can leverage this fact when merging the # outputs. highstate_output = all( [out.get('outputter', '') == 'highstate' and 'data' in out for out in six.itervalues(outputs)] ) # The following helper function is used to extract changes from highstate # output. def extract_changes(obj): if not isinstance(obj, dict): return {} elif 'changes' in obj: if (isinstance(obj['changes'], dict) and obj['changes'].get('out', '') == 'highstate' and 'ret' in obj['changes']): return obj['changes']['ret'] else: return obj['changes'] else: found_changes = {} for key, value in six.iteritems(obj): change = extract_changes(value) if change: found_changes[key] = change return found_changes if highstate_output: failed_runners = [runner_id for runner_id, out in six.iteritems(outputs) if out['data'].get('retcode', 0) != 0] all_successful = not failed_runners if all_successful: comment = 'All runner functions executed successfully.' else: runner_comments = [ 'Runner {0} failed with return value:\n{1}'.format( runner_id, salt.output.out_format(outputs[runner_id], 'nested', __opts__, nested_indent=2) ) for runner_id in failed_runners ] comment = '\n'.join(runner_comments) changes = {} for runner_id, out in six.iteritems(outputs): runner_changes = extract_changes(out['data']) if runner_changes: changes[runner_id] = runner_changes else: failed_runners = [runner_id for runner_id, out in six.iteritems(outputs) if out.get('exit_code', 0) != 0] all_successful = not failed_runners if all_successful: comment = 'All runner functions executed successfully.' else: if len(failed_runners) == 1: comment = 'Runner {0} failed.'.format(failed_runners[0]) else: comment =\ 'Runners {0} failed.'.format(', '.join(failed_runners)) changes = {'ret': { runner_id: out for runner_id, out in six.iteritems(outputs) }} ret = { 'name': name, 'result': all_successful, 'changes': changes, 'comment': comment } # The 'runner' function includes out['jid'] as '__jid__' in the returned # dict, but we cannot do this here because we have more than one JID if # we have more than one runner. return ret def wheel(name, **kwargs): ''' Execute a wheel module on the master .. versionadded:: 2014.7.0 name The name of the function to run kwargs Any keyword arguments to pass to the wheel function .. code-block:: yaml accept_minion_key: salt.wheel: - name: key.accept - match: frank ''' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} try: jid = __orchestration_jid__ except NameError: log.debug( 'Unable to fire args event due to missing __orchestration_jid__' ) jid = None if __opts__.get('test', False): ret['result'] = None, ret['changes'] = {} ret['comment'] = "Wheel function '{0}' would be executed.".format(name) return ret out = __salt__['saltutil.wheel'](name, __orchestration_jid__=jid, __env__=__env__, **kwargs) wheel_return = out.get('return') if isinstance(wheel_return, dict) and 'Error' in wheel_return: out['success'] = False success = out.get('success', True) ret = {'name': name, 'changes': {'return': wheel_return}, 'result': success} ret['comment'] = "Wheel function '{0}' {1}.".format( name, 'executed' if success else 'failed', ) ret['__orchestration__'] = True if 'jid' in out: ret['__jid__'] = out['jid'] return ret
latch_roundtrip.py
""" Measure latency of IPC between two local threads. """ import threading import time import mitogen import mitogen.core import mitogen.utils import ansible_mitogen.affinity mitogen.utils.setup_gil() ansible_mitogen.affinity.policy.assign_worker() X = 20000 def flip_flop(ready, inp, out): ready.put(None) for x in xrange(X): inp.get() out.put(None) ready = mitogen.core.Latch() l1 = mitogen.core.Latch() l2 = mitogen.core.Latch() t1 = threading.Thread(target=flip_flop, args=(ready, l1, l2)) t2 = threading.Thread(target=flip_flop, args=(ready, l2, l1)) t1.start() t2.start() ready.get() ready.get() t0 = mitogen.core.now() l1.put(None) t1.join() t2.join() print('++', int(1e6 * ((mitogen.core.now() - t0) / (1.0+X))), 'usec')
massreport.py
import json, requests, time, threading, os, ctypes from tkinter.constants import W from colorama import Fore class massreport: def __init__(self): os.system('cls') massreporttitle() print(f"""{y}[{w}+{y}]{w} Enter the ID of the server where the message to be reported is located: """) self.GUILD_ID = str(input(f"""{y}[{b}#{y}]{w} Guild ID: """)) print(f"""\n{y}[{w}+{y}]{w} Enter the ID of the channel in which the message to be reported is located: """) self.CHANNEL_ID = str(input(f"""{y}[{b}#{y}]{w} Channel ID: """)) print(f"""\n{y}[{w}+{y}]{W} Enter the ID of the message to be reported: """) self.MESSAGE_ID = str(input(f"""{y}[{b}#{y}]{w} Message ID: """)) print(f"""\n{y}[{w}+{y}]{w} Choose the reason for the report: """) print(f""" {y}[{w}1{y}]{w} Illegal content""") print(f""" {y}[{w}2{y}]{w} Harassment""") print(f""" {y}[{w}3{y}]{w} Spam or phishing links""") print(f""" {y}[{w}4{y}]{w} Self-harm""") print(f""" {y}[{w}5{y}]{w} NSFW content\n""") REASON = input(f"""{y}[{b}#{y}]{w} Choice: """) if REASON == '1': self.REASON = 0 elif REASON == '2': self.REASON = 1 elif REASON == '3': self.REASON = 2 elif REASON == '4': self.REASON = 3 elif REASON == '5': self.REASON = 4 else: print(f""" {y}[{Fore.LIGHTRED_EX }!{y}]{w} Your request is invalid !""") time.sleep(2) main() self.RESPONSES = {f""" 401: Unauthorized: {y}[{Fore.LIGHTRED_EX }!{y}]{w} Invalid Discord token, Missing Access: {y}[{Fore.LIGHTRED_EX }!{y}]{w} Missing access to channel or guild, You need to verify your account in order to perform this action: {y}[{Fore.LIGHTRED_EX }!{y}]{w} Unverified"""} self.sent = 0 self.errors = 0 def _reporter(self): report = requests.post( 'https://discordapp.com/api/v8/report', json={ 'channel_id': self.CHANNEL_ID, 'message_id': self.MESSAGE_ID, 'guild_id': self.GUILD_ID, 'reason': self.REASON }, headers={ 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'sv-SE', 'User-Agent': 'Discord/21295 CFNetwork/1128.0.1 Darwin/19.6.0', 'Content-Type': 'application/json', 'Authorization': self.TOKEN } ) if (status := report.status_code) == 201: self.sent += 1 print(f"""{y}[{Fore.LIGHTGREEN_EX }!{y}]{w} Reported successfully""") elif status in (401, 403): self.errors += 1 print(self.RESPONSES[report.json()['message']]) else: self.errors += 1 print(f"""{y}[{Fore.LIGHTRED_EX }!{y}]{w} Error: {report.text} | Status Code: {status}""") def _update_title(self): while True: os.system(f'title [Discord Reporter] - Sent: {self.sent} ^| Errors: {self.errors}') time.sleep(0.1) def _multi_threading(self): threading.Thread(target=self._update_title).start() while True: if threading.active_count() <= 300: time.sleep(1) threading.Thread(target=self._reporter).start() def setup(self): recognized = None if os.path.exists(config_json := 'temp/Config.json'): with open(config_json, 'r') as f: try: data = json.load(f) self.TOKEN = data['discordToken'] except (KeyError, json.decoder.JSONDecodeError): recognized = False else: recognized = True else: recognized = False if not recognized: print(f"""\n{y}[{w}+{y}]{w} Enter your token: """) self.TOKEN = input(f"""{y}[{b}#{y}]{w} Token: """) with open(config_json, 'w') as f: json.dump({'discordToken': self.TOKEN}, f) print() self._multi_threading() mr = massreport() mr.setup()
test_poll.py
# Test case for the os.poll() function import os import subprocess import random import select import threading import time import unittest from test.support import ( cpython_only, requires_subprocess, requires_working_socket ) from test.support import threading_helper from test.support.os_helper import TESTFN try: select.poll except AttributeError: raise unittest.SkipTest("select.poll not defined") requires_working_socket(module=True) def find_ready_matching(ready, flag): match = [] for fd, mode in ready: if mode & flag: match.append(fd) return match class PollTests(unittest.TestCase): def test_poll1(self): # Basic functional test of poll object # Create a bunch of pipe and test that poll works with them. p = select.poll() NUM_PIPES = 12 MSG = b" This is a test." MSG_LEN = len(MSG) readers = [] writers = [] r2w = {} w2r = {} for i in range(NUM_PIPES): rd, wr = os.pipe() p.register(rd) p.modify(rd, select.POLLIN) p.register(wr, select.POLLOUT) readers.append(rd) writers.append(wr) r2w[rd] = wr w2r[wr] = rd bufs = [] while writers: ready = p.poll() ready_writers = find_ready_matching(ready, select.POLLOUT) if not ready_writers: raise RuntimeError("no pipes ready for writing") wr = random.choice(ready_writers) os.write(wr, MSG) ready = p.poll() ready_readers = find_ready_matching(ready, select.POLLIN) if not ready_readers: raise RuntimeError("no pipes ready for reading") rd = random.choice(ready_readers) buf = os.read(rd, MSG_LEN) self.assertEqual(len(buf), MSG_LEN) bufs.append(buf) os.close(r2w[rd]) ; os.close( rd ) p.unregister( r2w[rd] ) p.unregister( rd ) writers.remove(r2w[rd]) self.assertEqual(bufs, [MSG] * NUM_PIPES) def test_poll_unit_tests(self): # returns NVAL for invalid file descriptor FD, w = os.pipe() os.close(FD) os.close(w) p = select.poll() p.register(FD) r = p.poll() self.assertEqual(r[0], (FD, select.POLLNVAL)) with open(TESTFN, 'w') as f: fd = f.fileno() p = select.poll() p.register(f) r = p.poll() self.assertEqual(r[0][0], fd) r = p.poll() self.assertEqual(r[0], (fd, select.POLLNVAL)) os.unlink(TESTFN) # type error for invalid arguments p = select.poll() self.assertRaises(TypeError, p.register, p) self.assertRaises(TypeError, p.unregister, p) # can't unregister non-existent object p = select.poll() self.assertRaises(KeyError, p.unregister, 3) # Test error cases pollster = select.poll() class Nope: pass class Almost: def fileno(self): return 'fileno' self.assertRaises(TypeError, pollster.register, Nope(), 0) self.assertRaises(TypeError, pollster.register, Almost(), 0) # Another test case for poll(). This is copied from the test case for # select(), modified to use poll() instead. @requires_subprocess() def test_poll2(self): cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=0) proc.__enter__() self.addCleanup(proc.__exit__, None, None, None) p = proc.stdout pollster = select.poll() pollster.register( p, select.POLLIN ) for tout in (0, 1000, 2000, 4000, 8000, 16000) + (-1,)*10: fdlist = pollster.poll(tout) if (fdlist == []): continue fd, flags = fdlist[0] if flags & select.POLLHUP: line = p.readline() if line != b"": self.fail('error: pipe seems to be closed, but still returns data') continue elif flags & select.POLLIN: line = p.readline() if not line: break self.assertEqual(line, b'testing...\n') continue else: self.fail('Unexpected return value from select.poll: %s' % fdlist) def test_poll3(self): # test int overflow pollster = select.poll() pollster.register(1) self.assertRaises(OverflowError, pollster.poll, 1 << 64) x = 2 + 3 if x != 5: self.fail('Overflow must have occurred') # Issues #15989, #17919 self.assertRaises(ValueError, pollster.register, 0, -1) self.assertRaises(OverflowError, pollster.register, 0, 1 << 64) self.assertRaises(ValueError, pollster.modify, 1, -1) self.assertRaises(OverflowError, pollster.modify, 1, 1 << 64) @cpython_only def test_poll_c_limits(self): from _testcapi import USHRT_MAX, INT_MAX, UINT_MAX pollster = select.poll() pollster.register(1) # Issues #15989, #17919 self.assertRaises(OverflowError, pollster.register, 0, USHRT_MAX + 1) self.assertRaises(OverflowError, pollster.modify, 1, USHRT_MAX + 1) self.assertRaises(OverflowError, pollster.poll, INT_MAX + 1) self.assertRaises(OverflowError, pollster.poll, UINT_MAX + 1) @threading_helper.reap_threads def test_threaded_poll(self): r, w = os.pipe() self.addCleanup(os.close, r) self.addCleanup(os.close, w) rfds = [] for i in range(10): fd = os.dup(r) self.addCleanup(os.close, fd) rfds.append(fd) pollster = select.poll() for fd in rfds: pollster.register(fd, select.POLLIN) t = threading.Thread(target=pollster.poll) t.start() try: time.sleep(0.5) # trigger ufds array reallocation for fd in rfds: pollster.unregister(fd) pollster.register(w, select.POLLOUT) self.assertRaises(RuntimeError, pollster.poll) finally: # and make the call to poll() from the thread return os.write(w, b'spam') t.join() @unittest.skipUnless(threading, 'Threading required for this test.') @threading_helper.reap_threads def test_poll_blocks_with_negative_ms(self): for timeout_ms in [None, -1000, -1, -1.0, -0.1, -1e-100]: # Create two file descriptors. This will be used to unlock # the blocking call to poll.poll inside the thread r, w = os.pipe() pollster = select.poll() pollster.register(r, select.POLLIN) poll_thread = threading.Thread(target=pollster.poll, args=(timeout_ms,)) poll_thread.start() poll_thread.join(timeout=0.1) self.assertTrue(poll_thread.is_alive()) # Write to the pipe so pollster.poll unblocks and the thread ends. os.write(w, b'spam') poll_thread.join() self.assertFalse(poll_thread.is_alive()) os.close(r) os.close(w) if __name__ == '__main__': unittest.main()
cluster_train.py
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import time import os import math from multiprocessing import Process import numpy as np import paddle.fluid as F import paddle.fluid.layers as L from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler import fleet from paddle.fluid.transpiler.distribute_transpiler import DistributeTranspilerConfig import paddle.fluid.incubate.fleet.base.role_maker as role_maker from pgl.utils.logger import log from pgl import data_loader from reader import DeepwalkReader from model import DeepwalkModel from utils import get_file_list from utils import build_graph from utils import build_fake_graph from utils import build_gen_func def init_role(): # reset the place according to role of parameter server training_role = os.getenv("TRAINING_ROLE", "TRAINER") paddle_role = role_maker.Role.WORKER place = F.CPUPlace() if training_role == "PSERVER": paddle_role = role_maker.Role.SERVER # set the fleet runtime environment according to configure ports = os.getenv("PADDLE_PORT", "6174").split(",") pserver_ips = os.getenv("PADDLE_PSERVERS").split(",") # ip,ip... eplist = [] if len(ports) > 1: # local debug mode, multi port for port in ports: eplist.append(':'.join([pserver_ips[0], port])) else: # distributed mode, multi ip for ip in pserver_ips: eplist.append(':'.join([ip, ports[0]])) pserver_endpoints = eplist # ip:port,ip:port... worker_num = int(os.getenv("PADDLE_TRAINERS_NUM", "0")) trainer_id = int(os.getenv("PADDLE_TRAINER_ID", "0")) role = role_maker.UserDefinedRoleMaker( current_id=trainer_id, role=paddle_role, worker_num=worker_num, server_endpoints=pserver_endpoints) fleet.init(role) def optimization(base_lr, loss, train_steps, optimizer='sgd'): decayed_lr = L.learning_rate_scheduler.polynomial_decay( learning_rate=base_lr, decay_steps=train_steps, end_learning_rate=0.0001 * base_lr, power=1.0, cycle=False) if optimizer == 'sgd': optimizer = F.optimizer.SGD(decayed_lr) elif optimizer == 'adam': optimizer = F.optimizer.Adam(decayed_lr, lazy_mode=True) else: raise ValueError log.info('learning rate:%f' % (base_lr)) #create the DistributeTranspiler configure config = DistributeTranspilerConfig() config.sync_mode = False #config.runtime_split_send_recv = False config.slice_var_up = False #create the distributed optimizer optimizer = fleet.distributed_optimizer(optimizer, config) optimizer.minimize(loss) def build_complied_prog(train_program, model_loss): num_threads = int(os.getenv("CPU_NUM", 10)) trainer_id = int(os.getenv("PADDLE_TRAINER_ID", 0)) exec_strategy = F.ExecutionStrategy() exec_strategy.num_threads = num_threads #exec_strategy.use_experimental_executor = True build_strategy = F.BuildStrategy() build_strategy.enable_inplace = True #build_strategy.memory_optimize = True build_strategy.memory_optimize = False build_strategy.remove_unnecessary_lock = False if num_threads > 1: build_strategy.reduce_strategy = F.BuildStrategy.ReduceStrategy.Reduce compiled_prog = F.compiler.CompiledProgram( train_program).with_data_parallel( loss_name=model_loss.name) return compiled_prog def train_prog(exe, program, loss, node2vec_pyreader, args, train_steps): trainer_id = int(os.getenv("PADDLE_TRAINER_ID", "0")) step = 0 while True: try: begin_time = time.time() loss_val, = exe.run(program, fetch_list=[loss]) log.info("step %s: loss %.5f speed: %.5f s/step" % (step, np.mean(loss_val), time.time() - begin_time)) step += 1 except F.core.EOFException: node2vec_pyreader.reset() if step % args.steps_per_save == 0 or step == train_steps: if trainer_id == 0 or args.is_distributed: model_save_dir = args.save_path model_path = os.path.join(model_save_dir, str(step)) if not os.path.exists(model_save_dir): os.makedirs(model_save_dir) fleet.save_persistables(exe, model_path) if step == train_steps: break def test(args): graph = build_graph(args.num_nodes, args.edge_path) gen_func = build_gen_func(args, graph) start = time.time() num = 10 for idx, _ in enumerate(gen_func()): if idx % num == num - 1: log.info("%s" % (1.0 * (time.time() - start) / num)) start = time.time() def walk(args): graph = build_graph(args.num_nodes, args.edge_path) num_sample_workers = args.num_sample_workers if args.train_files is None or args.train_files == "None": log.info("Walking from graph...") train_files = [None for _ in range(num_sample_workers)] else: log.info("Walking from train_data...") files = get_file_list(args.train_files) train_files = [[] for i in range(num_sample_workers)] for idx, f in enumerate(files): train_files[idx % num_sample_workers].append(f) def walk_to_file(walk_gen, filename, max_num): with open(filename, "w") as outf: num = 0 for walks in walk_gen: for walk in walks: outf.write("%s\n" % "\t".join([str(i) for i in walk])) num += 1 if num % 1000 == 0: log.info("Total: %s, %s walkpath is saved. " % (max_num, num)) if num == max_num: return m_args = [(DeepwalkReader( graph, batch_size=args.batch_size, walk_len=args.walk_len, win_size=args.win_size, neg_num=args.neg_num, neg_sample_type=args.neg_sample_type, walkpath_files=None, train_files=train_files[i]).walk_generator(), "%s/%s" % (args.walkpath_files, i), args.epoch * args.num_nodes // args.num_sample_workers) for i in range(num_sample_workers)] ps = [] for i in range(num_sample_workers): p = Process(target=walk_to_file, args=m_args[i]) p.start() ps.append(p) for i in range(num_sample_workers): ps[i].join() def train(args): import logging log.setLevel(logging.DEBUG) log.info("start") worker_num = int(os.getenv("PADDLE_TRAINERS_NUM", "0")) num_devices = int(os.getenv("CPU_NUM", 10)) model = DeepwalkModel(args.num_nodes, args.hidden_size, args.neg_num, args.is_sparse, args.is_distributed, 1.) pyreader = model.pyreader loss = model.forward() # init fleet init_role() train_steps = math.ceil(1. * args.num_nodes * args.epoch / args.batch_size / num_devices / worker_num) log.info("Train step: %s" % train_steps) if args.optimizer == "sgd": args.lr *= args.batch_size * args.walk_len * args.win_size optimization(args.lr, loss, train_steps, args.optimizer) # init and run server or worker if fleet.is_server(): fleet.init_server(args.warm_start_from_dir) fleet.run_server() if fleet.is_worker(): log.info("start init worker done") fleet.init_worker() #just the worker, load the sample log.info("init worker done") exe = F.Executor(F.CPUPlace()) exe.run(fleet.startup_program) log.info("Startup done") if args.dataset is not None: if args.dataset == "BlogCatalog": graph = data_loader.BlogCatalogDataset().graph elif args.dataset == "ArXiv": graph = data_loader.ArXivDataset().graph else: raise ValueError(args.dataset + " dataset doesn't exists") log.info("Load buildin BlogCatalog dataset done.") elif args.walkpath_files is None or args.walkpath_files == "None": graph = build_graph(args.num_nodes, args.edge_path) log.info("Load graph from '%s' done." % args.edge_path) else: graph = build_fake_graph(args.num_nodes) log.info("Load fake graph done.") # bind gen gen_func = build_gen_func(args, graph) pyreader.decorate_tensor_provider(gen_func) pyreader.start() compiled_prog = build_complied_prog(fleet.main_program, loss) train_prog(exe, compiled_prog, loss, pyreader, args, train_steps) if __name__ == '__main__': def str2bool(v): if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') parser = argparse.ArgumentParser(description='Deepwalk') parser.add_argument( "--hidden_size", type=int, default=64, help="Hidden size of the embedding.") parser.add_argument( "--lr", type=float, default=0.025, help="Learning rate.") parser.add_argument( "--neg_num", type=int, default=5, help="Number of negative samples.") parser.add_argument( "--epoch", type=int, default=1, help="Number of training epoch.") parser.add_argument( "--batch_size", type=int, default=128, help="Numbert of walk paths in a batch.") parser.add_argument( "--walk_len", type=int, default=40, help="Length of a walk path.") parser.add_argument( "--win_size", type=int, default=5, help="Window size in skip-gram.") parser.add_argument( "--save_path", type=str, default="model_path", help="Output path for saving model.") parser.add_argument( "--num_sample_workers", type=int, default=1, help="Number of sampling workers.") parser.add_argument( "--steps_per_save", type=int, default=3000, help="Steps for model saveing.") parser.add_argument( "--num_nodes", type=int, default=10000, help="Number of nodes in graph.") parser.add_argument("--edge_path", type=str, default="./graph_data") parser.add_argument("--train_files", type=str, default=None) parser.add_argument("--walkpath_files", type=str, default=None) parser.add_argument("--is_distributed", type=str2bool, default=False) parser.add_argument("--is_sparse", type=str2bool, default=True) parser.add_argument("--warm_start_from_dir", type=str, default=None) parser.add_argument("--dataset", type=str, default=None) parser.add_argument( "--neg_sample_type", type=str, default="average", choices=["average", "outdegree"]) parser.add_argument( "--mode", type=str, required=False, choices=['train', 'walk'], default="train") parser.add_argument( "--optimizer", type=str, required=False, choices=['adam', 'sgd'], default="sgd") args = parser.parse_args() log.info(args) if args.mode == "train": train(args) elif args.mode == "walk": walk(args)
test_context.py
# Copyright (C) PyZMQ Developers # Distributed under the terms of the Modified BSD License. import gc import sys import time from threading import Thread, Event import zmq from zmq.tests import ( BaseZMQTestCase, have_gevent, GreenTest, skip_green, PYPY, SkipTest, ) class TestContext(BaseZMQTestCase): def test_init(self): c1 = self.Context() self.assert_(isinstance(c1, self.Context)) del c1 c2 = self.Context() self.assert_(isinstance(c2, self.Context)) del c2 c3 = self.Context() self.assert_(isinstance(c3, self.Context)) del c3 def test_dir(self): ctx = self.Context() self.assertTrue('socket' in dir(ctx)) if zmq.zmq_version_info() > (3,): self.assertTrue('IO_THREADS' in dir(ctx)) ctx.term() def test_term(self): c = self.Context() c.term() self.assert_(c.closed) def test_context_manager(self): with self.Context() as c: pass self.assert_(c.closed) def test_fail_init(self): self.assertRaisesErrno(zmq.EINVAL, self.Context, -1) def test_term_hang(self): rep,req = self.create_bound_pair(zmq.ROUTER, zmq.DEALER) req.setsockopt(zmq.LINGER, 0) req.send(b'hello', copy=False) req.close() rep.close() self.context.term() def test_instance(self): ctx = self.Context.instance() c2 = self.Context.instance(io_threads=2) self.assertTrue(c2 is ctx) c2.term() c3 = self.Context.instance() c4 = self.Context.instance() self.assertFalse(c3 is c2) self.assertFalse(c3.closed) self.assertTrue(c3 is c4) def test_many_sockets(self): """opening and closing many sockets shouldn't cause problems""" ctx = self.Context() for i in range(16): sockets = [ ctx.socket(zmq.REP) for i in range(65) ] [ s.close() for s in sockets ] # give the reaper a chance time.sleep(1e-2) ctx.term() def test_sockopts(self): """setting socket options with ctx attributes""" ctx = self.Context() ctx.linger = 5 self.assertEqual(ctx.linger, 5) s = ctx.socket(zmq.REQ) self.assertEqual(s.linger, 5) self.assertEqual(s.getsockopt(zmq.LINGER), 5) s.close() # check that subscribe doesn't get set on sockets that don't subscribe: ctx.subscribe = b'' s = ctx.socket(zmq.REQ) s.close() ctx.term() def test_destroy(self): """Context.destroy should close sockets""" ctx = self.Context() sockets = [ ctx.socket(zmq.REP) for i in range(65) ] # close half of the sockets [ s.close() for s in sockets[::2] ] ctx.destroy() # reaper is not instantaneous time.sleep(1e-2) for s in sockets: self.assertTrue(s.closed) def test_destroy_linger(self): """Context.destroy should set linger on closing sockets""" req,rep = self.create_bound_pair(zmq.REQ, zmq.REP) req.send(b'hi') time.sleep(1e-2) self.context.destroy(linger=0) # reaper is not instantaneous time.sleep(1e-2) for s in (req,rep): self.assertTrue(s.closed) def test_term_noclose(self): """Context.term won't close sockets""" ctx = self.Context() s = ctx.socket(zmq.REQ) self.assertFalse(s.closed) t = Thread(target=ctx.term) t.start() t.join(timeout=0.1) self.assertTrue(t.is_alive(), "Context should be waiting") s.close() t.join(timeout=0.1) self.assertFalse(t.is_alive(), "Context should have closed") def test_gc(self): """test close&term by garbage collection alone""" if PYPY: raise SkipTest("GC doesn't work ") # test credit @dln (GH #137): def gcf(): def inner(): ctx = self.Context() s = ctx.socket(zmq.PUSH) inner() gc.collect() t = Thread(target=gcf) t.start() t.join(timeout=1) self.assertFalse(t.is_alive(), "Garbage collection should have cleaned up context") def test_cyclic_destroy(self): """ctx.destroy should succeed when cyclic ref prevents gc""" # test credit @dln (GH #137): class CyclicReference(object): def __init__(self, parent=None): self.parent = parent def crash(self, sock): self.sock = sock self.child = CyclicReference(self) def crash_zmq(): ctx = self.Context() sock = ctx.socket(zmq.PULL) c = CyclicReference() c.crash(sock) ctx.destroy() crash_zmq() def test_term_thread(self): """ctx.term should not crash active threads (#139)""" ctx = self.Context() evt = Event() evt.clear() def block(): s = ctx.socket(zmq.REP) s.bind_to_random_port('tcp://127.0.0.1') evt.set() try: s.recv() except zmq.ZMQError as e: self.assertEqual(e.errno, zmq.ETERM) return finally: s.close() self.fail("recv should have been interrupted with ETERM") t = Thread(target=block) t.start() evt.wait(1) self.assertTrue(evt.is_set(), "sync event never fired") time.sleep(0.01) ctx.term() t.join(timeout=1) self.assertFalse(t.is_alive(), "term should have interrupted s.recv()") def test_destroy_no_sockets(self): ctx = self.Context() s = ctx.socket(zmq.PUB) s.bind_to_random_port('tcp://127.0.0.1') s.close() ctx.destroy() assert s.closed assert ctx.closed def test_ctx_opts(self): if zmq.zmq_version_info() < (3,): raise SkipTest("context options require libzmq 3") ctx = self.Context() ctx.set(zmq.MAX_SOCKETS, 2) self.assertEqual(ctx.get(zmq.MAX_SOCKETS), 2) ctx.max_sockets = 100 self.assertEqual(ctx.max_sockets, 100) self.assertEqual(ctx.get(zmq.MAX_SOCKETS), 100) def test_shadow(self): ctx = self.Context() ctx2 = self.Context.shadow(ctx.underlying) self.assertEqual(ctx.underlying, ctx2.underlying) s = ctx.socket(zmq.PUB) s.close() del ctx2 self.assertFalse(ctx.closed) s = ctx.socket(zmq.PUB) ctx2 = self.Context.shadow(ctx.underlying) s2 = ctx2.socket(zmq.PUB) s.close() s2.close() ctx.term() self.assertRaisesErrno(zmq.EFAULT, ctx2.socket, zmq.PUB) del ctx2 def test_shadow_pyczmq(self): try: from pyczmq import zctx, zsocket, zstr except Exception: raise SkipTest("Requires pyczmq") ctx = zctx.new() a = zsocket.new(ctx, zmq.PUSH) zsocket.bind(a, "inproc://a") ctx2 = self.Context.shadow_pyczmq(ctx) b = ctx2.socket(zmq.PULL) b.connect("inproc://a") zstr.send(a, b'hi') rcvd = self.recv(b) self.assertEqual(rcvd, b'hi') b.close() if False: # disable green context tests class TestContextGreen(GreenTest, TestContext): """gevent subclass of context tests""" # skip tests that use real threads: test_gc = GreenTest.skip_green test_term_thread = GreenTest.skip_green test_destroy_linger = GreenTest.skip_green
shr.py
from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.label import Label from kivy.config import Config from kivy.uix.textinput import TextInput from kivy.uix.switch import Switch import threading import os import random Config.set('graphics','height','700')#высота Config.set('graphics','width','1350') ''' cvb=open("ras.txt","r") vy=cvb.read() cvb.close() file=open('ras.txt','r') kolsb=file.read() file.close() ''' def alfa(): fil=open("layout.txt","r", encoding='utf-8') layout=str(fil.read()) fil.close() f=[] exec("f.extend("+layout+")") return f #return ['A','B','C','D','E','F','G','L','J','K','I','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','l','j','k','i','m','n','o','p','q','r','s','t','u','v','w','x','y','z','А','Б','В','Г','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П','Р','С','Т','У','Ф','Х','Ц','Ч','Ш','Щ','Ъ','Ы','Ь','Э','Ю','Я','а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я',' ',',','.','<','>',':',';','?','/','!','@','#','№','$','|','%','&','*','(',')','-','+','_','=','^','0','1','2','3','4','5','6','7','8','9'] cvb=open('kwo.txt','w') b6=len(alfa()) cvb.write(str(b6)) cvb.close() class Shif_PPApp(App): def callback(self,instance, value): if self.ghi==False: self.ghi=True elif self.ghi==True: self.ghi=False def sg(self,args): alfaw=alfa() kwo=len(alfaw) kolsb=self.ns.text file=open('Shif/kol.txt','r') vb=file.read() file.close() file=open('Shif/kol.txt','w') file.write(kolsb) file.close() j=self.t.text al=[] #try: j=int(j) kolsb=int(kolsb) ma=1 if j>1000: threading.Thread(target=lambda: os.system('ош1.py')).start() elif j>0 and j<1001: skr=0 y='' ir="" p=kwo*kolsb for gh in range(p): file=open('Shif/'+str(skr)+'.txt','w') y="" for e in range(j): q=random.randint(0, kwo-1) y+=alfaw[q] if y not in al: file.write(str(y)) file.close() skr+=1 al.extend(y) else: while y in al: y="" for e in range(j): q=random.randint(0, kwo-1) y+=alfaw[q] file.write(str(y)) file.close() skr+=1 al.extend(y) if int(kolsb)<int(vb): for z in range((int(vb)*kwo)-int(skr)): try: os.remove('Shif/'+str(skr)+'.txt') skr+=1 except: pass threading.Thread(target=lambda: os.system('увед.py')).start() elif j<0 or j==0 or kolsb<0: threading.Thread(target=lambda: os.system('ошm.py')).start() else: threading.Thread(target=lambda: os.system('ош.py')).start() #except: #threading.Thread(target=lambda: os.system('ош2.py')).start() def ssh(self,args): alfawsh=['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''] alfaw=alfa() alfator=[] kwo=len(alfaw) bws=[] bwsh=[] st=0 br=0 bz=0 ma=0 j=0 dn="" file=open('Shif/kol.txt','r') kolsb=file.read() file.close() kolsb=int(kolsb) m=kwo*kolsb for i in range(m): file=open('Shif/'+str(st)+".txt","r") dn=file.read() file.close() if st<=kwo-1: alfawsh[st]=dn elif st>kwo-1: alfawsh+='6' alfawsh[st]=dn st+=1 ft=self.ti.text zr=len(ft) file=open("зашифровано.txt","w") file.close() om=False pr=False n=0 for iz in range(zr): br=0 k=len(bws) if self.ghi==True: j=random.randint(1,kolsb) om=True else: for h in range(k): #if k-1<0: if ft[bz]== bws[h]: om=True pr=True hk=bws[k-1] if j<kolsb-1: j+=1 elif j>=kolsb-1: j=0 n+=1 for e in range(kwo): if ft[bz]==alfaw[br]: if om==False and self.ghi!=True: file=open("зашифровано.txt","a") file.write(alfawsh[br]) bws+= alfaw[br] file.close() else: file=open("зашифровано.txt","a") bb=br+(150*j) if j<kolsb: file.write(alfawsh[br+(kwo*(j))]) elif j>=kolsb: file.write(alfawsh[br+(kwo*(j-1))]) bws+= alfaw[br] file.close() break br+=1 om=False j=0 bz+=1 file=open("зашифровано.txt","r") ik=file.read() file.close() self.tp.text=ik self.tp.text def ob(self,args): threading.Thread(target=lambda: os.system('ob.py')).start() def ob2(self,args): threading.Thread(target=lambda: os.system('ob2.py')).start() def ob3(self,args): threading.Thread(target=lambda: os.system('ob3.py')).start() def sh(self,args): threading.Thread(target=lambda: os.system('forin.py')).start() def dsh(self,args): threading.Thread(target=lambda: os.system('rashinsh.py')).start() def ssr(self,args): alfawsh=['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''] alfaw=alfa() ht=len(alfaw) print(ht) fz=self.ti.text dn="" kwo=len(alfaw) st=0 #111 file=open('Shif/kol.txt','r') kolsb=file.read() file.close() kolsb=int(kolsb) m=ht*kolsb for i in range(m): file=open('Shif/'+str(st)+".txt","r") dn=file.read() file.close() if st<=kwo-1: alfawsh[st]=dn elif st>kwo-1: alfawsh+='6' alfawsh[st]=dn st+=1 st=0 bn=0 dn="" pahz="" yz="" hj=0 file=open('Shif/kol.txt','r') kolsb=file.read() file.close() kolsb=int(kolsb) for i in range(m): file=open('Shif/'+str(st)+".txt","r") dn=file.read() file.close() alfawsh[st]=dn st+=1 ul=len(alfawsh[0]) gh=len(fz)/ul ''' for z in range(kolsb): print(i+(z*ht)) ''' for i in range(int(gh)): for hu in range(ul): yz+=fz[hj] hj+=1 for i in range(m): if yz==alfawsh[i]: pahz+=alfaw[i-(ht*int(i/ht))] break yz="" file=open("раскодировано.txt","w") file.write(pahz) file.close() file=open("раскодировано.txt","r") self.tp.text=file.read() file.close() def build(self): self.ghi=0 bl=BoxLayout(orientation="vertical") gr=GridLayout(cols=7,size_hint=(1,.1)) self.t=TextInput(text="") gr.add_widget(self.t) gr.add_widget(Button(text="Cгенерировать",on_press=self.sg,size_hint=(1.1,.05))) gr.add_widget(Button(text="подготовить шифр для передачи",on_press=self.sh,size_hint=(1.1,.05))) gr.add_widget(Button(text="подготовить полученный шифр",on_press=self.dsh,size_hint=(1.1,.05))) gr.add_widget(Button(text="зашифровать",on_press=self.ssh)) gr.add_widget(Button(text="расшифровать",on_press=self.ssr,size_hint=(1.1,.05))) bl.add_widget(gr) self.ti=TextInput() self.tp=TextInput() bl.add_widget(self.ti) bl.add_widget(self.tp) gn=GridLayout(cols=3,size_hint=(1,.12)) self.ns=TextInput(size_hint=(0.7,1),text="1") gn.add_widget(Label(text="сколько составить шифров на каждую букву")) gn.add_widget(self.ns) gn.add_widget(Button(text="Не понял?",size_hint=(0.7,1),on_press=self.ob)) bl.add_widget(gn) gp=GridLayout(cols=3,size_hint=(1,.12)) gp.add_widget(Label(text="ставить варианты шифров букв в случайно")) switch = Switch() switch.bind(active=self.callback) gp.add_widget(switch) gp.add_widget(Button(text="Не понял?",size_hint=(0.7,1),on_press=self.ob3)) bl.add_widget(gp) return bl if __name__=="__main__": Shif_PPApp().run()
reducer.py
import os import threading from fedn.clients.reducer.control import ReducerControl from fedn.clients.reducer.interfaces import ReducerInferenceInterface from fedn.clients.reducer.restservice import ReducerRestService from fedn.clients.reducer.state import ReducerStateToString from fedn.common.security.certificatemanager import CertificateManager from fedn.clients.reducer.statestore.mongoreducerstatestore import MongoReducerStateStore class InvalidReducerConfiguration(Exception): pass class MissingReducerConfiguration(Exception): pass class Reducer: def __init__(self, statestore): """ """ self.statestore = statestore config = self.statestore.get_reducer() if not config: print("REDUCER: Failed to retrive Reducer config, exiting.") raise MissingReducerConfiguration() self.name = config['name'] self.token = config['token'] try: path = config['path'] except KeyError: path = os.getcwd() self.certificate_manager = CertificateManager(os.getcwd() + "/certs/") self.control = ReducerControl(self.statestore) self.inference = ReducerInferenceInterface() rest_certificate = self.certificate_manager.get_or_create("reducer") self.rest = ReducerRestService(config, self.control, self.certificate_manager, certificate=rest_certificate) def run(self): threading.Thread(target=self.control_loop, daemon=True).start() self.rest.run() def control_loop(self): import time from datetime import datetime try: old_state = self.control.state() t1 = datetime.now() while True: time.sleep(1) if old_state != self.control.state(): delta = datetime.now() - t1 print("Reducer in state {} for {} seconds. Entering {} state".format(ReducerStateToString(old_state),delta.seconds,ReducerStateToString(self.control.state())), flush=True) t1 = datetime.now() old_state = self.control.state() self.control.monitor() except (KeyboardInterrupt, SystemExit): print("Exiting..", flush=True)
startDask.py
import os import argparse import time from dask.distributed import Client import sys, uuid import threading import subprocess import socket import mlflow from notebook.notebookapp import list_running_servers def flush(proc, proc_log): while True: proc_out = proc.stdout.readline() if proc_out == "" and proc.poll() is not None: proc_log.close() break elif proc_out: sys.stdout.write(proc_out) proc_log.write(proc_out) proc_log.flush() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--jupyter_token", default=uuid.uuid1().hex) parser.add_argument("--script") args, unparsed = parser.parse_known_args() for k, v in os.environ.items(): if k.startswith("MLFLOW"): print(k, v) MLFLOW_RUN_ID = os.getenv("MLFLOW_RUN_ID") print("- env: MASTER_ADDR: ", os.environ.get("MASTER_ADDR")) print("- env: MASTER_PORT: ", os.environ.get("MASTER_PORT")) print("- env: RANK: ", os.environ.get("RANK")) print("- env: LOCAL_RANK: ", os.environ.get("LOCAL_RANK")) print("- env: NODE_RANK: ", os.environ.get("NODE_RANK")) rank = os.environ.get("RANK") ip = socket.gethostbyname(socket.gethostname()) master = os.environ.get("MASTER_ADDR") master_port = os.environ.get("MASTER_PORT") print("- my rank is ", rank) print("- my ip is ", ip) print("- master is ", master) print("- master port is ", master_port) scheduler = master + ":8786" dashboard = master + ":8787" print("- scheduler is ", scheduler) print("- dashboard is ", dashboard) print("args: ", args) print("unparsed: ", unparsed) print("- my rank is ", rank) print("- my ip is ", ip) if not os.path.exists("logs"): os.makedirs("logs") print("free disk space on /tmp") os.system(f"df -P /tmp") if str(rank) == "0": mlflow.log_param("headnode", ip) mlflow.log_param( "cluster", "scheduler: {scheduler}, dashboard: {dashboard}".format( scheduler=scheduler, dashboard=dashboard ), ) cmd = ( "jupyter lab --ip 0.0.0.0 --port 8888" + " --NotebookApp.token={token}" + " --allow-root --no-browser" ).format(token=args.jupyter_token) os.environ["MLFLOW_RUN_ID"] = MLFLOW_RUN_ID jupyter_log = open("logs/jupyter_log.txt", "w") jupyter_proc = subprocess.Popen( cmd.split(), universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) jupyter_flush = threading.Thread(target=flush, args=(jupyter_proc, jupyter_log)) jupyter_flush.start() # while not list(list_running_servers()): # time.sleep(5) # jupyter_servers = list(list_running_servers()) # assert (len(jupyter_servers) == 1), "more than one jupyter server is running" mlflow.log_param( "jupyter", "ip: {ip_addr}, port: {port}".format(ip_addr=ip, port="8888") ) mlflow.log_param("jupyter-token", args.jupyter_token) cmd = ( "dask-scheduler " + "--port " + scheduler.split(":")[1] + " --dashboard-address " + dashboard ) print(cmd) os.environ["MLFLOW_RUN_ID"] = MLFLOW_RUN_ID scheduler_log = open("logs/scheduler_log.txt", "w") scheduler_proc = subprocess.Popen( cmd.split(), universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) scheduler_flush = threading.Thread( target=flush, args=(scheduler_proc, scheduler_log) ) scheduler_flush.start() cmd = "dask-worker " + scheduler print(cmd) os.environ["MLFLOW_RUN_ID"] = MLFLOW_RUN_ID worker_log = open("logs/worker_{rank}_log.txt".format(rank=rank), "w") worker_proc = subprocess.Popen( cmd.split(), universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) worker_flush = threading.Thread(target=flush, args=(worker_proc, worker_log)) worker_flush.start() if args.script: command_line = " ".join(["python", args.script] + unparsed) print("Launching:", command_line) os.environ["MLFLOW_RUN_ID"] = MLFLOW_RUN_ID driver_log = open("logs/driver_log.txt", "w") driver_proc = subprocess.Popen( command_line.split(), universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) driver_flush = threading.Thread( target=flush, args=(driver_proc, driver_log) ) driver_flush.start() # Wait until process terminates (without using p.wait()) # while driver_proc.poll() is None: # # Process hasn't exited yet, let's wait some # time.sleep(0.5) print("waiting for driver process to terminate") driver_proc.wait() exit_code = driver_proc.returncode print("process ended with code", exit_code) print("killing scheduler, worker and jupyter") jupyter_proc.kill() scheduler_proc.kill() worker_proc.kill() exit(exit_code) else: flush(scheduler_proc, scheduler_log) else: cmd = "dask-worker " + scheduler print(cmd) os.environ["MLFLOW_RUN_ID"] = MLFLOW_RUN_ID worker_log = open("logs/worker_{rank}_log.txt".format(rank=rank), "w") worker_proc = subprocess.Popen( cmd.split(), universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) flush(worker_proc, worker_log)
mmalobj.py
# vim: set et sw=4 sts=4 fileencoding=utf-8: # # Python header conversion # Copyright (c) 2013-2015 Dave Jones <dave@waveform.org.uk> # # Original headers # Copyright (c) 2012, Broadcom Europe Ltd # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. from __future__ import ( unicode_literals, print_function, division, absolute_import, ) # Make Py2's str equivalent to Py3's str = type('') import io import ctypes as ct import warnings import weakref from threading import Thread, Event from collections import namedtuple from fractions import Fraction from itertools import cycle from functools import reduce from operator import mul from . import bcm_host, mmal from .streams import BufferIO from .exc import ( mmal_check, PiCameraValueError, PiCameraRuntimeError, PiCameraMMALError, PiCameraPortDisabled, PiCameraDeprecated, ) # Old firmwares confuse the RGB24 and BGR24 encodings. This flag tracks whether # the order needs fixing (it is set during MMALCamera.__init__). FIX_RGB_BGR_ORDER = None # Mapping of parameters to the C-structure they expect / return. If a parameter # does not appear in this mapping, it cannot be queried / set with the # MMALControlPort.params attribute. PARAM_TYPES = { mmal.MMAL_PARAMETER_ALGORITHM_CONTROL: mmal.MMAL_PARAMETER_ALGORITHM_CONTROL_T, mmal.MMAL_PARAMETER_ANNOTATE: None, # adjusted by MMALCamera.annotate_rev mmal.MMAL_PARAMETER_ANTISHAKE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_AUDIO_LATENCY_TARGET: mmal.MMAL_PARAMETER_AUDIO_LATENCY_TARGET_T, mmal.MMAL_PARAMETER_AWB_MODE: mmal.MMAL_PARAMETER_AWBMODE_T, mmal.MMAL_PARAMETER_BRIGHTNESS: mmal.MMAL_PARAMETER_RATIONAL_T, mmal.MMAL_PARAMETER_BUFFER_FLAG_FILTER: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_BUFFER_REQUIREMENTS: mmal.MMAL_PARAMETER_BUFFER_REQUIREMENTS_T, mmal.MMAL_PARAMETER_CAMERA_BURST_CAPTURE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_CAMERA_CLOCKING_MODE: mmal.MMAL_PARAMETER_CAMERA_CLOCKING_MODE_T, mmal.MMAL_PARAMETER_CAMERA_CONFIG: mmal.MMAL_PARAMETER_CAMERA_CONFIG_T, mmal.MMAL_PARAMETER_CAMERA_CUSTOM_SENSOR_CONFIG: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_CAMERA_INFO: None, # adjusted by MMALCameraInfo.info_rev mmal.MMAL_PARAMETER_CAMERA_INTERFACE: mmal.MMAL_PARAMETER_CAMERA_INTERFACE_T, mmal.MMAL_PARAMETER_CAMERA_MIN_ISO: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_CAMERA_NUM: mmal.MMAL_PARAMETER_INT32_T, mmal.MMAL_PARAMETER_CAMERA_RX_CONFIG: mmal.MMAL_PARAMETER_CAMERA_RX_CONFIG_T, mmal.MMAL_PARAMETER_CAMERA_RX_TIMING: mmal.MMAL_PARAMETER_CAMERA_RX_TIMING_T, mmal.MMAL_PARAMETER_CAMERA_SETTINGS: mmal.MMAL_PARAMETER_CAMERA_SETTINGS_T, mmal.MMAL_PARAMETER_CAMERA_USE_CASE: mmal.MMAL_PARAMETER_CAMERA_USE_CASE_T, mmal.MMAL_PARAMETER_CAPTURE_EXPOSURE_COMP: mmal.MMAL_PARAMETER_INT32_T, mmal.MMAL_PARAMETER_CAPTURE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_CAPTURE_MODE: mmal.MMAL_PARAMETER_CAPTUREMODE_T, mmal.MMAL_PARAMETER_CAPTURE_STATS_PASS: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_CAPTURE_STATUS: mmal.MMAL_PARAMETER_CAPTURE_STATUS_T, mmal.MMAL_PARAMETER_CHANGE_EVENT_REQUEST: mmal.MMAL_PARAMETER_CHANGE_EVENT_REQUEST_T, mmal.MMAL_PARAMETER_CLOCK_ACTIVE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_CLOCK_DISCONT_THRESHOLD: mmal.MMAL_PARAMETER_CLOCK_DISCONT_THRESHOLD_T, mmal.MMAL_PARAMETER_CLOCK_ENABLE_BUFFER_INFO: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_CLOCK_FRAME_RATE: mmal.MMAL_PARAMETER_RATIONAL_T, mmal.MMAL_PARAMETER_CLOCK_LATENCY: mmal.MMAL_PARAMETER_CLOCK_LATENCY_T, mmal.MMAL_PARAMETER_CLOCK_REQUEST_THRESHOLD: mmal.MMAL_PARAMETER_CLOCK_REQUEST_THRESHOLD_T, mmal.MMAL_PARAMETER_CLOCK_SCALE: mmal.MMAL_PARAMETER_RATIONAL_T, mmal.MMAL_PARAMETER_CLOCK_TIME: mmal.MMAL_PARAMETER_INT64_T, mmal.MMAL_PARAMETER_CLOCK_UPDATE_THRESHOLD: mmal.MMAL_PARAMETER_CLOCK_UPDATE_THRESHOLD_T, mmal.MMAL_PARAMETER_COLOUR_EFFECT: mmal.MMAL_PARAMETER_COLOURFX_T, mmal.MMAL_PARAMETER_CONTRAST: mmal.MMAL_PARAMETER_RATIONAL_T, mmal.MMAL_PARAMETER_CORE_STATISTICS: mmal.MMAL_PARAMETER_CORE_STATISTICS_T, mmal.MMAL_PARAMETER_CUSTOM_AWB_GAINS: mmal.MMAL_PARAMETER_AWB_GAINS_T, mmal.MMAL_PARAMETER_DISPLAYREGION: mmal.MMAL_DISPLAYREGION_T, mmal.MMAL_PARAMETER_DPF_CONFIG: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_DYNAMIC_RANGE_COMPRESSION: mmal.MMAL_PARAMETER_DRC_T, mmal.MMAL_PARAMETER_ENABLE_RAW_CAPTURE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_EXIF_DISABLE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_EXIF: mmal.MMAL_PARAMETER_EXIF_T, mmal.MMAL_PARAMETER_EXP_METERING_MODE: mmal.MMAL_PARAMETER_EXPOSUREMETERINGMODE_T, mmal.MMAL_PARAMETER_EXPOSURE_COMP: mmal.MMAL_PARAMETER_INT32_T, mmal.MMAL_PARAMETER_EXPOSURE_MODE: mmal.MMAL_PARAMETER_EXPOSUREMODE_T, mmal.MMAL_PARAMETER_EXTRA_BUFFERS: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_FIELD_OF_VIEW: mmal.MMAL_PARAMETER_FIELD_OF_VIEW_T, mmal.MMAL_PARAMETER_FLASH: mmal.MMAL_PARAMETER_FLASH_T, mmal.MMAL_PARAMETER_FLASH_REQUIRED: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_FLASH_SELECT: mmal.MMAL_PARAMETER_FLASH_SELECT_T, mmal.MMAL_PARAMETER_FLICKER_AVOID: mmal.MMAL_PARAMETER_FLICKERAVOID_T, mmal.MMAL_PARAMETER_FOCUS: mmal.MMAL_PARAMETER_FOCUS_T, mmal.MMAL_PARAMETER_FOCUS_REGIONS: mmal.MMAL_PARAMETER_FOCUS_REGIONS_T, mmal.MMAL_PARAMETER_FOCUS_STATUS: mmal.MMAL_PARAMETER_FOCUS_STATUS_T, mmal.MMAL_PARAMETER_FPS_RANGE: mmal.MMAL_PARAMETER_FPS_RANGE_T, mmal.MMAL_PARAMETER_FRAME_RATE: mmal.MMAL_PARAMETER_RATIONAL_T, # actually mmal.MMAL_PARAMETER_FRAME_RATE_T but this only contains a rational anyway... mmal.MMAL_PARAMETER_IMAGE_EFFECT: mmal.MMAL_PARAMETER_IMAGEFX_T, mmal.MMAL_PARAMETER_IMAGE_EFFECT_PARAMETERS: mmal.MMAL_PARAMETER_IMAGEFX_PARAMETERS_T, mmal.MMAL_PARAMETER_INPUT_CROP: mmal.MMAL_PARAMETER_INPUT_CROP_T, mmal.MMAL_PARAMETER_INTRAPERIOD: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_ISO: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_JPEG_ATTACH_LOG: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_JPEG_Q_FACTOR: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_JPEG_RESTART_INTERVAL: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_LOCKSTEP_ENABLE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_LOGGING: mmal.MMAL_PARAMETER_LOGGING_T, mmal.MMAL_PARAMETER_MB_ROWS_PER_SLICE: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_MEM_USAGE: mmal.MMAL_PARAMETER_MEM_USAGE_T, mmal.MMAL_PARAMETER_MINIMISE_FRAGMENTATION: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_MIRROR: mmal.MMAL_PARAMETER_UINT32_T, # actually mmal.MMAL_PARAMETER_MIRROR_T but this just contains a uint32 mmal.MMAL_PARAMETER_NALUNITFORMAT: mmal.MMAL_PARAMETER_VIDEO_NALUNITFORMAT_T, mmal.MMAL_PARAMETER_NO_IMAGE_PADDING: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_POWERMON_ENABLE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_PRIVACY_INDICATOR: mmal.MMAL_PARAMETER_PRIVACY_INDICATOR_T, mmal.MMAL_PARAMETER_PROFILE: mmal.MMAL_PARAMETER_VIDEO_PROFILE_T, mmal.MMAL_PARAMETER_RATECONTROL: mmal.MMAL_PARAMETER_VIDEO_RATECONTROL_T, mmal.MMAL_PARAMETER_REDEYE: mmal.MMAL_PARAMETER_REDEYE_T, mmal.MMAL_PARAMETER_ROTATION: mmal.MMAL_PARAMETER_INT32_T, mmal.MMAL_PARAMETER_SATURATION: mmal.MMAL_PARAMETER_RATIONAL_T, mmal.MMAL_PARAMETER_SEEK: mmal.MMAL_PARAMETER_SEEK_T, mmal.MMAL_PARAMETER_SENSOR_INFORMATION: mmal.MMAL_PARAMETER_SENSOR_INFORMATION_T, mmal.MMAL_PARAMETER_SHARPNESS: mmal.MMAL_PARAMETER_RATIONAL_T, mmal.MMAL_PARAMETER_SHUTTER_SPEED: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_STATISTICS: mmal.MMAL_PARAMETER_STATISTICS_T, mmal.MMAL_PARAMETER_STEREOSCOPIC_MODE: mmal.MMAL_PARAMETER_STEREOSCOPIC_MODE_T, mmal.MMAL_PARAMETER_STILLS_DENOISE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_SUPPORTED_ENCODINGS: mmal.MMAL_PARAMETER_ENCODING_T, mmal.MMAL_PARAMETER_SUPPORTED_PROFILES: mmal.MMAL_PARAMETER_VIDEO_PROFILE_T, mmal.MMAL_PARAMETER_SW_SATURATION_DISABLE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_SW_SHARPEN_DISABLE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_SYSTEM_TIME: mmal.MMAL_PARAMETER_UINT64_T, mmal.MMAL_PARAMETER_THUMBNAIL_CONFIGURATION: mmal.MMAL_PARAMETER_THUMBNAIL_CONFIG_T, mmal.MMAL_PARAMETER_URI: mmal.MMAL_PARAMETER_URI_T, mmal.MMAL_PARAMETER_USE_STC: mmal.MMAL_PARAMETER_CAMERA_STC_MODE_T, mmal.MMAL_PARAMETER_VIDEO_ALIGN_HORIZ: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_VIDEO_ALIGN_VERT: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_VIDEO_BIT_RATE: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_VIDEO_DENOISE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_VIDEO_DROPPABLE_PFRAMES: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_VIDEO_EEDE_ENABLE: mmal.MMAL_PARAMETER_VIDEO_EEDE_ENABLE_T, mmal.MMAL_PARAMETER_VIDEO_EEDE_LOSSRATE: mmal.MMAL_PARAMETER_VIDEO_EEDE_LOSSRATE_T, mmal.MMAL_PARAMETER_VIDEO_ENCODE_FRAME_LIMIT_BITS: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_VIDEO_ENCODE_INITIAL_QUANT: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_VIDEO_ENCODE_INLINE_HEADER: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_VIDEO_ENCODE_INLINE_VECTORS: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_VIDEO_ENCODE_MAX_QUANT: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_VIDEO_ENCODE_MIN_QUANT: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_VIDEO_ENCODE_PEAK_RATE: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_VIDEO_ENCODE_QP_P: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_VIDEO_ENCODE_RC_MODEL: mmal.MMAL_PARAMETER_VIDEO_ENCODE_RC_MODEL_T, mmal.MMAL_PARAMETER_VIDEO_ENCODE_RC_SLICE_DQUANT: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_VIDEO_ENCODE_SEI_ENABLE: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_VIDEO_ENCODE_SPS_TIMING: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_VIDEO_FRAME_RATE: mmal.MMAL_PARAMETER_RATIONAL_T, # actually mmal.MMAL_PARAMETER_FRAME_RATE_T but this only contains a rational anyway... mmal.MMAL_PARAMETER_VIDEO_IMMUTABLE_INPUT: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_VIDEO_INTERLACE_TYPE: mmal.MMAL_PARAMETER_VIDEO_INTERLACE_TYPE_T, mmal.MMAL_PARAMETER_VIDEO_INTERPOLATE_TIMESTAMPS: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_VIDEO_INTRA_REFRESH: mmal.MMAL_PARAMETER_VIDEO_INTRA_REFRESH_T, mmal.MMAL_PARAMETER_VIDEO_LEVEL_EXTENSION: mmal.MMAL_PARAMETER_VIDEO_LEVEL_EXTENSION_T, mmal.MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS: mmal.MMAL_PARAMETER_UINT32_T, mmal.MMAL_PARAMETER_VIDEO_RENDER_STATS: mmal.MMAL_PARAMETER_VIDEO_RENDER_STATS_T, mmal.MMAL_PARAMETER_VIDEO_REQUEST_I_FRAME: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_VIDEO_STABILISATION: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_ZERO_COPY: mmal.MMAL_PARAMETER_BOOLEAN_T, mmal.MMAL_PARAMETER_ZERO_SHUTTER_LAG: mmal.MMAL_PARAMETER_ZEROSHUTTERLAG_T, mmal.MMAL_PARAMETER_ZOOM: mmal.MMAL_PARAMETER_SCALEFACTOR_T, } class PiCameraFraction(Fraction): """ Extends :class:`~fractions.Fraction` to act as a (numerator, denominator) tuple when required. """ def __len__(self): warnings.warn( PiCameraDeprecated( 'Accessing framerate as a tuple is deprecated; this value is ' 'now a Fraction, so you can query the numerator and ' 'denominator properties directly, convert to an int or float, ' 'or perform arithmetic operations and comparisons directly')) return 2 def __getitem__(self, index): warnings.warn( PiCameraDeprecated( 'Accessing framerate as a tuple is deprecated; this value is ' 'now a Fraction, so you can query the numerator and ' 'denominator properties directly, convert to an int or float, ' 'or perform arithmetic operations and comparisons directly')) if index == 0: return self.numerator elif index == 1: return self.denominator else: raise IndexError('invalid index %d' % index) def __contains__(self, value): return value in (self.numerator, self.denominator) class PiResolution(namedtuple('PiResolution', ('width', 'height'))): """ A :func:`~collections.namedtuple` derivative which represents a resolution with a :attr:`width` and :attr:`height`. .. attribute:: width The width of the resolution in pixels .. attribute:: height The height of the resolution in pixels .. versionadded:: 1.11 """ __slots__ = () # workaround python issue #24931 def pad(self, width=32, height=16): """ Returns the resolution padded up to the nearest multiple of *width* and *height* which default to 32 and 16 respectively (the camera's native block size for most operations). For example: .. code-block:: pycon >>> PiResolution(1920, 1080).pad() PiResolution(width=1920, height=1088) >>> PiResolution(100, 100).pad(16, 16) PiResolution(width=128, height=112) >>> PiResolution(100, 100).pad(16, 16) PiResolution(width=112, height=112) """ return PiResolution( width=((self.width + (width - 1)) // width) * width, height=((self.height + (height - 1)) // height) * height, ) def transpose(self): """ Returns the resolution with the width and height transposed. For example: .. code-block:: pycon >>> PiResolution(1920, 1080).transpose() PiResolution(width=1080, height=1920) """ return PiResolution(self.height, self.width) def __str__(self): return '%dx%d' % (self.width, self.height) class PiFramerateRange(namedtuple('PiFramerateRange', ('low', 'high'))): """ This class is a :func:`~collections.namedtuple` derivative used to store the low and high limits of a range of framerates. It is recommended that you access the information stored by this class by attribute rather than position (for example: ``camera.framerate_range.low`` rather than ``camera.framerate_range[0]``). .. attribute:: low The lowest framerate that the camera is permitted to use (inclusive). When the :attr:`~picamera.PiCamera.framerate_range` attribute is queried, this value will always be returned as a :class:`~fractions.Fraction`. .. attribute:: high The highest framerate that the camera is permitted to use (inclusive). When the :attr:`~picamera.PiCamera.framerate_range` attribute is queried, this value will always be returned as a :class:`~fractions.Fraction`. .. versionadded:: 1.13 """ __slots__ = () # workaround python issue #24931 def __str__(self): return '%s..%s' % (self.low, self.high) def open_stream(stream, output=True, buffering=65536): """ This is the core of picamera's IO-semantics. It returns a tuple of a file-like object and a bool indicating whether the stream requires closing once the caller is finished with it. * If *stream* is a string, it is opened as a file object (with mode 'wb' if *output* is ``True``, and the specified amount of *bufffering*). In this case the function returns ``(stream, True)``. * If *stream* is a stream with a ``write`` method, it is returned as ``(stream, False)``. * Otherwise *stream* is assumed to be a writeable buffer and is wrapped with :class:`BufferIO`. The function returns ``(stream, True)``. """ if isinstance(stream, bytes): stream = stream.decode('ascii') opened = isinstance(stream, str) if opened: stream = io.open(stream, 'wb' if output else 'rb', buffering) else: try: if output: stream.write else: stream.read except AttributeError: # Assume the stream is actually a buffer opened = True stream = BufferIO(stream) if output and not stream.writable: raise IOError('writeable buffer required for output') return (stream, opened) def close_stream(stream, opened): """ If *opened* is ``True``, then the ``close`` method of *stream* will be called. Otherwise, the function will attempt to call the ``flush`` method on *stream* (if one exists). This function essentially takes the output of :func:`open_stream` and finalizes the result. """ if opened: stream.close() else: try: stream.flush() except AttributeError: pass def to_resolution(value): """ Converts *value* which may be a (width, height) tuple or a string containing a representation of a resolution (e.g. "1024x768" or "1080p") to a (width, height) tuple. """ if isinstance(value, bytes): value = value.decode('utf-8') if isinstance(value, str): try: # A selection from https://en.wikipedia.org/wiki/Graphics_display_resolution # Feel free to suggest additions w, h = { 'VGA': (640, 480), 'SVGA': (800, 600), 'XGA': (1024, 768), 'SXGA': (1280, 1024), 'UXGA': (1600, 1200), 'HD': (1280, 720), 'FHD': (1920, 1080), '1080P': (1920, 1080), '720P': (1280, 720), }[value.strip().upper()] except KeyError: w, h = (int(i.strip()) for i in value.upper().split('X', 1)) else: try: w, h = value except (TypeError, ValueError): raise PiCameraValueError("Invalid resolution tuple: %r" % value) return PiResolution(w, h) def to_fraction(value, den_limit=65536): """ Converts *value*, which can be any numeric type, an MMAL_RATIONAL_T, or a (numerator, denominator) tuple to a :class:`~fractions.Fraction` limiting the denominator to the range 0 < n <= *den_limit* (which defaults to 65536). """ try: # int, long, or fraction n, d = value.numerator, value.denominator except AttributeError: try: # float n, d = value.as_integer_ratio() except AttributeError: try: n, d = value.num, value.den except AttributeError: try: # tuple n, d = value warnings.warn( PiCameraDeprecated( "Setting framerate or gains as a tuple is " "deprecated; please use one of Python's many " "numeric classes like int, float, Decimal, or " "Fraction instead")) except (TypeError, ValueError): # try and convert anything else to a Fraction directly value = Fraction(value) n, d = value.numerator, value.denominator # Ensure denominator is reasonable if d == 0: raise PiCameraValueError("Denominator cannot be 0") elif d > den_limit: return Fraction(n, d).limit_denominator(den_limit) else: return Fraction(n, d) def to_rational(value): """ Converts *value* (which can be anything accepted by :func:`to_fraction`) to an MMAL_RATIONAL_T structure. """ value = to_fraction(value) return mmal.MMAL_RATIONAL_T(value.numerator, value.denominator) def buffer_bytes(buf): """ Given an object which implements the :ref:`buffer protocol <bufferobjects>`, this function returns the size of the object in bytes. The object can be multi-dimensional or include items larger than byte-size. """ if not isinstance(buf, memoryview): m = memoryview(buf) return m.itemsize * reduce(mul, m.shape) def debug_pipeline(port): """ Given an :class:`MMALVideoPort` *port*, this traces all objects in the pipeline feeding it (including components and connections) and yields each object in turn. Hence the generator typically yields something like: * :class:`MMALVideoPort` (the specified output port) * :class:`MMALEncoder` (the encoder which owns the output port) * :class:`MMALVideoPort` (the encoder's input port) * :class:`MMALConnection` (the connection between the splitter and encoder) * :class:`MMALVideoPort` (the splitter's output port) * :class:`MMALSplitter` (the splitter on the camera's video port) * :class:`MMALVideoPort` (the splitter's input port) * :class:`MMALConnection` (the connection between the splitter and camera) * :class:`MMALVideoPort` (the camera's video port) * :class:`MMALCamera` (the camera component) """ def find_port(addr): for obj in MMALObject.REGISTRY: if isinstance(obj, MMALControlPort): if ct.addressof(obj._port[0]) == addr: return obj raise IndexError('unable to locate port with address %x' % addr) def find_component(addr): for obj in MMALObject.REGISTRY: if isinstance(obj, MMALBaseComponent) and obj._component is not None: if ct.addressof(obj._component[0]) == addr: return obj raise IndexError('unable to locate component with address %x' % addr) assert isinstance(port, (MMALControlPort, MMALPythonPort)) while True: if port.type == mmal.MMAL_PORT_TYPE_OUTPUT: yield port if isinstance(port, MMALPythonPort): comp = port._owner() else: comp = find_component(ct.addressof(port._port[0].component[0])) yield comp if not isinstance(comp, (MMALComponent, MMALPythonComponent)): break if comp.connection is None: break if isinstance(comp.connection, MMALPythonConnection): port = comp.connection._target else: port = find_port(ct.addressof(comp.connection._connection[0].in_[0])) yield port yield comp.connection if isinstance(comp.connection, MMALPythonConnection): port = comp.connection._source else: port = find_port(ct.addressof(comp.connection._connection[0].out[0])) def print_pipeline(port): """ Prints a human readable representation of the pipeline feeding the specified :class:`MMALVideoPort` *port*. """ rows = [[], [], [], [], []] under_comp = False for obj in reversed(list(debug_pipeline(port))): if isinstance(obj, (MMALBaseComponent, MMALPythonBaseComponent)): rows[0].append(obj.name) under_comp = True elif isinstance(obj, MMALVideoPort): rows[0].append('[%d]' % obj._port[0].index) if under_comp: rows[1].append('encoding') if obj.format == mmal.MMAL_ENCODING_OPAQUE: rows[1].append(obj.opaque_subformat) else: rows[1].append(mmal.FOURCC_str(obj._port[0].format[0].encoding)) if under_comp: rows[2].append('buf') rows[2].append('%dx%d' % (obj._port[0].buffer_num, obj._port[0].buffer_size)) if under_comp: rows[3].append('bitrate') rows[3].append('%dbps' % (obj._port[0].format[0].bitrate,)) if under_comp: rows[4].append('frame') under_comp = False rows[4].append('%dx%d@%sfps' % ( obj._port[0].format[0].es[0].video.width, obj._port[0].format[0].es[0].video.height, obj.framerate)) elif isinstance(obj, MMALPythonPort): rows[0].append('[%d]' % obj._index) if under_comp: rows[1].append('encoding') if obj.format == mmal.MMAL_ENCODING_OPAQUE: rows[1].append(obj.opaque_subformat) else: rows[1].append(mmal.FOURCC_str(obj._format[0].encoding)) if under_comp: rows[2].append('buf') rows[2].append('%dx%d' % (obj.buffer_count, obj.buffer_size)) if under_comp: rows[3].append('bitrate') rows[3].append('%dbps' % (obj._format[0].bitrate,)) if under_comp: rows[4].append('frame') under_comp = False rows[4].append('%dx%d@%sfps' % ( obj._format[0].es[0].video.width, obj._format[0].es[0].video.height, obj.framerate)) elif isinstance(obj, (MMALConnection, MMALPythonConnection)): rows[0].append('') rows[1].append('') rows[2].append('-->') rows[3].append('') rows[4].append('') if under_comp: rows[1].append('encoding') rows[2].append('buf') rows[3].append('bitrate') rows[4].append('frame') cols = list(zip(*rows)) max_lens = [max(len(s) for s in col) + 2 for col in cols] rows = [ ''.join('{0:{align}{width}s}'.format(s, align=align, width=max_len) for s, max_len, align in zip(row, max_lens, cycle('^<^>'))) for row in rows ] for row in rows: print(row) class MMALObject(object): """ Represents an object wrapper around an MMAL object (component, port, connection, etc). This base class maintains a registry of all MMAL objects currently alive (via weakrefs) which permits object lookup by name and listing all used MMAL objects. """ __slots__ = ('__weakref__',) REGISTRY = weakref.WeakSet() def __init__(self): super(MMALObject, self).__init__() MMALObject.REGISTRY.add(self) class MMALBaseComponent(MMALObject): """ Represents a generic MMAL component. Class attributes are read to determine the component type, and the OPAQUE sub-formats of each connectable port. """ __slots__ = ('_component', '_control', '_inputs', '_outputs') component_type = b'none' opaque_input_subformats = () opaque_output_subformats = () def __init__(self): super(MMALBaseComponent, self).__init__() self._component = ct.POINTER(mmal.MMAL_COMPONENT_T)() mmal_check( mmal.mmal_component_create(self.component_type, self._component), prefix="Failed to create MMAL component %s" % self.component_type) if self._component[0].input_num != len(self.opaque_input_subformats): raise PiCameraRuntimeError( 'Expected %d inputs but found %d on component %s' % ( len(self.opaque_input_subformats), self._component[0].input_num, self.component_type)) if self._component[0].output_num != len(self.opaque_output_subformats): raise PiCameraRuntimeError( 'Expected %d outputs but found %d on component %s' % ( len(self.opaque_output_subformats), self._component[0].output_num, self.component_type)) self._control = MMALControlPort(self._component[0].control) port_class = { mmal.MMAL_ES_TYPE_UNKNOWN: MMALPort, mmal.MMAL_ES_TYPE_CONTROL: MMALControlPort, mmal.MMAL_ES_TYPE_VIDEO: MMALVideoPort, mmal.MMAL_ES_TYPE_AUDIO: MMALAudioPort, mmal.MMAL_ES_TYPE_SUBPICTURE: MMALSubPicturePort, } self._inputs = tuple( port_class[self._component[0].input[n][0].format[0].type]( self._component[0].input[n], opaque_subformat) for n, opaque_subformat in enumerate(self.opaque_input_subformats)) self._outputs = tuple( port_class[self._component[0].output[n][0].format[0].type]( self._component[0].output[n], opaque_subformat) for n, opaque_subformat in enumerate(self.opaque_output_subformats)) def close(self): """ Close the component and release all its resources. After this is called, most methods will raise exceptions if called. """ if self._component is not None: # ensure we free any pools associated with input/output ports for output in self.outputs: output.disable() for input in self.inputs: input.disable() mmal.mmal_component_destroy(self._component) self._component = None self._inputs = () self._outputs = () self._control = None @property def name(self): return self._component[0].name.decode('ascii') @property def control(self): """ The :class:`MMALControlPort` control port of the component which can be used to configure most aspects of the component's behaviour. """ return self._control @property def inputs(self): """ A sequence of :class:`MMALPort` objects representing the inputs of the component. """ return self._inputs @property def outputs(self): """ A sequence of :class:`MMALPort` objects representing the outputs of the component. """ return self._outputs @property def enabled(self): """ Returns ``True`` if the component is currently enabled. Use :meth:`enable` and :meth:`disable` to control the component's state. """ return bool(self._component[0].is_enabled) def enable(self): """ Enable the component. When a component is enabled it will process data sent to its input port(s), sending the results to buffers on its output port(s). Components may be implicitly enabled by connections. """ mmal_check( mmal.mmal_component_enable(self._component), prefix="Failed to enable component") def disable(self): """ Disables the component. """ mmal_check( mmal.mmal_component_disable(self._component), prefix="Failed to disable component") def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): self.close() def __repr__(self): if self._component is not None: return '<%s "%s": %d inputs %d outputs>' % ( self.__class__.__name__, self.name, len(self.inputs), len(self.outputs)) else: return '<%s closed>' % self.__class__.__name__ class MMALControlPort(MMALObject): """ Represents an MMAL port with properties to configure the port's parameters. """ __slots__ = ('_port', '_params', '_wrapper') def __init__(self, port): super(MMALControlPort, self).__init__() self._port = port self._params = MMALPortParams(port) self._wrapper = None @property def index(self): """ Returns an integer indicating the port's position within its owning list (inputs, outputs, etc.) """ return self._port[0].index @property def enabled(self): """ Returns a :class:`bool` indicating whether the port is currently enabled. Unlike other classes, this is a read-only property. Use :meth:`enable` and :meth:`disable` to modify the value. """ return bool(self._port[0].is_enabled) def enable(self, callback=None): """ Enable the port with the specified callback function (this must be ``None`` for connected ports, and a callable for disconnected ports). The callback function must accept two parameters which will be this :class:`MMALControlPort` (or descendent) and an :class:`MMALBuffer` instance. Any return value will be ignored. """ def wrapper(port, buf): buf = MMALBuffer(buf) try: callback(self, buf) finally: buf.release() if callback: self._wrapper = mmal.MMAL_PORT_BH_CB_T(wrapper) else: self._wrapper = ct.cast(None, mmal.MMAL_PORT_BH_CB_T) mmal_check( mmal.mmal_port_enable(self._port, self._wrapper), prefix="Unable to enable port %s" % self.name) def disable(self): """ Disable the port. """ # NOTE: The test here only exists to avoid spamming the console; when # disabling an already disabled port MMAL dumps errors to stderr. If # this test isn't here closing a camera results in half a dozen lines # of ignored errors if self.enabled: try: mmal_check( mmal.mmal_port_disable(self._port), prefix="Unable to disable port %s" % self.name) except PiCameraMMALError as e: # Ignore the error if we're disabling an already disabled port if not (e.status == mmal.MMAL_EINVAL and not self.enabled): raise e self._wrapper = None @property def name(self): result = self._port[0].name.decode('ascii') if result.endswith(')'): try: # strip (format) from port names as it doesn't really belong # there (it doesn't identify the port in any way) and makes # matching some of the correctional cases a pain return result[:result.rindex('(')] except ValueError: return result else: return result @property def type(self): """ The type of the port. One of: * MMAL_PORT_TYPE_OUTPUT * MMAL_PORT_TYPE_INPUT * MMAL_PORT_TYPE_CONTROL * MMAL_PORT_TYPE_CLOCK """ return self._port[0].type @property def capabilities(self): """ The capabilities of the port. A bitfield of the following: * MMAL_PORT_CAPABILITY_PASSTHROUGH * MMAL_PORT_CAPABILITY_ALLOCATION * MMAL_PORT_CAPABILITY_SUPPORTS_EVENT_FORMAT_CHANGE """ return self._port[0].capabilities @property def params(self): """ The configurable parameters for the port. This is presented as a mutable mapping of parameter numbers to values, implemented by the :class:`MMALPortParams` class. """ return self._params def __repr__(self): if self._port is not None: return '<MMALControlPort "%s">' % self.name else: return '<MMALControlPort closed>' class MMALPort(MMALControlPort): """ Represents an MMAL port with properties to configure and update the port's format. This is the base class of :class:`MMALVideoPort`, :class:`MMALAudioPort`, and :class:`MMALSubPicturePort`. """ __slots__ = ('_opaque_subformat', '_pool', '_stopped', '_connection') # A mapping of corrected definitions of supported_formats for ports with # particular names. Older firmwares either raised EINVAL, ENOSYS, or just # reported the wrong things for various ports; these lists are derived from # querying newer firmwares or in some cases guessing sensible defaults # (for ports where even the newer firmwares get stuff wrong). _supported_formats_patch = { 'vc.ril.camera:out:2': [ mmal.MMAL_ENCODING_I420, mmal.MMAL_ENCODING_NV12, mmal.MMAL_ENCODING_I422, mmal.MMAL_ENCODING_YUYV, mmal.MMAL_ENCODING_YVYU, mmal.MMAL_ENCODING_VYUY, mmal.MMAL_ENCODING_UYVY, mmal.MMAL_ENCODING_BGR24, mmal.MMAL_ENCODING_BGRA, mmal.MMAL_ENCODING_RGB16, mmal.MMAL_ENCODING_YV12, mmal.MMAL_ENCODING_NV21, mmal.MMAL_ENCODING_RGB24, mmal.MMAL_ENCODING_RGBA, ], 'vc.ril.image_encode:in:0': [ mmal.MMAL_ENCODING_RGB16, mmal.MMAL_ENCODING_RGB24, mmal.MMAL_ENCODING_RGBA, mmal.MMAL_ENCODING_BGRA, mmal.MMAL_ENCODING_I420, mmal.MMAL_ENCODING_I422, mmal.MMAL_ENCODING_NV12, mmal.MMAL_ENCODING_YUYV, mmal.MMAL_ENCODING_YVYU, mmal.MMAL_ENCODING_VYUY, ], 'vc.ril.image_encode:out:0': [ mmal.MMAL_ENCODING_JPEG, mmal.MMAL_ENCODING_GIF, mmal.MMAL_ENCODING_PNG, mmal.MMAL_ENCODING_BMP, mmal.MMAL_ENCODING_PPM, mmal.MMAL_ENCODING_TGA, ], 'vc.ril.resize:in:0': [ mmal.MMAL_ENCODING_RGBA, mmal.MMAL_ENCODING_BGRA, mmal.MMAL_ENCODING_RGB16, mmal.MMAL_ENCODING_I420, # several invalid encodings (lowercase versions of the priors) # appear here in modern firmwares but since they don't map to any # constants they're excluded mmal.MMAL_ENCODING_I420_SLICE, ], 'vc.ril.resize:out:0': [ mmal.MMAL_ENCODING_RGBA, mmal.MMAL_ENCODING_BGRA, mmal.MMAL_ENCODING_RGB16, mmal.MMAL_ENCODING_I420, # same invalid encodings as above here mmal.MMAL_ENCODING_I420_SLICE, ], 'vc.ril.isp:in:0': [ mmal.MMAL_ENCODING_BAYER_SBGGR8, mmal.MMAL_ENCODING_BAYER_SBGGR10DPCM8, mmal.MMAL_ENCODING_BAYER_SBGGR10P, mmal.MMAL_ENCODING_BAYER_SBGGR12P, mmal.MMAL_ENCODING_YUYV, mmal.MMAL_ENCODING_YVYU, mmal.MMAL_ENCODING_VYUY, mmal.MMAL_ENCODING_UYVY, mmal.MMAL_ENCODING_I420, mmal.MMAL_ENCODING_YV12, mmal.MMAL_ENCODING_I422, mmal.MMAL_ENCODING_RGB24, mmal.MMAL_ENCODING_BGR24, mmal.MMAL_ENCODING_RGBA, mmal.MMAL_ENCODING_BGRA, mmal.MMAL_ENCODING_RGB16, mmal.MMAL_ENCODING_YUVUV128, mmal.MMAL_ENCODING_NV12, mmal.MMAL_ENCODING_NV21, ], 'vc.ril.isp:out:0': [ mmal.MMAL_ENCODING_YUYV, mmal.MMAL_ENCODING_YVYU, mmal.MMAL_ENCODING_VYUY, mmal.MMAL_ENCODING_UYVY, mmal.MMAL_ENCODING_I420, mmal.MMAL_ENCODING_YV12, mmal.MMAL_ENCODING_I422, mmal.MMAL_ENCODING_RGB24, mmal.MMAL_ENCODING_BGR24, mmal.MMAL_ENCODING_RGBA, mmal.MMAL_ENCODING_BGRA, mmal.MMAL_ENCODING_RGB16, mmal.MMAL_ENCODING_YUVUV128, mmal.MMAL_ENCODING_NV12, mmal.MMAL_ENCODING_NV21, ], 'vc.null_sink:in:0': [ mmal.MMAL_ENCODING_I420, mmal.MMAL_ENCODING_RGB24, mmal.MMAL_ENCODING_BGR24, mmal.MMAL_ENCODING_RGBA, mmal.MMAL_ENCODING_BGRA, ], } def __init__(self, port, opaque_subformat='OPQV'): super(MMALPort, self).__init__(port) self.opaque_subformat = opaque_subformat self._pool = None self._stopped = True self._connection = None def __repr__(self): if self._port is not None: return '<MMALPort "%s": format=MMAL_FOURCC(%r) buffers=%dx%d>' % ( self.name, mmal.FOURCC_str(self.format), self.buffer_count, self.buffer_size) else: return '<MMALPort closed>' def _get_opaque_subformat(self): return self._opaque_subformat def _set_opaque_subformat(self, value): self._opaque_subformat = value opaque_subformat = property( _get_opaque_subformat, _set_opaque_subformat, doc="""\ Retrieves or sets the opaque sub-format that the port speaks. While most formats (I420, RGBA, etc.) mean one thing, the opaque format is special; different ports produce different sorts of data when configured for OPQV format. This property stores a string which uniquely identifies what the associated port means for OPQV format. If the port does not support opaque format at all, set this property to ``None``. :class:`MMALConnection` uses this information when negotiating formats for a connection between two ports. """) def _get_format(self): result = self._port[0].format[0].encoding if FIX_RGB_BGR_ORDER: return { mmal.MMAL_ENCODING_RGB24: mmal.MMAL_ENCODING_BGR24, mmal.MMAL_ENCODING_BGR24: mmal.MMAL_ENCODING_RGB24, }.get(result, result) else: return result def _set_format(self, value): if FIX_RGB_BGR_ORDER: value = { mmal.MMAL_ENCODING_RGB24: mmal.MMAL_ENCODING_BGR24, mmal.MMAL_ENCODING_BGR24: mmal.MMAL_ENCODING_RGB24, }.get(value, value) self._port[0].format[0].encoding = value if value == mmal.MMAL_ENCODING_OPAQUE: self._port[0].format[0].encoding_variant = mmal.MMAL_ENCODING_I420 format = property(_get_format, _set_format, doc="""\ Retrieves or sets the encoding format of the port. Setting this attribute implicitly sets the encoding variant to a sensible value (I420 in the case of OPAQUE). After setting this attribute, call :meth:`commit` to make the changes effective. """) @property def supported_formats(self): """ Retrieves a sequence of supported encodings on this port. """ try: mp = self.params[mmal.MMAL_PARAMETER_SUPPORTED_ENCODINGS] except PiCameraMMALError as e: if e.status in (mmal.MMAL_EINVAL, mmal.MMAL_ENOSYS): # Workaround: old firmwares raise EINVAL or ENOSYS when various # ports are queried for supported formats. The following is the # correct sequence for old firmwares (note: swapped RGB24 and # BGR24 order in still port) ... probably (vc.ril.camera:out:2 # is definitely right, the rest are largely guessed based on # queries of later firmwares) try: return MMALPort._supported_formats_patch[self.name] except KeyError: raise e else: raise else: result = [ v for v in mp.encoding if v != 0 ][:mp.hdr.size // ct.sizeof(ct.c_uint32)] # Workaround: Fix incorrect result on MMALImageEncoder.outputs[0] # from modern firmwares if self.name == 'vc.ril.image_encode:out:0' and result == [ mmal.MMAL_ENCODING_MP2V, mmal.MMAL_ENCODING_MP2V, mmal.MMAL_ENCODING_H264, mmal.MMAL_ENCODING_H264, mmal.MMAL_ENCODING_VP7, mmal.MMAL_ENCODING_VP7, mmal.MMAL_ENCODING_VP6, mmal.MMAL_ENCODING_VP6]: return MMALPort._supported_formats_patch[self.name] else: return result def _get_bitrate(self): return self._port[0].format[0].bitrate def _set_bitrate(self, value): self._port[0].format[0].bitrate = value bitrate = property(_get_bitrate, _set_bitrate, doc="""\ Retrieves or sets the bitrate limit for the port's format. """) def copy_from(self, source): """ Copies the port's :attr:`format` from the *source* :class:`MMALControlPort`. """ if isinstance(source, MMALPythonPort): mmal.mmal_format_copy(self._port[0].format, source._format) else: mmal.mmal_format_copy(self._port[0].format, source._port[0].format) def commit(self): """ Commits the port's configuration and automatically updates the number and size of associated buffers according to the recommendations of the MMAL library. This is typically called after adjusting the port's format and/or associated settings (like width and height for video ports). """ mmal_check( mmal.mmal_port_format_commit(self._port), prefix="Format couldn't be set on port %s" % self.name) # Workaround: Unfortunately, there is an upstream issue with the # buffer_num_recommended which means it can't currently be used (see # discussion in raspberrypi/userland#167). There's another upstream # issue with buffer_num_min which means we need to guard against 0 # values... self._port[0].buffer_num = max(1, self._port[0].buffer_num_min) self._port[0].buffer_size = ( self._port[0].buffer_size_recommended if self._port[0].buffer_size_recommended > 0 else self._port[0].buffer_size_min) @property def pool(self): """ Returns the :class:`MMALPool` associated with the buffer, if any. """ return self._pool def get_buffer(self, block=True, timeout=None): """ Returns a :class:`MMALBuffer` from the associated :attr:`pool`. *block* and *timeout* act as they do in the corresponding :meth:`MMALPool.get_buffer`. """ if not self.enabled: raise PiCameraPortDisabled( 'cannot get buffer from disabled port %s' % self.name) return self.pool.get_buffer(block, timeout) def send_buffer(self, buf): """ Send :class:`MMALBuffer` *buf* to the port. """ if ( self.type == mmal.MMAL_PORT_TYPE_INPUT and isinstance(self._connection, MMALPythonConnection) and self._connection._callback is not None): try: modified_buf = self._connection._callback(self._connection, buf) except: buf.release() raise else: if modified_buf is None: buf.release() return else: buf = modified_buf try: mmal_check( mmal.mmal_port_send_buffer(self._port, buf._buf), prefix="cannot send buffer to port %s" % self.name) except PiCameraMMALError as e: # If port is disabled, convert exception for convenience if e.status == mmal.MMAL_EINVAL and not self.enabled: raise PiCameraPortDisabled( 'cannot send buffer to disabled port %s' % self.name) else: raise def flush(self): """ Flush the port. """ mmal_check( mmal.mmal_port_flush(self._port), prefix="Unable to flush port %s" % self.name) def _get_buffer_count(self): return self._port[0].buffer_num def _set_buffer_count(self, value): if value < 1: raise PiCameraMMALError(mmal.MMAL_EINVAL, 'buffer count <1') self._port[0].buffer_num = value buffer_count = property(_get_buffer_count, _set_buffer_count, doc="""\ The number of buffers allocated (or to be allocated) to the port. The ``mmalobj`` layer automatically configures this based on recommendations from the MMAL library. """) def _get_buffer_size(self): return self._port[0].buffer_size def _set_buffer_size(self, value): if value < 0: raise PiCameraMMALError(mmal.MMAL_EINVAL, 'buffer size <0') self._port[0].buffer_size = value buffer_size = property(_get_buffer_size, _set_buffer_size, doc="""\ The size of buffers allocated (or to be allocated) to the port. The size of buffers is typically dictated by the port's format. The ``mmalobj`` layer automatically configures this based on recommendations from the MMAL library. """) def enable(self, callback=None): """ Enable the port with the specified callback function (this must be ``None`` for connected ports, and a callable for disconnected ports). The callback function must accept two parameters which will be this :class:`MMALControlPort` (or descendent) and an :class:`MMALBuffer` instance. The callback should return ``True`` when processing is complete and no further calls are expected (e.g. at frame-end for an image encoder), and ``False`` otherwise. """ def wrapper(port, buf): buf = MMALBuffer(buf) try: if not self._stopped and callback(self, buf): self._stopped = True finally: buf.release() try: self._pool.send_buffer(block=False) except PiCameraPortDisabled: # The port was disabled, no point trying again pass # Workaround: There is a bug in the MJPEG encoder that causes a # deadlock if the FIFO is full on shutdown. Increasing the encoder # buffer size makes this less likely to happen. See # raspberrypi/userland#208. Connecting the encoder component resets the # output port's buffer size, hence why we correct this here, just # before enabling the port. if self._port[0].format[0].encoding == mmal.MMAL_ENCODING_MJPEG: self._port[0].buffer_size = max(512 * 1024, self._port[0].buffer_size_recommended) if callback: assert self._stopped assert self._pool is None self._stopped = False self._pool = MMALPortPool(self) try: self._wrapper = mmal.MMAL_PORT_BH_CB_T(wrapper) mmal_check( mmal.mmal_port_enable(self._port, self._wrapper), prefix="Unable to enable port %s" % self.name) # If this port is an output port, send it all the buffers # in the pool. If it's an input port, don't bother: the user # will presumably want to feed buffers to it manually if self._port[0].type == mmal.MMAL_PORT_TYPE_OUTPUT: self._pool.send_all_buffers(block=False) except: self._pool.close() self._pool = None self._stopped = True raise else: super(MMALPort, self).enable() def disable(self): """ Disable the port. """ self._stopped = True super(MMALPort, self).disable() if self._pool is not None: self._pool.close() self._pool = None @property def connection(self): """ If this port is connected to another, this property holds the :class:`MMALConnection` or :class:`MMALPythonConnection` object which represents that connection. If this port is not connected, this property is ``None``. """ return self._connection def connect(self, other, **options): """ Connect this port to the *other* :class:`MMALPort` (or :class:`MMALPythonPort`). The type and configuration of the connection will be automatically selected. Various connection *options* can be specified as keyword arguments. These will be passed onto the :class:`MMALConnection` or :class:`MMALPythonConnection` constructor that is called (see those classes for an explanation of the available options). """ # Always construct connections from the output end if self.type != mmal.MMAL_PORT_TYPE_OUTPUT: return other.connect(self, **options) if other.type != mmal.MMAL_PORT_TYPE_INPUT: raise PiCameraValueError( 'A connection can only be established between an output and ' 'an input port') if isinstance(other, MMALPythonPort): return MMALPythonConnection(self, other, **options) else: return MMALConnection(self, other, **options) def disconnect(self): """ Destroy the connection between this port and another port. """ if self.connection is not None: self.connection.close() class MMALVideoPort(MMALPort): """ Represents an MMAL port used to pass video data. """ __slots__ = () def __repr__(self): if self._port is not None: return '<MMALVideoPort "%s": format=MMAL_FOURCC(%r) buffers=%dx%d frames=%s@%sfps>' % ( self.name, mmal.FOURCC_str(self.format), self._port[0].buffer_num, self._port[0].buffer_size, self.framesize, self.framerate) else: return '<MMALVideoPort closed>' def _get_framesize(self): return PiResolution( self._port[0].format[0].es[0].video.crop.width, self._port[0].format[0].es[0].video.crop.height, ) def _set_framesize(self, value): value = to_resolution(value) video = self._port[0].format[0].es[0].video video.width = bcm_host.VCOS_ALIGN_UP(value.width, 32) video.height = bcm_host.VCOS_ALIGN_UP(value.height, 16) video.crop.width = value.width video.crop.height = value.height framesize = property(_get_framesize, _set_framesize, doc="""\ Retrieves or sets the size of the port's video frames as a (width, height) tuple. This attribute implicitly handles scaling the given size up to the block size of the camera (32x16). After setting this attribute, call :meth:`~MMALPort.commit` to make the changes effective. """) def _get_framerate(self): video = self._port[0].format[0].es[0].video try: return Fraction( video.frame_rate.num, video.frame_rate.den) except ZeroDivisionError: assert video.frame_rate.num == 0 return Fraction(0, 1) def _set_framerate(self, value): value = to_fraction(value) video = self._port[0].format[0].es[0].video video.frame_rate.num = value.numerator video.frame_rate.den = value.denominator framerate = property(_get_framerate, _set_framerate, doc="""\ Retrieves or sets the framerate of the port's video frames in fps. After setting this attribute, call :meth:`~MMALPort.commit` to make the changes effective. """) class MMALAudioPort(MMALPort): """ Represents an MMAL port used to pass audio data. """ __slots__ = () def __repr__(self): if self._port is not None: return '<MMALAudioPort "%s": format=MMAL_FOURCC(%r) buffers=%dx%d>' % ( self.name, mmal.FOURCC_str(self.format), self._port[0].buffer_num, self._port[0].buffer_size) else: return '<MMALAudioPort closed>' class MMALSubPicturePort(MMALPort): """ Represents an MMAL port used to pass sub-picture (caption) data. """ __slots__ = () def __repr__(self): if self._port is not None: return '<MMALSubPicturePort "%s": format=MMAL_FOURCC(%r) buffers=%dx%d>' % ( self.name, mmal.FOURCC_str(self.format), self._port[0].buffer_num, self._port[0].buffer_size) else: return '<MMALSubPicturePort closed>' class MMALPortParams(object): """ Represents the parameters of an MMAL port. This class implements the :attr:`MMALControlPort.params` attribute. Internally, the class understands how to convert certain structures to more common Python data-types. For example, parameters that expect an MMAL_RATIONAL_T type will return and accept Python's :class:`~fractions.Fraction` class (or any other numeric types), while parameters that expect an MMAL_BOOL_T type will treat anything as a truthy value. Parameters that expect the MMAL_PARAMETER_STRING_T structure will be treated as plain strings, and likewise MMAL_PARAMETER_INT32_T and similar structures will be treated as plain ints. Parameters that expect more complex structures will return and expect those structures verbatim. """ __slots__ = ('_port',) def __init__(self, port): super(MMALPortParams, self).__init__() self._port = port def __getitem__(self, key): dtype = PARAM_TYPES[key] # Use the short-cut functions where possible (teeny bit faster if we # get some C to do the structure wrapping for us) func = { mmal.MMAL_PARAMETER_RATIONAL_T: mmal.mmal_port_parameter_get_rational, mmal.MMAL_PARAMETER_BOOLEAN_T: mmal.mmal_port_parameter_get_boolean, mmal.MMAL_PARAMETER_INT32_T: mmal.mmal_port_parameter_get_int32, mmal.MMAL_PARAMETER_INT64_T: mmal.mmal_port_parameter_get_int64, mmal.MMAL_PARAMETER_UINT32_T: mmal.mmal_port_parameter_get_uint32, mmal.MMAL_PARAMETER_UINT64_T: mmal.mmal_port_parameter_get_uint64, }.get(dtype, mmal.mmal_port_parameter_get) conv = { mmal.MMAL_PARAMETER_RATIONAL_T: lambda v: Fraction(v.num, v.den), mmal.MMAL_PARAMETER_BOOLEAN_T: lambda v: v.value != mmal.MMAL_FALSE, mmal.MMAL_PARAMETER_INT32_T: lambda v: v.value, mmal.MMAL_PARAMETER_INT64_T: lambda v: v.value, mmal.MMAL_PARAMETER_UINT32_T: lambda v: v.value, mmal.MMAL_PARAMETER_UINT64_T: lambda v: v.value, mmal.MMAL_PARAMETER_STRING_T: lambda v: v.str.decode('ascii'), }.get(dtype, lambda v: v) if func == mmal.mmal_port_parameter_get: result = dtype( mmal.MMAL_PARAMETER_HEADER_T(key, ct.sizeof(dtype)) ) mmal_check( func(self._port, result.hdr), prefix="Failed to get parameter %d" % key) else: dtype = { mmal.MMAL_PARAMETER_RATIONAL_T: mmal.MMAL_RATIONAL_T, mmal.MMAL_PARAMETER_BOOLEAN_T: mmal.MMAL_BOOL_T, mmal.MMAL_PARAMETER_INT32_T: ct.c_int32, mmal.MMAL_PARAMETER_INT64_T: ct.c_int64, mmal.MMAL_PARAMETER_UINT32_T: ct.c_uint32, mmal.MMAL_PARAMETER_UINT64_T: ct.c_uint64, }[dtype] result = dtype() mmal_check( func(self._port, key, result), prefix="Failed to get parameter %d" % key) return conv(result) def __setitem__(self, key, value): dtype = PARAM_TYPES[key] func = { mmal.MMAL_PARAMETER_RATIONAL_T: mmal.mmal_port_parameter_set_rational, mmal.MMAL_PARAMETER_BOOLEAN_T: mmal.mmal_port_parameter_set_boolean, mmal.MMAL_PARAMETER_INT32_T: mmal.mmal_port_parameter_set_int32, mmal.MMAL_PARAMETER_INT64_T: mmal.mmal_port_parameter_set_int64, mmal.MMAL_PARAMETER_UINT32_T: mmal.mmal_port_parameter_set_uint32, mmal.MMAL_PARAMETER_UINT64_T: mmal.mmal_port_parameter_set_uint64, mmal.MMAL_PARAMETER_STRING_T: mmal.mmal_port_parameter_set_string, }.get(dtype, mmal.mmal_port_parameter_set) conv = { mmal.MMAL_PARAMETER_RATIONAL_T: lambda v: to_rational(v), mmal.MMAL_PARAMETER_BOOLEAN_T: lambda v: mmal.MMAL_TRUE if v else mmal.MMAL_FALSE, mmal.MMAL_PARAMETER_STRING_T: lambda v: v.encode('ascii'), }.get(dtype, lambda v: v) if func == mmal.mmal_port_parameter_set: mp = conv(value) assert mp.hdr.id == key assert mp.hdr.size >= ct.sizeof(dtype) mmal_check( func(self._port, mp.hdr), prefix="Failed to set parameter %d to %r" % (key, value)) else: mmal_check( func(self._port, key, conv(value)), prefix="Failed to set parameter %d to %r" % (key, value)) class MMALBuffer(object): """ Represents an MMAL buffer header. This is usually constructed from the buffer header pointer and is largely supplied to make working with the buffer's data a bit simpler. Using the buffer as a context manager implicitly locks the buffer's memory and returns the :mod:`ctypes` buffer object itself:: def callback(port, buf): with buf as data: # data is a ctypes uint8 array with size entries print(len(data)) Alternatively you can use the :attr:`data` property directly, which returns and modifies the buffer's data as a :class:`bytes` object (note this is generally slower than using the buffer object unless you are simply replacing the entire buffer):: def callback(port, buf): # the buffer contents as a byte-string print(buf.data) """ __slots__ = ('_buf',) def __init__(self, buf): super(MMALBuffer, self).__init__() self._buf = buf def _get_command(self): return self._buf[0].cmd def _set_command(self, value): self._buf[0].cmd = value command = property(_get_command, _set_command, doc="""\ The command set in the buffer's meta-data. This is usually 0 for buffers returned by an encoder; typically this is only used by buffers sent to the callback of a control port. """) def _get_flags(self): return self._buf[0].flags def _set_flags(self, value): self._buf[0].flags = value flags = property(_get_flags, _set_flags, doc="""\ The flags set in the buffer's meta-data, returned as a bitmapped integer. Typical flags include: * ``MMAL_BUFFER_HEADER_FLAG_EOS`` -- end of stream * ``MMAL_BUFFER_HEADER_FLAG_FRAME_START`` -- start of frame data * ``MMAL_BUFFER_HEADER_FLAG_FRAME_END`` -- end of frame data * ``MMAL_BUFFER_HEADER_FLAG_KEYFRAME`` -- frame is a key-frame * ``MMAL_BUFFER_HEADER_FLAG_FRAME`` -- frame data * ``MMAL_BUFFER_HEADER_FLAG_CODECSIDEINFO`` -- motion estimatation data """) def _get_pts(self): return self._buf[0].pts def _set_pts(self, value): self._buf[0].pts = value pts = property(_get_pts, _set_pts, doc="""\ The presentation timestamp (PTS) of the buffer, as an integer number of microseconds or ``MMAL_TIME_UNKNOWN``. """) def _get_dts(self): return self._buf[0].dts def _set_dts(self, value): self._buf[0].dts = value dts = property(_get_dts, _set_dts, doc="""\ The decoding timestamp (DTS) of the buffer, as an integer number of microseconds or ``MMAL_TIME_UNKNOWN``. """) @property def size(self): """ Returns the length of the buffer's data area in bytes. This will be greater than or equal to :attr:`length` and is fixed in value. """ return self._buf[0].alloc_size def _get_offset(self): return self._buf[0].offset def _set_offset(self, value): assert 0 <= value <= self.size self._buf[0].offset = value self.length = min(self.size - self.offset, self.length) offset = property(_get_offset, _set_offset, doc="""\ The offset from the start of the buffer at which the data actually begins. Defaults to 0. If this is set to a value which would force the current :attr:`length` off the end of the buffer's :attr:`size`, then :attr:`length` will be decreased automatically. """) def _get_length(self): return self._buf[0].length def _set_length(self, value): assert 0 <= value <= self.size - self.offset self._buf[0].length = value length = property(_get_length, _set_length, doc="""\ The length of data held in the buffer. Must be less than or equal to the allocated size of data held in :attr:`size` minus the data :attr:`offset`. This attribute can be used to effectively blank the buffer by setting it to zero. """) def _get_data(self): with self as buf: return ct.string_at( ct.byref(buf, self._buf[0].offset), self._buf[0].length) def _set_data(self, value): value_len = buffer_bytes(value) if value_len: if value_len > self.size: raise PiCameraValueError( 'data is too large for buffer (%d > %d)' % ( value_len, self.size)) bp = ct.c_uint8 * value_len try: sp = bp.from_buffer(value) except TypeError: sp = bp.from_buffer_copy(value) with self as buf: ct.memmove(buf, sp, value_len) self._buf[0].offset = 0 self._buf[0].length = value_len data = property(_get_data, _set_data, doc="""\ The data held in the buffer as a :class:`bytes` string. You can set this attribute to modify the data in the buffer. Acceptable values are anything that supports the buffer protocol, and which contains :attr:`size` bytes or less. Setting this attribute implicitly modifies the :attr:`length` attribute to the length of the specified value and sets :attr:`offset` to zero. .. note:: Accessing a buffer's data via this attribute is relatively slow (as it copies the buffer's data to/from Python objects). See the :class:`MMALBuffer` documentation for details of a faster (but more complex) method. """) def replicate(self, source): """ Replicates the *source* :class:`MMALBuffer`. This copies all fields from the *source* buffer, including the internal :attr:`data` pointer. In other words, after replication this buffer and the *source* buffer will share the same block of memory for *data*. The *source* buffer will also be referenced internally by this buffer and will only be recycled once this buffer is released. .. note:: This is fundamentally different to the operation of the :meth:`copy_from` method. It is much faster, but imposes the burden that two buffers now share data (the *source* cannot be released until the replicant has been released). """ mmal_check( mmal.mmal_buffer_header_replicate(self._buf, source._buf), prefix='unable to replicate buffer') def copy_from(self, source): """ Copies all fields (including data) from the *source* :class:`MMALBuffer`. This buffer must have sufficient :attr:`size` to store :attr:`length` bytes from the *source* buffer. This method implicitly sets :attr:`offset` to zero, and :attr:`length` to the number of bytes copied. .. note:: This is fundamentally different to the operation of the :meth:`replicate` method. It is much slower, but afterward the copied buffer is entirely independent of the *source*. """ assert self.size >= source.length source_len = source._buf[0].length if source_len: with self as target_buf, source as source_buf: ct.memmove(target_buf, ct.byref(source_buf, source.offset), source_len) self._buf[0].offset = 0 self._buf[0].length = source_len self.copy_meta(source) def copy_meta(self, source): """ Copy meta-data from the *source* :class:`MMALBuffer`; specifically this copies all buffer fields with the exception of :attr:`data`, :attr:`length` and :attr:`offset`. """ self._buf[0].cmd = source._buf[0].cmd self._buf[0].flags = source._buf[0].flags self._buf[0].dts = source._buf[0].dts self._buf[0].pts = source._buf[0].pts self._buf[0].type[0] = source._buf[0].type[0] def acquire(self): """ Acquire a reference to the buffer. This will prevent the buffer from being recycled until :meth:`release` is called. This method can be called multiple times in which case an equivalent number of calls to :meth:`release` must be made before the buffer will actually be released. """ mmal.mmal_buffer_header_acquire(self._buf) def release(self): """ Release a reference to the buffer. This is the opposing call to :meth:`acquire`. Once all references have been released, the buffer will be recycled. """ mmal.mmal_buffer_header_release(self._buf) def reset(self): """ Resets all buffer header fields to default values. """ mmal.mmal_buffer_header_reset(self._buf) def __enter__(self): mmal_check( mmal.mmal_buffer_header_mem_lock(self._buf), prefix='unable to lock buffer header memory') return ct.cast( self._buf[0].data, ct.POINTER(ct.c_uint8 * self._buf[0].alloc_size)).contents def __exit__(self, *exc): mmal.mmal_buffer_header_mem_unlock(self._buf) return False def __repr__(self): if self._buf is not None: return '<MMALBuffer object: flags=%s command=%s length=%d>' % ( ''.join(( 'S' if self.flags & mmal.MMAL_BUFFER_HEADER_FLAG_FRAME_START else '_', 'E' if self.flags & mmal.MMAL_BUFFER_HEADER_FLAG_FRAME_END else '_', 'K' if self.flags & mmal.MMAL_BUFFER_HEADER_FLAG_KEYFRAME else '_', 'C' if self.flags & mmal.MMAL_BUFFER_HEADER_FLAG_CONFIG else '_', 'M' if self.flags & mmal.MMAL_BUFFER_HEADER_FLAG_CODECSIDEINFO else '_', 'X' if self.flags & mmal.MMAL_BUFFER_HEADER_FLAG_EOS else '_', )), { 0: 'none', mmal.MMAL_EVENT_ERROR: 'error', mmal.MMAL_EVENT_FORMAT_CHANGED: 'format-change', mmal.MMAL_EVENT_PARAMETER_CHANGED: 'param-change', mmal.MMAL_EVENT_EOS: 'end-of-stream', }[self.command], self.length) else: return '<MMALBuffer object: ???>' class MMALQueue(object): """ Represents an MMAL buffer queue. Buffers can be added to the queue with the :meth:`put` method, and retrieved from the queue (with optional wait timeout) with the :meth:`get` method. """ __slots__ = ('_queue', '_created') def __init__(self, queue): self._created = False self._queue = queue @classmethod def create(cls): self = cls(mmal.mmal_queue_create()) self._created = True return self def close(self): if self._created: mmal_queue_destroy(self._queue) self._queue = None def __len__(self): return mmal.mmal_queue_length(self._queue) def get(self, block=True, timeout=None): """ Get the next buffer from the queue. If *block* is ``True`` (the default) and *timeout* is ``None`` (the default) then the method will block until a buffer is available. Otherwise *timeout* is the maximum time to wait (in seconds) for a buffer to become available. If a buffer is not available before the timeout expires, the method returns ``None``. Likewise, if *block* is ``False`` and no buffer is immediately available then ``None`` is returned. """ if block and timeout is None: buf = mmal.mmal_queue_wait(self._queue) elif block and timeout is not None: buf = mmal.mmal_queue_timedwait(self._queue, int(timeout * 1000)) else: buf = mmal.mmal_queue_get(self._queue) if buf: return MMALBuffer(buf) def put(self, buf): """ Place :class:`MMALBuffer` *buf* at the back of the queue. """ mmal.mmal_queue_put(self._queue, buf._buf) def put_back(self, buf): """ Place :class:`MMALBuffer` *buf* at the front of the queue. This is used when a buffer was removed from the queue but needs to be put back at the front where it was originally taken from. """ mmal.mmal_queue_put_back(self._queue, buf._buf) class MMALPool(object): """ Represents an MMAL pool containing :class:`MMALBuffer` objects. All active ports are associated with a pool of buffers, and a queue. Instances can be treated as a sequence of :class:`MMALBuffer` objects but this is only recommended for debugging purposes; otherwise, use the :meth:`get_buffer`, :meth:`send_buffer`, and :meth:`send_all_buffers` methods which work with the encapsulated :class:`MMALQueue`. """ __slots__ = ('_pool', '_queue') def __init__(self, pool): self._pool = pool super(MMALPool, self).__init__() self._queue = MMALQueue(pool[0].queue) def __len__(self): return self._pool[0].headers_num def __getitem__(self, index): return MMALBuffer(self._pool[0].header[index]) @property def queue(self): """ The :class:`MMALQueue` associated with the pool. """ return self._queue def close(self): if self._pool is not None: mmal.mmal_pool_destroy(self._pool) self._pool = None def resize(self, new_count, new_size): """ Resizes the pool to contain *new_count* buffers with *new_size* bytes allocated to each buffer. *new_count* must be 1 or more (you cannot resize a pool to contain no headers). However, *new_size* can be 0 which causes all payload buffers to be released. .. warning:: If the pool is associated with a port, the port must be disabled when resizing the pool. """ mmal_check( mmal.mmal_pool_resize(self._pool, new_count, new_size), prefix='unable to resize pool') def get_buffer(self, block=True, timeout=None): """ Get the next buffer from the pool's queue. See :meth:`MMALQueue.get` for the meaning of the parameters. """ return self._queue.get(block, timeout) def send_buffer(self, port, block=True, timeout=None): """ Get a buffer from the pool's queue and send it to *port*. *block* and *timeout* act as they do in :meth:`get_buffer`. If no buffer is available (for the values of *block* and *timeout*, :exc:`~picamera.PiCameraMMALError` is raised). """ buf = self.get_buffer(block, timeout) if buf is None: raise PiCameraMMALError(mmal.MMAL_EAGAIN, 'no buffers available') port.send_buffer(buf) def send_all_buffers(self, port, block=True, timeout=None): """ Send all buffers from the queue to *port*. *block* and *timeout* act as they do in :meth:`get_buffer`. If no buffer is available (for the values of *block* and *timeout*, :exc:`~picamera.PiCameraMMALError` is raised). """ for i in range(len(self._queue)): self.send_buffer(port, block, timeout) class MMALPortPool(MMALPool): """ Construct an MMAL pool for the number and size of buffers required by the :class:`MMALPort` *port*. """ __slots__ = ('_port',) def __init__(self, port): pool = mmal.mmal_port_pool_create( port._port, port._port[0].buffer_num, port._port[0].buffer_size) if not pool: raise PiCameraMMALError( mmal.MMAL_ENOSPC, 'failed to create buffer header pool for port %s' % port.name) super(MMALPortPool, self).__init__(pool) self._port = port def close(self): if self._pool is not None: mmal.mmal_port_pool_destroy(self._port._port, self._pool) self._port = None self._pool = None super(MMALPortPool, self).close() @property def port(self): return self._port def send_buffer(self, port=None, block=True, timeout=None): """ Get a buffer from the pool and send it to *port* (or the port the pool is associated with by default). *block* and *timeout* act as they do in :meth:`MMALPool.get_buffer`. """ if port is None: port = self._port super(MMALPortPool, self).send_buffer(port, block, timeout) def send_all_buffers(self, port=None, block=True, timeout=None): """ Send all buffers from the pool to *port* (or the port the pool is associated with by default). *block* and *timeout* act as they do in :meth:`MMALPool.get_buffer`. """ if port is None: port = self._port super(MMALPortPool, self).send_all_buffers(port, block, timeout) class MMALBaseConnection(MMALObject): """ Abstract base class for :class:`MMALConnection` and :class:`MMALPythonConnection`. Handles weakrefs to the source and target ports, and format negotiation. All other connection details are handled by the descendent classes. """ __slots__ = ('_source', '_target') default_formats = () compatible_opaque_formats = { ('OPQV-single', 'OPQV-single'), ('OPQV-dual', 'OPQV-dual'), ('OPQV-strips', 'OPQV-strips'), ('OPQV-dual', 'OPQV-single'), ('OPQV-single', 'OPQV-dual'), # recent firmwares permit this } def __init__( self, source, target, formats=default_formats): super(MMALBaseConnection, self).__init__() if not isinstance(source, (MMALPort, MMALPythonPort)): raise PiCameraValueError('source is not a port') if not isinstance(target, (MMALPort, MMALPythonPort)): raise PiCameraValueError('target is not a port') if source.type != mmal.MMAL_PORT_TYPE_OUTPUT: raise PiCameraValueError('source is not an output port') if target.type != mmal.MMAL_PORT_TYPE_INPUT: raise PiCameraValueError('target is not an input port') if source.connection is not None: raise PiCameraValueError('source port is already connected') if target.connection is not None: raise PiCameraValueError('target port is already connected') if formats is None: formats = () self._source = source self._target = target try: iter(formats) except TypeError: formats = (formats,) self._negotiate_format(formats) source._connection = self target._connection = self # Descendents continue with connection implementation... def close(self): if self._source is not None: self._source._connection = None self._source = None if self._target is not None: self._target._connection = None self._target = None def _negotiate_format(self, formats): def copy_format(): self._source.commit() self._target.copy_from(self._source) self._target.commit() def max_buffers(): self._source.buffer_count = self._target.buffer_count = max( self._source.buffer_count, self._target.buffer_count) self._source.buffer_size = self._target.buffer_size = max( self._source.buffer_size, self._target.buffer_size) # Filter out formats that aren't supported on both source and target # ports. This is a little tricky as ports that support OPAQUE never # claim they do (so we have to assume it's mutually supported) mutually_supported = ( set(self._source.supported_formats) & set(self._target.supported_formats) ) | {mmal.MMAL_ENCODING_OPAQUE} formats = [f for f in formats if f in mutually_supported] if formats: # If there are any formats left to try, perform the negotiation # with the filtered list. Again, there's some special casing to # deal with the incompatible OPAQUE sub-formats for f in formats: if f == mmal.MMAL_ENCODING_OPAQUE: if (self._source.opaque_subformat, self._target.opaque_subformat) in self.compatible_opaque_formats: self._source.format = mmal.MMAL_ENCODING_OPAQUE else: continue else: self._source.format = f try: copy_format() except PiCameraMMALError as e: if e.status != mmal.MMAL_EINVAL: raise continue else: max_buffers() return raise PiCameraMMALError( mmal.MMAL_EINVAL, 'failed to negotiate port format') else: # If no formats are available to try (either from filtering or # because none were given), assume the source port is set up # properly. Just copy the format to the target and hope the caller # knows what they're doing try: copy_format() except PiCameraMMALError as e: if e.status != mmal.MMAL_EINVAL: raise raise PiCameraMMALError( mmal.MMAL_EINVAL, 'failed to copy source format to target port') else: max_buffers() def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): self.close() @property def source(self): """ The source :class:`MMALPort` or :class:`MMALPythonPort` of the connection. """ return self._source @property def target(self): """ The target :class:`MMALPort` or :class:`MMALPythonPort` of the connection. """ return self._target class MMALConnection(MMALBaseConnection): """ Represents an MMAL internal connection between two components. The constructor accepts arguments providing the *source* :class:`MMALPort` and *target* :class:`MMALPort`. The *formats* parameter specifies an iterable of formats (in preference order) that the connection may attempt when negotiating formats between the two ports. If this is ``None``, or an empty iterable, no negotiation will take place and the source port's format will simply be copied to the target port. Otherwise, the iterable will be worked through in order until a format acceptable to both ports is discovered. .. note:: The default *formats* list starts with OPAQUE; the class understands the different OPAQUE sub-formats (see :ref:`mmal` for more information) and will only select OPAQUE if compatible sub-formats can be used on both ports. The *callback* parameter can optionally specify a callable which will be executed for each buffer that traverses the connection (providing an opportunity to manipulate or drop that buffer). If specified, it must be a callable which accepts two parameters: the :class:`MMALConnection` object sending the data, and the :class:`MMALBuffer` object containing data. The callable may optionally manipulate the :class:`MMALBuffer` and return it to permit it to continue traversing the connection, or return ``None`` in which case the buffer will be released. .. note:: There is a significant performance penalty for specifying a callback between MMAL components as it requires buffers to be copied from the GPU's memory to the CPU's memory and back again. .. data:: default_formats :annotation: = (MMAL_ENCODING_OPAQUE, MMAL_ENCODING_I420, MMAL_ENCODING_RGB24, MMAL_ENCODING_BGR24, MMAL_ENCODING_RGBA, MMAL_ENCODING_BGRA) Class attribute defining the default formats used to negotiate connections between MMAL components. """ __slots__ = ('_connection', '_callback', '_wrapper') default_formats = ( mmal.MMAL_ENCODING_OPAQUE, mmal.MMAL_ENCODING_I420, mmal.MMAL_ENCODING_RGB24, mmal.MMAL_ENCODING_BGR24, mmal.MMAL_ENCODING_RGBA, mmal.MMAL_ENCODING_BGRA, ) def __init__( self, source, target, formats=default_formats, callback=None): if not isinstance(source, MMALPort): raise PiCameraValueError('source is not an MMAL port') if not isinstance(target, MMALPort): raise PiCameraValueError('target is not an MMAL port') super(MMALConnection, self).__init__(source, target, formats) self._connection = ct.POINTER(mmal.MMAL_CONNECTION_T)() self._callback = callback flags = mmal.MMAL_CONNECTION_FLAG_ALLOCATION_ON_INPUT if callback is None: flags |= mmal.MMAL_CONNECTION_FLAG_TUNNELLING try: mmal_check( mmal.mmal_connection_create( self._connection, source._port, target._port, flags), prefix="Failed to create connection") except: self._connection = None raise def close(self): if self._connection is not None: mmal.mmal_connection_destroy(self._connection) self._connection = None self._wrapper = None super(MMALConnection, self).close() @property def enabled(self): """ Returns ``True`` if the connection is enabled. Use :meth:`enable` and :meth:`disable` to control the state of the connection. """ return bool(self._connection[0].is_enabled) def enable(self): """ Enable the connection. When a connection is enabled, data is continually transferred from the output port of the source to the input port of the target component. """ def wrapper(connection): buf = mmal.mmal_queue_get(connection[0].queue) if buf: buf = MMALBuffer(buf) try: modified_buf = self._callback(self, buf) except: buf.release() raise else: if modified_buf is not None: try: self._target.send_buffer(modified_buf) except PiCameraPortDisabled: # Target port disabled; ignore the error pass else: buf.release() return buf = mmal.mmal_queue_get(connection[0].pool[0].queue) if buf: buf = MMALBuffer(buf) try: self._source.send_buffer(buf) except PiCameraPortDisabled: # Source port has been disabled; ignore the error pass if self._callback is not None: self._wrapper = mmal.MMAL_CONNECTION_CALLBACK_T(wrapper) self._connection[0].callback = self._wrapper self._source.params[mmal.MMAL_PARAMETER_ZERO_COPY] = True self._target.params[mmal.MMAL_PARAMETER_ZERO_COPY] = True mmal_check( mmal.mmal_connection_enable(self._connection), prefix="Failed to enable connection") if self._callback is not None: MMALPool(self._connection[0].pool).send_all_buffers(self._source) def disable(self): """ Disables the connection. """ mmal_check( mmal.mmal_connection_disable(self._connection), prefix="Failed to disable connection") self._wrapper = None @property def name(self): return self._connection[0].name.decode('ascii') def __repr__(self): if self._connection is not None: return '<MMALConnection "%s">' % self.name else: return '<MMALConnection closed>' class MMALRawCamera(MMALBaseComponent): """ The MMAL "raw camera" component. Don't use this! If you insist on using this anyway, read the forum post about `raw sensor access`_ first. .. raw sensor access: https://www.raspberrypi.org/forums/viewtopic.php?f=43&t=109137 """ __slots__ = () component_type = mmal.MMAL_COMPONENT_RAW_CAMERA opaque_input_subformats = () opaque_output_subformats = ('OPQV-single',) class MMALCamera(MMALBaseComponent): """ Represents the MMAL camera component. This component has 0 input ports and 3 output ports. The intended use of the output ports (which in turn determines the behaviour of those ports) is as follows: * Port 0 is intended for preview renderers * Port 1 is intended for video recording * Port 2 is intended for still image capture Use the ``MMAL_PARAMETER_CAMERA_CONFIG`` parameter on the control port to obtain and manipulate the camera's configuration. """ __slots__ = () component_type = mmal.MMAL_COMPONENT_DEFAULT_CAMERA opaque_output_subformats = ('OPQV-single', 'OPQV-dual', 'OPQV-strips') annotate_structs = ( mmal.MMAL_PARAMETER_CAMERA_ANNOTATE_T, mmal.MMAL_PARAMETER_CAMERA_ANNOTATE_V2_T, mmal.MMAL_PARAMETER_CAMERA_ANNOTATE_V3_T, ) def __init__(self): global FIX_RGB_BGR_ORDER super(MMALCamera, self).__init__() if PARAM_TYPES[mmal.MMAL_PARAMETER_ANNOTATE] is None: found = False # try largest struct to smallest as later firmwares still happily # accept earlier revision structures # XXX do old firmwares reject too-large structs? for struct in reversed(MMALCamera.annotate_structs): try: PARAM_TYPES[mmal.MMAL_PARAMETER_ANNOTATE] = struct self.control.params[mmal.MMAL_PARAMETER_ANNOTATE] except PiCameraMMALError: pass else: found = True break if not found: PARAM_TYPES[mmal.MMAL_PARAMETER_ANNOTATE] = None raise PiCameraMMALError( mmal.MMAL_EINVAL, "unknown camera annotation structure revision") if FIX_RGB_BGR_ORDER is None: # old firmware lists BGR24 before RGB24 in supported_formats for f in self.outputs[1].supported_formats: if f == mmal.MMAL_ENCODING_BGR24: FIX_RGB_BGR_ORDER = True break elif f == mmal.MMAL_ENCODING_RGB24: FIX_RGB_BGR_ORDER = False break def _get_annotate_rev(self): try: return MMALCamera.annotate_structs.index(PARAM_TYPES[mmal.MMAL_PARAMETER_ANNOTATE]) + 1 except IndexError: raise PiCameraMMALError( mmal.MMAL_EINVAL, "unknown camera annotation structure revision") def _set_annotate_rev(self, value): try: PARAM_TYPES[mmal.MMAL_PARAMETER_ANNOTATE] = MMALCamera.annotate_structs[value - 1] except IndexError: raise PiCameraMMALError( mmal.MMAL_EINVAL, "invalid camera annotation structure revision") annotate_rev = property(_get_annotate_rev, _set_annotate_rev, doc="""\ The annotation capabilities of the firmware have evolved over time and several structures are available for querying and setting video annotations. By default the :class:`MMALCamera` class will pick the latest annotation structure supported by the current firmware but you can select older revisions with :attr:`annotate_rev` for other purposes (e.g. testing). """) class MMALCameraInfo(MMALBaseComponent): """ Represents the MMAL camera-info component. Query the ``MMAL_PARAMETER_CAMERA_INFO`` parameter on the control port to obtain information about the connected camera module. """ __slots__ = () component_type = mmal.MMAL_COMPONENT_DEFAULT_CAMERA_INFO info_structs = ( mmal.MMAL_PARAMETER_CAMERA_INFO_T, mmal.MMAL_PARAMETER_CAMERA_INFO_V2_T, ) def __init__(self): super(MMALCameraInfo, self).__init__() if PARAM_TYPES[mmal.MMAL_PARAMETER_CAMERA_INFO] is None: found = False # try smallest structure to largest as later firmwares reject # older structures for struct in MMALCameraInfo.info_structs: try: PARAM_TYPES[mmal.MMAL_PARAMETER_CAMERA_INFO] = struct self.control.params[mmal.MMAL_PARAMETER_CAMERA_INFO] except PiCameraMMALError: pass else: found = True break if not found: PARAM_TYPES[mmal.MMAL_PARAMETER_CAMERA_INFO] = None raise PiCameraMMALError( mmal.MMAL_EINVAL, "unknown camera info structure revision") def _get_info_rev(self): try: return MMALCameraInfo.info_structs.index(PARAM_TYPES[mmal.MMAL_PARAMETER_CAMERA_INFO]) + 1 except IndexError: raise PiCameraMMALError( mmal.MMAL_EINVAL, "unknown camera info structure revision") def _set_info_rev(self, value): try: PARAM_TYPES[mmal.MMAL_PARAMETER_CAMERA_INFO] = MMALCameraInfo.info_structs[value - 1] except IndexError: raise PiCameraMMALError( mmal.MMAL_EINVAL, "invalid camera info structure revision") info_rev = property(_get_info_rev, _set_info_rev, doc="""\ The camera information capabilities of the firmware have evolved over time and several structures are available for querying camera information. When initialized, :class:`MMALCameraInfo` will attempt to discover which structure is in use by the extant firmware. This property can be used to discover the structure version and to modify the version in use for other purposes (e.g. testing). """) class MMALComponent(MMALBaseComponent): """ Represents an MMAL component that acts as a filter of some sort, with a single input that connects to an upstream source port. This is an asbtract base class. """ __slots__ = () def __init__(self): super(MMALComponent, self).__init__() assert len(self.opaque_input_subformats) == 1 def close(self): self.disconnect() super(MMALComponent, self).close() def enable(self): super(MMALComponent, self).enable() if self.connection is not None: self.connection.enable() def disable(self): if self.connection is not None: self.connection.disable() super(MMALComponent, self).disable() def connect(self, source, **options): """ Connects the input port of this component to the specified *source* :class:`MMALPort` or :class:`MMALPythonPort`. Alternatively, as a convenience (primarily intended for command line experimentation; don't use this in scripts), *source* can be another component in which case the first unconnected output port will be selected as *source*. Keyword arguments will be passed along to the connection constructor. See :class:`MMALConnection` and :class:`MMALPythonConnection` for further information. """ if isinstance(source, (MMALPort, MMALPythonPort)): return self.inputs[0].connect(source) else: for port in source.outputs: if not port.connection: return self.inputs[0].connect(port, **options) raise PiCameraMMALError( mmal.MMAL_EINVAL, 'no free output ports on %r' % source) def disconnect(self): """ Destroy the connection between this component's input port and the upstream component. """ self.inputs[0].disconnect() @property def connection(self): """ The :class:`MMALConnection` or :class:`MMALPythonConnection` object linking this component to the upstream component. """ return self.inputs[0].connection class MMALSplitter(MMALComponent): """ Represents the MMAL splitter component. This component has 1 input port and 4 output ports which all generate duplicates of buffers passed to the input port. """ __slots__ = () component_type = mmal.MMAL_COMPONENT_DEFAULT_VIDEO_SPLITTER opaque_input_subformats = ('OPQV-single',) opaque_output_subformats = ('OPQV-single',) * 4 class MMALISPResizer(MMALComponent): """ Represents the MMAL ISP resizer component. This component has 1 input port and 1 output port, and supports resizing via the VideoCore ISP, along with conversion of numerous formats into numerous other formats (e.g. OPAQUE to RGB, etc). This is more efficient than :class:`MMALResizer` but is only available on later firmware versions. """ __slots__ = () component_type = mmal.MMAL_COMPONENT_DEFAULT_ISP opaque_input_subformats = ('OPQV-single',) opaque_output_subformats = (None,) class MMALResizer(MMALComponent): """ Represents the MMAL VPU resizer component. This component has 1 input port and 1 output port. This supports resizing via the VPU. This is not as efficient as :class:`MMALISPResizer` but is available on all firmware verions. The output port can (and usually should) have a different frame size to the input port. """ __slots__ = () component_type = mmal.MMAL_COMPONENT_DEFAULT_RESIZER opaque_input_subformats = (None,) opaque_output_subformats = (None,) class MMALEncoder(MMALComponent): """ Represents a generic MMAL encoder. This is an abstract base class. """ __slots__ = () class MMALVideoEncoder(MMALEncoder): """ Represents the MMAL video encoder component. This component has 1 input port and 1 output port. The output port is usually configured with ``MMAL_ENCODING_H264`` or ``MMAL_ENCODING_MJPEG``. """ __slots__ = () component_type = mmal.MMAL_COMPONENT_DEFAULT_VIDEO_ENCODER opaque_input_subformats = ('OPQV-dual',) opaque_output_subformats = (None,) class MMALImageEncoder(MMALEncoder): """ Represents the MMAL image encoder component. This component has 1 input port and 1 output port. The output port is typically configured with ``MMAL_ENCODING_JPEG`` but can also use ``MMAL_ENCODING_PNG``, ``MMAL_ENCODING_GIF``, etc. """ __slots__ = () component_type = mmal.MMAL_COMPONENT_DEFAULT_IMAGE_ENCODER opaque_input_subformats = ('OPQV-strips',) opaque_output_subformats = (None,) class MMALDecoder(MMALComponent): """ Represents a generic MMAL decoder. This is an abstract base class. """ __slots__ = () class MMALVideoDecoder(MMALDecoder): """ Represents the MMAL video decoder component. This component has 1 input port and 1 output port. The input port is usually configured with ``MMAL_ENCODING_H264`` or ``MMAL_ENCODING_MJPEG``. """ __slots__ = () component_type = mmal.MMAL_COMPONENT_DEFAULT_VIDEO_DECODER opaque_input_subformats = (None,) opaque_output_subformats = ('OPQV-single',) class MMALImageDecoder(MMALDecoder): """ Represents the MMAL iamge decoder component. This component has 1 input port and 1 output port. The input port is usually configured with ``MMAL_ENCODING_JPEG``. """ __slots__ = () component_type = mmal.MMAL_COMPONENT_DEFAULT_IMAGE_DECODER opaque_input_subformats = (None,) opaque_output_subformats = ('OPQV-single',) class MMALRenderer(MMALComponent): """ Represents the MMAL renderer component. This component has 1 input port and 0 output ports. It is used to implement the camera preview and overlays. """ __slots__ = () component_type = mmal.MMAL_COMPONENT_DEFAULT_VIDEO_RENDERER opaque_input_subformats = ('OPQV-single',) class MMALNullSink(MMALComponent): """ Represents the MMAL null-sink component. This component has 1 input port and 0 output ports. It is used to keep the preview port "alive" (and thus calculating white-balance and exposure) when the camera preview is not required. """ __slots__ = () component_type = mmal.MMAL_COMPONENT_DEFAULT_NULL_SINK opaque_input_subformats = ('OPQV-single',) class MMALPythonPort(MMALObject): """ Implements ports for Python-based MMAL components. """ __slots__ = ( '_buffer_count', '_buffer_size', '_connection', '_enabled', '_owner', '_pool', '_type', '_index', '_supported_formats', '_format', '_callback', ) _FORMAT_BPP = { 'I420': 1.5, 'RGB3': 3, 'RGBA': 4, 'BGR3': 3, 'BGRA': 4, } def __init__(self, owner, port_type, index): self._buffer_count = 2 self._buffer_size = 0 self._connection = None self._enabled = False self._owner = weakref.ref(owner) self._pool = None self._callback = None self._type = port_type self._index = index self._supported_formats = { mmal.MMAL_ENCODING_I420, mmal.MMAL_ENCODING_RGB24, mmal.MMAL_ENCODING_BGR24, mmal.MMAL_ENCODING_RGBA, mmal.MMAL_ENCODING_BGRA, } self._format = ct.pointer(mmal.MMAL_ES_FORMAT_T( type=mmal.MMAL_ES_TYPE_VIDEO, encoding=mmal.MMAL_ENCODING_I420, es=ct.pointer(mmal.MMAL_ES_SPECIFIC_FORMAT_T()))) def close(self): self.disconnect() self.disable() self._format = None def __repr__(self): return '<MMALPythonPort "%s": format=MMAL_FOURCC(%r) buffers=%dx%d frames=%s@%sfps>' % ( self.name, mmal.FOURCC_str(self.format), self.buffer_count, self.buffer_size, self.framesize, self.framerate) def _get_bitrate(self): return self._format[0].bitrate def _set_bitrate(self, value): self._format[0].bitrate = value bitrate = property(_get_bitrate, _set_bitrate, doc="""\ Retrieves or sets the bitrate limit for the port's format. """) def _get_supported_formats(self): return self._supported_formats def _set_supported_formats(self, value): try: value = {f for f in value} except TypeError: value = {value} if not value: raise PiCameraMMALError( mmal.MMAL_EINVAL, "port must have at least one valid format") self._supported_formats = value supported_formats = property(_get_supported_formats, _set_supported_formats, doc="""\ Retrieves or sets the set of valid formats for this port. The set must always contain at least one valid format. A single format can be specified; it will be converted implicitly to a singleton set. If the current port :attr:`format` is not a member of the new set, no error is raised. An error will be raised when :meth:`commit` is next called if :attr:`format` is still not a member of the set. """) def _get_format(self): return self._format[0].encoding def _set_format(self, value): self._format[0].encoding = value format = property(_get_format, _set_format, doc="""\ Retrieves or sets the encoding format of the port. Setting this attribute implicitly sets the encoding variant to a sensible value (I420 in the case of OPAQUE). """) def _get_framesize(self): return PiResolution( self._format[0].es[0].video.crop.width, self._format[0].es[0].video.crop.height, ) def _set_framesize(self, value): value = to_resolution(value) video = self._format[0].es[0].video video.width = bcm_host.VCOS_ALIGN_UP(value.width, 32) video.height = bcm_host.VCOS_ALIGN_UP(value.height, 16) video.crop.width = value.width video.crop.height = value.height framesize = property(_get_framesize, _set_framesize, doc="""\ Retrieves or sets the size of the source's video frames as a (width, height) tuple. This attribute implicitly handles scaling the given size up to the block size of the camera (32x16). """) def _get_framerate(self): video = self._format[0].es[0].video try: return Fraction( video.frame_rate.num, video.frame_rate.den) except ZeroDivisionError: return Fraction(0, 1) def _set_framerate(self, value): value = to_fraction(value) video = self._format[0].es[0].video video.frame_rate.num = value.numerator video.frame_rate.den = value.denominator framerate = property(_get_framerate, _set_framerate, doc="""\ Retrieves or sets the framerate of the port's video frames in fps. """) @property def pool(self): """ Returns the :class:`MMALPool` associated with the buffer, if any. """ return self._pool @property def opaque_subformat(self): return None def _get_buffer_count(self): return self._buffer_count def _set_buffer_count(self, value): if value < 1: raise PiCameraMMALError(mmal.MMAL_EINVAL, 'buffer count <1') self._buffer_count = int(value) buffer_count = property(_get_buffer_count, _set_buffer_count, doc="""\ The number of buffers allocated (or to be allocated) to the port. The default is 2 but more may be required in the case of long pipelines with replicated buffers. """) def _get_buffer_size(self): return self._buffer_size def _set_buffer_size(self, value): if value < 0: raise PiCameraMMALError(mmal.MMAL_EINVAL, 'buffer size <0') self._buffer_size = value buffer_size = property(_get_buffer_size, _set_buffer_size, doc="""\ The size of buffers allocated (or to be allocated) to the port. The size of buffers defaults to a value dictated by the port's format. """) def copy_from(self, source): """ Copies the port's :attr:`format` from the *source* :class:`MMALControlPort`. """ if isinstance(source, MMALPythonPort): mmal.mmal_format_copy(self._format, source._format) else: mmal.mmal_format_copy(self._format, source._port[0].format) def commit(self): """ Commits the port's configuration and automatically updates the number and size of associated buffers. This is typically called after adjusting the port's format and/or associated settings (like width and height for video ports). """ if self.format not in self.supported_formats: raise PiCameraMMALError( mmal.MMAL_EINVAL, 'invalid format for port %r' % self) self._buffer_count = 2 video = self._format[0].es[0].video try: self._buffer_size = int( MMALPythonPort._FORMAT_BPP[str(self.format)] * video.width * video.height) except KeyError: # If it's an unknown / encoded format just leave the buffer size # alone and hope the owning component knows what to set pass self._owner()._commit_port(self) @property def enabled(self): """ Returns a :class:`bool` indicating whether the port is currently enabled. Unlike other classes, this is a read-only property. Use :meth:`enable` and :meth:`disable` to modify the value. """ return self._enabled def enable(self, callback=None): """ Enable the port with the specified callback function (this must be ``None`` for connected ports, and a callable for disconnected ports). The callback function must accept two parameters which will be this :class:`MMALControlPort` (or descendent) and an :class:`MMALBuffer` instance. Any return value will be ignored. """ if self._connection is not None: if callback is not None: raise PiCameraMMALError( mmal.MMAL_EINVAL, 'connected ports must be enabled without callback') else: if callback is None: raise PiCameraMMALError( mmal.MMAL_EINVAL, 'unconnected ports must be enabled with callback') if self.type == mmal.MMAL_PORT_TYPE_INPUT or self._connection is None: self._pool = MMALPythonPortPool(self) self._callback = callback self._enabled = True def disable(self): """ Disable the port. """ self._enabled = False if self._pool is not None: # Release any unprocessed buffers from the owner's queue before # we destroy them all while True: buf = self._owner()._queue.get(False) if buf: buf.release() else: break self._pool.close() self._pool = None self._callback = None def get_buffer(self, block=True, timeout=None): """ Returns a :class:`MMALBuffer` from the associated :attr:`pool`. *block* and *timeout* act as they do in the corresponding :meth:`MMALPool.get_buffer`. """ if not self._enabled: raise PiCameraPortDisabled( 'cannot get buffer from disabled port %s' % self.name) if self._pool is not None: # Unconnected port or input port case; retrieve buffer from the # allocated pool return self._pool.get_buffer(block, timeout) else: # Connected output port case; get a buffer from the target input # port (in this case the port is just a thin proxy for the # corresponding input port) assert self.type == mmal.MMAL_PORT_TYPE_OUTPUT return self._connection.target.get_buffer(block, timeout) def send_buffer(self, buf): """ Send :class:`MMALBuffer` *buf* to the port. """ # NOTE: The MMALPythonConnection callback must occur *before* the test # for the port being enabled; it's meant to be the connection making # the callback prior to the buffer getting to the port after all if ( self.type == mmal.MMAL_PORT_TYPE_INPUT and self._connection._callback is not None): try: modified_buf = self._connection._callback(self._connection, buf) except: buf.release() raise else: if modified_buf is None: buf.release() else: buf = modified_buf if not self._enabled: raise PiCameraPortDisabled( 'cannot send buffer to disabled port %s' % self.name) if self._callback is not None: # but what about output ports? try: # XXX Return value? If it's an input port we should ignore it, self._callback(self, buf) except: buf.release() raise if self._type == mmal.MMAL_PORT_TYPE_INPUT: # Input port case; queue the buffer for processing on the # owning component self._owner()._queue.put(buf) elif self._connection is None: # Unconnected output port case; release the buffer back to the # pool buf.release() else: # Connected output port case; forward the buffer to the # connected component's input port # XXX If it's a format-change event? self._connection.target.send_buffer(buf) @property def name(self): return '%s:%s:%d' % (self._owner().name, { mmal.MMAL_PORT_TYPE_OUTPUT: 'out', mmal.MMAL_PORT_TYPE_INPUT: 'in', mmal.MMAL_PORT_TYPE_CONTROL: 'control', mmal.MMAL_PORT_TYPE_CLOCK: 'clock', }[self.type], self._index) @property def type(self): """ The type of the port. One of: * MMAL_PORT_TYPE_OUTPUT * MMAL_PORT_TYPE_INPUT * MMAL_PORT_TYPE_CONTROL * MMAL_PORT_TYPE_CLOCK """ return self._type @property def capabilities(self): """ The capabilities of the port. A bitfield of the following: * MMAL_PORT_CAPABILITY_PASSTHROUGH * MMAL_PORT_CAPABILITY_ALLOCATION * MMAL_PORT_CAPABILITY_SUPPORTS_EVENT_FORMAT_CHANGE """ return mmal.MMAL_PORT_CAPABILITY_SUPPORTS_EVENT_FORMAT_CHANGE @property def index(self): """ Returns an integer indicating the port's position within its owning list (inputs, outputs, etc.) """ return self._index @property def connection(self): """ If this port is connected to another, this property holds the :class:`MMALConnection` or :class:`MMALPythonConnection` object which represents that connection. If this port is not connected, this property is ``None``. """ return self._connection def connect(self, other, **options): """ Connect this port to the *other* :class:`MMALPort` (or :class:`MMALPythonPort`). The type and configuration of the connection will be automatically selected. Various connection options can be specified as keyword arguments. These will be passed onto the :class:`MMALConnection` or :class:`MMALPythonConnection` constructor that is called (see those classes for an explanation of the available options). """ # Always construct connections from the output end if self.type != mmal.MMAL_PORT_TYPE_OUTPUT: return other.connect(self, **options) if other.type != mmal.MMAL_PORT_TYPE_INPUT: raise PiCameraValueError( 'A connection can only be established between an output and ' 'an input port') return MMALPythonConnection(self, other, **options) def disconnect(self): """ Destroy the connection between this port and another port. """ if self.connection is not None: self.connection.close() class MMALPythonPortPool(MMALPool): """ Creates a pool of buffer headers for an :class:`MMALPythonPort`. This is only used when a fake port is used without a corresponding :class:`MMALPythonConnection`. """ __slots__ = ('_port',) def __init__(self, port): super(MMALPythonPortPool, self).__init__( mmal.mmal_pool_create(port.buffer_count, port.buffer_size)) self._port = port @property def port(self): return self._port def send_buffer(self, port=None, block=True, timeout=None): """ Get a buffer from the pool and send it to *port* (or the port the pool is associated with by default). *block* and *timeout* act as they do in :meth:`MMALPool.get_buffer`. """ if port is None: port = self._port super(MMALPythonPortPool, self).send_buffer(port, block, timeout) def send_all_buffers(self, port=None, block=True, timeout=None): """ Send all buffers from the pool to *port* (or the port the pool is associated with by default). *block* and *timeout* act as they do in :meth:`MMALPool.get_buffer`. """ if port is None: port = self._port super(MMALPythonPortPool, self).send_all_buffers(port, block, timeout) class MMALPythonBaseComponent(MMALObject): """ Base class for Python-implemented MMAL components. This class provides the :meth:`_commit_port` method used by descendents to control their ports' behaviour, and the :attr:`enabled` property. However, it is unlikely that users will want to sub-class this directly. See :class:`MMALPythonComponent` for a more useful starting point. """ __slots__ = ('_inputs', '_outputs', '_enabled',) def __init__(self): super(MMALPythonBaseComponent, self).__init__() self._enabled = False self._inputs = () self._outputs = () # TODO Control port? def close(self): """ Close the component and release all its resources. After this is called, most methods will raise exceptions if called. """ self.disable() @property def enabled(self): """ Returns ``True`` if the component is currently enabled. Use :meth:`enable` and :meth:`disable` to control the component's state. """ return self._enabled def enable(self): """ Enable the component. When a component is enabled it will process data sent to its input port(s), sending the results to buffers on its output port(s). Components may be implicitly enabled by connections. """ self._enabled = True def disable(self): """ Disables the component. """ self._enabled = False @property def control(self): """ The :class:`MMALControlPort` control port of the component which can be used to configure most aspects of the component's behaviour. """ return None @property def inputs(self): """ A sequence of :class:`MMALPort` objects representing the inputs of the component. """ return self._inputs @property def outputs(self): """ A sequence of :class:`MMALPort` objects representing the outputs of the component. """ return self._outputs def _commit_port(self, port): """ Called by ports when their format is committed. Descendents may override this to reconfigure output ports when input ports are committed, or to raise errors if the new port configuration is unacceptable. .. warning:: This method must *not* reconfigure input ports when called; however it can reconfigure *output* ports when input ports are committed. """ pass def __repr__(self): if self._outputs: return '<%s "%s": %d inputs %d outputs>' % ( self.__class__.__name__, self.name, len(self.inputs), len(self.outputs)) else: return '<%s closed>' % self.__class__.__name__ class MMALPythonSource(MMALPythonBaseComponent): """ Provides a source for other :class:`MMALComponent` instances. The specified *input* is read in chunks the size of the configured output buffer(s) until the input is exhausted. The :meth:`wait` method can be used to block until this occurs. If the output buffer is configured to use a full-frame unencoded format (like I420 or RGB), frame-end flags will be automatically generated by the source. When the input is exhausted an empty buffer with the End Of Stream (EOS) flag will be sent. The component provides all picamera's usual IO-handling characteristics; if *input* is a string, a file with that name will be opened as the input and closed implicitly when the component is closed. Otherwise, the input will not be closed implicitly (the component did not open it, so the assumption is that closing *input* is the caller's responsibility). If *input* is an object with a ``read`` method it is assumed to be a file-like object and is used as is. Otherwise, *input* is assumed to be a readable object supporting the buffer protocol (which is wrapped in a :class:`BufferIO` stream). """ __slots__ = ('_stream', '_opened', '_thread') def __init__(self, input): super(MMALPythonSource, self).__init__() self._inputs = () self._outputs = (MMALPythonPort(self, mmal.MMAL_PORT_TYPE_OUTPUT, 0),) self._stream, self._opened = open_stream(input, output=False) self._thread = None def close(self): super(MMALPythonSource, self).close() if self._outputs: self._outputs[0].close() self._outputs = () if self._stream: close_stream(self._stream, self._opened) self._stream = None def enable(self): super(MMALPythonSource, self).enable() self._thread = Thread(target=self._send_run) self._thread.daemon = True self._thread.start() def disable(self): super(MMALPythonSource, self).disable() if self._thread: self._thread.join() self._thread = None def wait(self, timeout=None): """ Wait for the source to send all bytes from the specified input. If *timeout* is specified, it is the number of seconds to wait for completion. The method returns ``True`` if the source completed within the specified timeout and ``False`` otherwise. """ if not self.enabled: raise PiCameraMMALError( mmal.MMAL_EINVAL, 'cannot wait on disabled component') self._thread.join(timeout) return not self._thread.is_alive() def _send_run(self): # Calculate the size of a frame if possible (i.e. when the output # format is an unencoded full frame format). If it's an unknown / # encoded format, we've no idea what the framesize is (this would # presumably require decoding the stream) so leave framesize as None. video = self._outputs[0]._format[0].es[0].video try: framesize = ( MMALPythonPort._FORMAT_BPP[str(self._outputs[0].format)] * video.width * video.height) except KeyError: framesize = None frameleft = framesize while self.enabled: buf = self._outputs[0].get_buffer(timeout=0.1) if buf: try: if frameleft is None: send = buf.size else: send = min(frameleft, buf.size) with buf as data: if send == buf.size: try: # readinto() is by far the fastest method of # getting data into the buffer buf.length = self._stream.readinto(data) except AttributeError: # if there's no readinto() method, fallback on # read() and the data setter (memmove) buf.data = self._stream.read(buf.size) else: buf.data = self._stream.read(send) if frameleft is not None: frameleft -= buf.length if not frameleft: buf.flags |= mmal.MMAL_BUFFER_HEADER_FLAG_FRAME_END frameleft = framesize if not buf.length: buf.flags |= mmal.MMAL_BUFFER_HEADER_FLAG_EOS break finally: self._outputs[0].send_buffer(buf) @property def name(self): return 'py.source' class MMALPythonComponent(MMALPythonBaseComponent): """ Provides a Python-based MMAL component with a *name*, a single input and the specified number of *outputs* (default 1). The :meth:`connect` and :meth:`disconnect` methods can be used to establish or break a connection from the input port to an upstream component. Typically descendents will override the :meth:`_handle_frame` method to respond to buffers sent to the input port, and will set :attr:`MMALPythonPort.supported_formats` in the constructor to define the formats that the component will work with. """ __slots__ = ('_name', '_thread', '_queue', '_error') def __init__(self, name='py.component', outputs=1): super(MMALPythonComponent, self).__init__() self._name = name self._thread = None self._error = None self._queue = MMALQueue.create() self._inputs = (MMALPythonPort(self, mmal.MMAL_PORT_TYPE_INPUT, 0),) self._outputs = tuple( MMALPythonPort(self, mmal.MMAL_PORT_TYPE_OUTPUT, n) for n in range(outputs) ) def close(self): super(MMALPythonComponent, self).close() self.disconnect() if self._inputs: self._inputs[0].close() self._inputs = () for output in self._outputs: output.disable() self._outputs = () self._queue.close() self._queue = None def connect(self, source, **options): """ Connects the input port of this component to the specified *source* :class:`MMALPort` or :class:`MMALPythonPort`. Alternatively, as a convenience (primarily intended for command line experimentation; don't use this in scripts), *source* can be another component in which case the first unconnected output port will be selected as *source*. Keyword arguments will be passed along to the connection constructor. See :class:`MMALConnection` and :class:`MMALPythonConnection` for further information. """ if isinstance(source, (MMALPort, MMALPythonPort)): return self.inputs[0].connect(source) else: for port in source.outputs: if not port.connection: return self.inputs[0].connect(port, **options) raise PiCameraMMALError( mmal.MMAL_EINVAL, 'no free output ports on %r' % source) def disconnect(self): """ Destroy the connection between this component's input port and the upstream component. """ self.inputs[0].disconnect() @property def connection(self): """ The :class:`MMALConnection` or :class:`MMALPythonConnection` object linking this component to the upstream component. """ return self.inputs[0].connection @property def name(self): return self._name def _commit_port(self, port): """ Overridden to to copy the input port's configuration to the output port(s), and to ensure that the output port(s)' format(s) match the input port's format. """ super(MMALPythonComponent, self)._commit_port(port) if port.type == mmal.MMAL_PORT_TYPE_INPUT: for output in self.outputs: output.copy_from(port) elif port.type == mmal.MMAL_PORT_TYPE_OUTPUT: if port.format != self.inputs[0].format: raise PiCameraMMALError(mmal.MMAL_EINVAL, 'output format mismatch') def enable(self): super(MMALPythonComponent, self).enable() if not self._thread: self._thread = Thread(target=self._thread_run) self._thread.daemon = True self._thread.start() def disable(self): super(MMALPythonComponent, self).disable() if self._thread: self._thread.join() self._thread = None if self._error: raise self._error def _thread_run(self): try: while self._enabled: buf = self._queue.get(timeout=0.1) if buf: try: handler = { 0: self._handle_frame, mmal.MMAL_EVENT_PARAMETER_CHANGED: self._handle_parameter_changed, mmal.MMAL_EVENT_FORMAT_CHANGED: self._handle_format_changed, mmal.MMAL_EVENT_ERROR: self._handle_error, mmal.MMAL_EVENT_EOS: self._handle_end_of_stream, }[buf.command] if handler(self.inputs[0], buf): self._enabled = False finally: buf.release() except Exception as e: self._error = e self._enabled = False def _handle_frame(self, port, buf): """ Handles frame data buffers (where :attr:`MMALBuffer.command` is set to 0). Typically, if the component has output ports, the method is expected to fetch a buffer from the output port(s), write data into them, and send them back to their respective ports. Return values are as for normal event handlers (``True`` when no more buffers are expected, ``False`` otherwise). """ return False def _handle_format_changed(self, port, buf): """ Handles format change events passed to the component (where :attr:`MMALBuffer.command` is set to MMAL_EVENT_FORMAT_CHANGED). The default implementation re-configures the input port of the component and emits the event on all output ports for downstream processing. Override this method if you wish to do something else in response to format change events. The *port* parameter is the port into which the event arrived, and *buf* contains the event itself (a MMAL_EVENT_FORMAT_CHANGED_T structure). Use ``mmal_event_format_changed_get`` on the buffer's data to extract the event. """ with buf as data: event = mmal.mmal_event_format_changed_get(buf._buf) if port.connection: # Handle format change on the source output port, if any. We # don't check the output port capabilities because it was the # port that emitted the format change in the first case so it'd # be odd if it didn't support them (or the format requested)! output = port.connection._source output.disable() if isinstance(output, MMALPythonPort): mmal.mmal_format_copy(output._format, event[0].format) else: mmal.mmal_format_copy(output._port[0].format, event[0].format) output.commit() output.buffer_count = ( event[0].buffer_num_recommended if event[0].buffer_num_recommended > 0 else event[0].buffer_num_min) output.buffer_size = ( event[0].buffer_size_recommended if event[0].buffer_size_recommended > 0 else event[0].buffer_size_min) if isinstance(output, MMALPythonPort): output.enable() else: output.enable(port.connection._transfer) # Now deal with the format change on this input port (this is only # called from _thread_run so port must be an input port) try: if not (port.capabilities & mmal.MMAL_PORT_CAPABILITY_SUPPORTS_EVENT_FORMAT_CHANGE): raise PiCameraMMALError( mmal.MMAL_EINVAL, 'port %s does not support event change' % self.name) mmal.mmal_format_copy(port._format, event[0].format) self._commit_port(port) port.pool.resize( event[0].buffer_num_recommended if event[0].buffer_num_recommended > 0 else event[0].buffer_num_min, event[0].buffer_size_recommended if event[0].buffer_size_recommended > 0 else event[0].buffer_size_min) port.buffer_count = len(port.pool) port.buffer_size = port.pool[0].size except: # If this port can't handle the format change, or if anything goes # wrong (like the owning component doesn't like the new format) # stop the pipeline (from here at least) if port.connection: port.connection.disable() raise # Chain the format-change onward so everything downstream sees it. # NOTE: the callback isn't given the format-change because there's no # image data in it for output in self.outputs: out_buf = output.get_buffer() out_buf.copy_from(buf) output.send_buffer(out_buf) return False def _handle_parameter_changed(self, port, buf): """ Handles parameter change events passed to the component (where :attr:`MMALBuffer.command` is set to MMAL_EVENT_PARAMETER_CHANGED). The default implementation does nothing but return ``False`` (indicating that processing should continue). Override this in descendents to respond to parameter changes. The *port* parameter is the port into which the event arrived, and *buf* contains the event itself (a MMAL_EVENT_PARAMETER_CHANGED_T structure). """ return False def _handle_error(self, port, buf): """ Handles error notifications passed to the component (where :attr:`MMALBuffer.command` is set to MMAL_EVENT_ERROR). The default implementation does nothing but return ``True`` (indicating that processing should halt). Override this in descendents to respond to error events. The *port* parameter is the port into which the event arrived. """ return True def _handle_end_of_stream(self, port, buf): """ Handles end-of-stream notifications passed to the component (where :attr:`MMALBuffer.command` is set to MMAL_EVENT_EOS). The default implementation does nothing but return ``True`` (indicating that processing should halt). Override this in descendents to respond to the end of stream. The *port* parameter is the port into which the event arrived. """ return True class MMALPythonTarget(MMALPythonComponent): """ Provides a simple component that writes all received buffers to the specified *output* until a frame with the *done* flag is seen (defaults to MMAL_BUFFER_HEADER_FLAG_EOS indicating End Of Stream). The component provides all picamera's usual IO-handling characteristics; if *output* is a string, a file with that name will be opened as the output and closed implicitly when the component is closed. Otherwise, the output will not be closed implicitly (the component did not open it, so the assumption is that closing *output* is the caller's responsibility). If *output* is an object with a ``write`` method it is assumed to be a file-like object and is used as is. Otherwise, *output* is assumed to be a writeable object supporting the buffer protocol (which is wrapped in a :class:`BufferIO` stream). """ __slots__ = ('_opened', '_stream', '_done', '_event') def __init__(self, output, done=mmal.MMAL_BUFFER_HEADER_FLAG_EOS): super(MMALPythonTarget, self).__init__(name='py.target', outputs=0) self._stream, self._opened = open_stream(output) self._done = done self._event = Event() # Accept all the formats picamera generally produces (user can add # other esoteric stuff if they need to) self.inputs[0].supported_formats = { mmal.MMAL_ENCODING_MJPEG, mmal.MMAL_ENCODING_H264, mmal.MMAL_ENCODING_JPEG, mmal.MMAL_ENCODING_GIF, mmal.MMAL_ENCODING_PNG, mmal.MMAL_ENCODING_BMP, mmal.MMAL_ENCODING_I420, mmal.MMAL_ENCODING_RGB24, mmal.MMAL_ENCODING_BGR24, mmal.MMAL_ENCODING_RGBA, mmal.MMAL_ENCODING_BGRA, } def close(self): super(MMALPythonTarget, self).close() close_stream(self._stream, self._opened) def enable(self): self._event.clear() super(MMALPythonTarget, self).enable() def wait(self, timeout=None): """ Wait for the output to be "complete" as defined by the constructor's *done* parameter. If *timeout* is specified it is the number of seconds to wait for completion. The method returns ``True`` if the target completed within the specified timeout and ``False`` otherwise. """ return self._event.wait(timeout) def _handle_frame(self, port, buf): self._stream.write(buf.data) if buf.flags & self._done: self._event.set() return True return False class MMALPythonConnection(MMALBaseConnection): """ Represents a connection between an :class:`MMALPythonBaseComponent` and a :class:`MMALBaseComponent` or another :class:`MMALPythonBaseComponent`. The constructor accepts arguments providing the *source* :class:`MMALPort` (or :class:`MMALPythonPort`) and *target* :class:`MMALPort` (or :class:`MMALPythonPort`). The *formats* parameter specifies an iterable of formats (in preference order) that the connection may attempt when negotiating formats between the two ports. If this is ``None``, or an empty iterable, no negotiation will take place and the source port's format will simply be copied to the target port. Otherwise, the iterable will be worked through in order until a format acceptable to both ports is discovered. The *callback* parameter can optionally specify a callable which will be executed for each buffer that traverses the connection (providing an opportunity to manipulate or drop that buffer). If specified, it must be a callable which accepts two parameters: the :class:`MMALPythonConnection` object sending the data, and the :class:`MMALBuffer` object containing data. The callable may optionally manipulate the :class:`MMALBuffer` and return it to permit it to continue traversing the connection, or return ``None`` in which case the buffer will be released. .. data:: default_formats :annotation: = (MMAL_ENCODING_I420, MMAL_ENCODING_RGB24, MMAL_ENCODING_BGR24, MMAL_ENCODING_RGBA, MMAL_ENCODING_BGRA) Class attribute defining the default formats used to negotiate connections between Python and and MMAL components, in preference order. Note that OPAQUE is not present in contrast with the default formats in :class:`MMALConnection`. """ __slots__ = ('_enabled', '_callback') default_formats = ( mmal.MMAL_ENCODING_I420, mmal.MMAL_ENCODING_RGB24, mmal.MMAL_ENCODING_BGR24, mmal.MMAL_ENCODING_RGBA, mmal.MMAL_ENCODING_BGRA, ) def __init__( self, source, target, formats=default_formats, callback=None): if not ( isinstance(source, MMALPythonPort) or isinstance(target, MMALPythonPort) ): raise PiCameraValueError('use a real MMAL connection') super(MMALPythonConnection, self).__init__(source, target, formats) self._enabled = False self._callback = callback def close(self): self.disable() super(MMALPythonConnection, self).close() @property def enabled(self): """ Returns ``True`` if the connection is enabled. Use :meth:`enable` and :meth:`disable` to control the state of the connection. """ return self._enabled def enable(self): """ Enable the connection. When a connection is enabled, data is continually transferred from the output port of the source to the input port of the target component. """ if not self._enabled: self._enabled = True if isinstance(self._target, MMALPythonPort): # Connected python input ports require no callback self._target.enable() else: # Connected MMAL input ports don't know they're connected so # provide a dummy callback self._target.params[mmal.MMAL_PARAMETER_ZERO_COPY] = True self._target.enable(lambda port, buf: True) if isinstance(self._source, MMALPythonPort): # Connected python output ports are nothing more than thin # proxies for the target input port; no callback required self._source.enable() else: # Connected MMAL output ports are made to transfer their # data to the Python input port self._source.params[mmal.MMAL_PARAMETER_ZERO_COPY] = True self._source.enable(self._transfer) def disable(self): """ Disables the connection. """ self._enabled = False self._source.disable() self._target.disable() def _transfer(self, port, buf): while self._enabled: try: dest = self._target.get_buffer(timeout=0.01) except PiCameraPortDisabled: dest = None if dest: dest.copy_from(buf) try: self._target.send_buffer(dest) except PiCameraPortDisabled: pass return False @property def name(self): return '%s/%s' % (self._source.name, self._target.name) def __repr__(self): try: return '<MMALPythonConnection "%s">' % self.name except NameError: return '<MMALPythonConnection closed>'
availability.py
import time import threading from metrics.metric import Metric from datetime import datetime import numpy as np METRIC_NAME = 'Availability' VALUE_FIELD = 'value' UNIT_FIELD = 'unit' class Availability(Metric): def __init__(self, conf_path='conf/conf.json'): super().__init__(conf_path) def compute_metric(self, update_interval): while True: # Compute time window of interest for the query t0 = datetime.now() time.sleep(update_interval) t1 = datetime.now() #TODO modificare metodo per la time window che non è conforme alle richeste timestamp, time_window = self.format_time_window(t0, t1) timestamp, time_window = '2016-06-20T22:28:46', '[2018-06-20T22:28:46 TO 2020-06-20T22:36:41]' # TODO: delete this line vdcs = self.read_vdcs_from_file() for vdc in vdcs: methods = self.read_methods(vdc) for method in methods: response = super().search(vdc, method, METRIC_NAME, timestamp, time_window) availabilities = [] for element in response: availabilities.append(element[VALUE_FIELD]) mean = np.mean(availabilities) self.write(vdc, methods, mean, METRIC_NAME, response[0][UNIT_FIELD], timestamp, time_window) print() def launch_sync_update(self): queries = self.conf_data['availability']['queries'] for query in queries: update_interval = query['update_interval'] threading.Thread(target=self.compute_metric, args=[update_interval]).start()
bbox_regression.py
""" This file has functions about generating bounding box regression targets """ from ..pycocotools.mask import encode import numpy as np from ..logger import logger from .bbox_transform import bbox_overlaps, bbox_transform from rcnn.config import config import math import cv2 import PIL.Image as Image import threading import Queue def compute_bbox_regression_targets(rois, overlaps, labels): """ given rois, overlaps, gt labels, compute bounding box regression targets :param rois: roidb[i]['boxes'] k * 4 :param overlaps: roidb[i]['max_overlaps'] k * 1 :param labels: roidb[i]['max_classes'] k * 1 :return: targets[i][class, dx, dy, dw, dh] k * 5 """ # Ensure ROIs are floats rois = rois.astype(np.float, copy=False) # Sanity check if len(rois) != len(overlaps): logger.warning('bbox regression: len(rois) != len(overlaps)') # Indices of ground-truth ROIs gt_inds = np.where(overlaps == 1)[0] if len(gt_inds) == 0: logger.warning('bbox regression: len(gt_inds) == 0') # Indices of examples for which we try to make predictions ex_inds = np.where(overlaps >= config.TRAIN.BBOX_REGRESSION_THRESH)[0] # Get IoU overlap between each ex ROI and gt ROI ex_gt_overlaps = bbox_overlaps(rois[ex_inds, :], rois[gt_inds, :]) # Find which gt ROI each ex ROI has max overlap with: # this will be the ex ROI's gt target gt_assignment = ex_gt_overlaps.argmax(axis=1) gt_rois = rois[gt_inds[gt_assignment], :] ex_rois = rois[ex_inds, :] targets = np.zeros((rois.shape[0], 5), dtype=np.float32) targets[ex_inds, 0] = labels[ex_inds] targets[ex_inds, 1:] = bbox_transform(ex_rois, gt_rois) return targets def add_bbox_regression_targets(roidb): """ given roidb, add ['bbox_targets'] and normalize bounding box regression targets :param roidb: roidb to be processed. must have gone through imdb.prepare_roidb :return: means, std variances of targets """ logger.info('bbox regression: add bounding box regression targets') assert len(roidb) > 0 assert 'max_classes' in roidb[0] num_images = len(roidb) num_classes = roidb[0]['gt_overlaps'].shape[1] for im_i in range(num_images): rois = roidb[im_i]['boxes'] max_overlaps = roidb[im_i]['max_overlaps'] max_classes = roidb[im_i]['max_classes'] roidb[im_i]['bbox_targets'] = compute_bbox_regression_targets(rois, max_overlaps, max_classes) if config.TRAIN.BBOX_NORMALIZATION_PRECOMPUTED: # use fixed / precomputed means and stds instead of empirical values means = np.tile(np.array(config.TRAIN.BBOX_MEANS), (num_classes, 1)) stds = np.tile(np.array(config.TRAIN.BBOX_STDS), (num_classes, 1)) else: # compute mean, std values class_counts = np.zeros((num_classes, 1)) + 1e-14 sums = np.zeros((num_classes, 4)) squared_sums = np.zeros((num_classes, 4)) for im_i in range(num_images): targets = roidb[im_i]['bbox_targets'] for cls in range(1, num_classes): cls_indexes = np.where(targets[:, 0] == cls)[0] if cls_indexes.size > 0: class_counts[cls] += cls_indexes.size sums[cls, :] += targets[cls_indexes, 1:].sum(axis=0) squared_sums[cls, :] += (targets[cls_indexes, 1:] ** 2).sum(axis=0) means = sums / class_counts # var(x) = E(x^2) - E(x)^2 stds = np.sqrt(squared_sums / class_counts - means ** 2) # normalized targets for im_i in range(num_images): targets = roidb[im_i]['bbox_targets'] for cls in range(1, num_classes): cls_indexes = np.where(targets[:, 0] == cls)[0] roidb[im_i]['bbox_targets'][cls_indexes, 1:] -= means[cls, :] roidb[im_i]['bbox_targets'][cls_indexes, 1:] /= stds[cls, :] return means.ravel(), stds.ravel() def expand_bbox_regression_targets(bbox_targets_data, num_classes): """ expand from 5 to 4 * num_classes; only the right class has non-zero bbox regression targets :param bbox_targets_data: [k * 5] :param num_classes: number of classes :return: bbox target processed [k * 4 num_classes] bbox_weights ! only foreground boxes have bbox regression computation! """ classes = bbox_targets_data[:, 0] bbox_targets = np.zeros((classes.size, 4 * num_classes), dtype=np.float32) bbox_weights = np.zeros(bbox_targets.shape, dtype=np.float32) indexes = np.where(classes > 0)[0] for index in indexes: cls = classes[index] start = int(4 * cls) end = start + 4 bbox_targets[index, start:end] = bbox_targets_data[index, 1:] bbox_weights[index, start:end] = config.TRAIN.BBOX_WEIGHTS return bbox_targets, bbox_weights def compute_mask_and_label(ex_rois, ex_labels, seg, flipped): # assert os.path.exists(seg_gt), 'Path does not exist: {}'.format(seg_gt) # im = Image.open(seg_gt) # pixel = list(im.getdata()) # pixel = np.array(pixel).reshape([im.size[1], im.size[0]]) im = Image.open(seg) pixel = list(im.getdata()) ins_seg = np.array(pixel).reshape([im.size[1], im.size[0]]) if flipped: ins_seg = ins_seg[:, ::-1] rois = ex_rois n_rois = ex_rois.shape[0] label = ex_labels class_id = config.CLASS_ID mask_target = np.zeros((n_rois, 28, 28), dtype=np.int8) mask_label = np.zeros((n_rois), dtype=np.int8) for n in range(n_rois): target = ins_seg[int(rois[n, 1]): int(rois[n, 3]), int(rois[n, 0]): int(rois[n, 2])] ids = np.unique(target) ins_id = 0 max_count = 0 for id in ids: if math.floor(id / 1000) == class_id[int(label[int(n)])]: px = np.where(ins_seg == int(id)) x_min = np.min(px[1]) y_min = np.min(px[0]) x_max = np.max(px[1]) y_max = np.max(px[0]) x1 = max(rois[n, 0], x_min) y1 = max(rois[n, 1], y_min) x2 = min(rois[n, 2], x_max) y2 = min(rois[n, 3], y_max) iou = (x2 - x1) * (y2 - y1) iou = iou / ((rois[n, 2] - rois[n, 0]) * (rois[n, 3] - rois[n, 1]) + (x_max - x_min) * (y_max - y_min) - iou) if iou > max_count: ins_id = id max_count = iou if max_count == 0: continue # print max_count mask = np.zeros(target.shape) idx = np.where(target == ins_id) mask[idx] = 1 mask = cv2.resize(mask, (28, 28), interpolation=cv2.INTER_NEAREST) mask_target[n] = mask mask_label[n] = label[int(n)] return mask_target, mask_label def compute_bbox_mask_targets_and_label(rois, overlaps, labels, seg, flipped): """ given rois, overlaps, gt labels, seg, compute bounding box mask targets :param rois: roidb[i]['boxes'] k * 4 :param overlaps: roidb[i]['max_overlaps'] k * 1 :param labels: roidb[i]['max_classes'] k * 1 :return: targets[i][class, dx, dy, dw, dh] k * 5 """ # Ensure ROIs are floats rois = rois.astype(np.float, copy=False) # Sanity check if len(rois) != len(overlaps): print 'bbox regression: this should not happen' # Indices of ground-truth ROIs gt_inds = np.where(overlaps == 1)[0] if len(gt_inds) == 0: print 'something wrong : zero ground truth rois' # Indices of examples for which we try to make predictions ex_inds = np.where(overlaps >= config.TRAIN.BBOX_REGRESSION_THRESH)[0] # Get IoU overlap between each ex ROI and gt ROI ex_gt_overlaps = bbox_overlaps(rois[ex_inds, :], rois[gt_inds, :]) # Find which gt ROI each ex ROI has max overlap with: # this will be the ex ROI's gt target gt_assignment = ex_gt_overlaps.argmax(axis=1) gt_rois = rois[gt_inds[gt_assignment], :] ex_rois = rois[ex_inds, :] mask_targets, mask_label = compute_mask_and_label(ex_rois, labels[ex_inds], seg, flipped) return mask_targets, mask_label, ex_inds def add_mask_targets(roidb): """ given roidb, add ['bbox_targets'] and normalize bounding box regression targets :param roidb: roidb to be processed. must have gone through imdb.prepare_roidb :return: means, std variances of targets """ print 'add bounding box mask targets' assert len(roidb) > 0 assert 'max_classes' in roidb[0] num_images = len(roidb) # Multi threads processing im_quene = Queue.Queue(maxsize=0) for im_i in range(num_images): im_quene.put(im_i) def process(): while not im_quene.empty(): im_i = im_quene.get() print "-----process img {}".format(im_i) rois = roidb[im_i]['boxes'] max_overlaps = roidb[im_i]['max_overlaps'] max_classes = roidb[im_i]['max_classes'] ins_seg = roidb[im_i]['ins_seg'] flipped = roidb[im_i]['flipped'] roidb[im_i]['mask_targets'], roidb[im_i]['mask_labels'], roidb[im_i]['mask_inds'] = \ compute_bbox_mask_targets_and_label(rois, max_overlaps, max_classes, ins_seg, flipped) threads = [threading.Thread(target=process, args=()) for i in range(10)] for t in threads: t.start() for t in threads: t.join() # Single thread # for im_i in range(num_images): # print "-----processing img {}".format(im_i) # rois = roidb[im_i]['boxes'] # max_overlaps = roidb[im_i]['max_overlaps'] # max_classes = roidb[im_i]['max_classes'] # ins_seg = roidb[im_i]['ins_seg'] # # roidb[im_i]['mask_targets'] = compute_bbox_mask_targets(rois, max_overlaps, max_classes, ins_seg) # roidb[im_i]['mask_targets'], roidb[im_i]['mask_labels'], roidb[im_i]['mask_inds'] = \ # compute_bbox_mask_targets_and_label(rois, max_overlaps, max_classes, ins_seg)
welcome.py
import tkinter as tk import menu from utils import _getFont, colors from ui import create_rounded_rectangle from threading import Thread from time import sleep class Welcome(tk.Canvas): def __init__(self, root): tk.Canvas.__init__(self, root, width=700, height=600, bd=0, highlightthickness=0, bg=colors.DBLUE) self.root = root self.time = 0 Thread(target=self.updateTimeout).start() self._loadView() def updateTimeout(self): while self.time < 4: sleep(1) self.time += 1 self.root.changeScreen(menu.GetIp) def _loadView(self): players = tk.PhotoImage(file='assets/elements/howtoplay.png') self.players = players.zoom(3).subsample(5) self.create_image(500, 210, image=self.players) self.create_text( 500, 350, text='Spaceteam is a cooperative game played with 3-4 people in the', fill=colors.GREEN, font=_getFont('body2') ) self.create_text( 500, 375, text='same network. Each player needs his/her device connected.', fill=colors.GREEN, font=_getFont('body2') ) create_rounded_rectangle(self, 175, 320, 825, 400, r=10, fill='', outline=colors.GREEN)
human_ros.py
#!/usr/bin/env python3 from enum import IntEnum import time import rospy from threading import Thread from dorna_enums import HumanResponse, DornaMovement from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint from moveit_msgs.msg import RobotState, RobotTrajectory, DisplayTrajectory, CollisionObject from dorna_api.msg import DornaPos, DornaJoint, DornaLimits, DornaHomed, DornaToolHead, DornaSpeed, DornaJerk from pix_2_world.msg import ButtonsPix, ButtonsWorld, Pix, World from std_msgs.msg import Float64, Int32, Bool, Header, String, Empty from dorna_api.srv import DornaConnect, DornaDisconnect, DornaHome, DornaSet, DornaPlay, DornaPause from dorna_api.srv import DornaHalt, DornaCalibrate, DornaJog, DornaErase, DornaView from dorna_api.srv import DornaPlanCmd, DornaXYZ, DornaXYZCheck, DornaXYZtoJoint, TfTransform from dorna_api.srv import DornaMoveJoints, DornaMoveXYZ, DornaOutputPin from pix_2_world.srv import Pix2World, NNService class HumanRos: def __init__(self): self._ns = 'dorna_real' self._joint_names = ['j0', 'j1', 'j2', 'j3', 'j4'] self._axis_names = ['x', 'y', 'z', 'a', 'b'] self.trajectory = None self._button_data = None self.connection_status = False ############################################## #### Human Service Proxies ##### ############################################## robot_srv_topics = ['connect', 'disconnect', 'home', 'set_joint', 'play', 'pause', 'halt', 'calibrate', 'jog', 'xyz_check', 'xyz_to_joint', 'move_joints', 'move_xyzab', 'digital_out'] robot_srv_msg_types = [DornaConnect, DornaDisconnect, DornaHome, DornaSet, DornaPlay, DornaPause, DornaHalt, DornaCalibrate, DornaJog, DornaXYZCheck, DornaXYZtoJoint, DornaMoveJoints, DornaMoveXYZ, DornaOutputPin] self._srv_prx_list = {} for topic, msg_type in zip(robot_srv_topics, robot_srv_msg_types): name_space = self._ns+'/robot_cmd/'+topic # rospy.wait_for_service(name_space) self._srv_prx_list[topic] = rospy.ServiceProxy(name_space, msg_type) moveit_srv_topics = ['view','move_home', 'move_extend', 'move_heart', 'move_rand', 'move_button', 'move_straight'] moveit_srv_msg_types = [DornaView, DornaPlanCmd, DornaPlanCmd, DornaPlanCmd, DornaPlanCmd, DornaXYZ, DornaPlanCmd] for topic, msg_type in zip(moveit_srv_topics, moveit_srv_msg_types): name_space = self._ns+'/moveit_cmd/'+topic # rospy.wait_for_service(name_space) self._srv_prx_list[topic] = rospy.ServiceProxy(name_space, msg_type) # rospy.wait_for_service('pix_2_world') self._srv_prx_list['pix_2_world'] = rospy.ServiceProxy('pix_2_world', Pix2World) self._srv_prx_list['tf_transform'] = rospy.ServiceProxy('get_tf_transform', TfTransform) ############################################## #### Human Subscribers ##### ############################################## self._sub_topics = ['cartesian_position', 'joint_angles'] pub_msg_types = [DornaPos, DornaJoint] self._subscriber_list = {} for topic, msg_type in zip(self._sub_topics, pub_msg_types): callback = getattr(self, topic+"_callback", None) self._subscriber_list[topic] = rospy.Subscriber(self._ns+'/robot_info/'+topic, msg_type, callback) callback = getattr(self, "sent_pic_callback", None) self._subscriber_list['sent_pic'] = rospy.Subscriber('/realsense/info/sent_pic', Empty, callback) callback = getattr(self, "buttons_world_callback", None) self._subscriber_list['buttons_world'] = rospy.Subscriber('buttons_world', ButtonsWorld, callback) # self._package_subscriber = rospy.Subscriber('/tag_detections', AprilTagDetectionArray, self.package_callback) ############################################## #### Human Publishers ##### ############################################## self._take_pic_pub = rospy.Publisher('/realsense/cmd/take_pic', Empty, queue_size=10) def init(self): self.connect() if self.connection_status: self.home() self.calibrate() try: response = input("Move to Home Pose enter 1: ") if response == '1': self.home_pose() else: pass except rospy.ROSException: pass else: self.init() def connect(self): rospy.wait_for_service('/dorna_real/robot_cmd/connect') response = input("Press Enter to Connect to Robot: ") if response == '': usb = "/dev/ttyACM0" response = self._srv_prx_list['connect'](usb) rospy.loginfo(response) if not response.connected: rospy.logerr('Error [Human_Ros]: Did not get proper response when connecting to robot') self.connection_status = response.connected else: self.connection_status = False def home(self): response = input("NOTE: Please check robot surroundings before homing!\n\rTo home the robot motors input 1, else the robot will set the motors to the home position\n\r\n\rHere: ") if response == "1": srv_response = self._srv_prx_list['home']() else: srv_response = self._srv_prx_list['set_joint']() if srv_response.homed: return else: rospy.logerr('Error [Human_Ros]: Did not get proper response when homing to robot') def calibrate(self): response = input("Do you want to calibrate the motors? Default in NO, Enter y to override\n\rHere: ") if response == 'y': for i in range(len(self._joint_names)): jog_response = input("Do you want to jog joint{}? y/n ".format(i)) if jog_response == 'n': pass elif jog_response == 'y' or jog_response == '': self.jog_motor(i) # response = self._srv_prx_list['calibrate']() else: pass def home_pose(self): self.service_check('/dorna_real/robot_cmd/move_joints') response = self._srv_prx_list['move_joints']("joint", DornaMovement.GLOBAL.value, DornaMovement.DEFAULT_JOINT_SPEED.value, [0, 145, -90, 0, 0]) if response.response: rospy.loginfo("Arrived at home location") else: rospy.logwarn("Did not get good response") # trajectory = response.trajectory.joint_trajectory # print(trajectory) # response = self._srv_prx_list['play'](trajectory) def tuck_away(self): self.service_check('/dorna_real/robot_cmd/move_joints') response = self._srv_prx_list['move_joints']('joint', DornaMovement.GLOBAL.value, DornaMovement.DEFAULT_XYZ_SPEED.value, [-90., 170., 0., 0., 0.]) if response.response: rospy.loginfo("Arrived at tuck_away location") else: rospy.logwarn("Did not get good response") def move_forward_test(self): self.service_check('/dorna_real/robot_cmd/move_xyzab') ## TODO:Fix this function speed = int(DornaMovement.DEFAULT_XYZ_SPEED.value/2) response = self._srv_prx_list['move_xyzab']("line", DornaMovement.RELATIVE.value, speed, [30, 0, 0, 0, 0]) if response.response: rospy.loginfo("Arrived at desired location") else: rospy.logwarn("Did not get good response") def move_xyz_test(self): self.service_check('/dorna_real/robot_cmd/move_xyzab') response = self._srv_prx_list['move_xyzab']("line", DornaMovement.GLOBAL.value, DornaMovement.DEFAULT_XYZ_SPEED.value, [300, 0, 500, 0, 0]) if response.response: rospy.loginfo("Arrived at tuck_away location") else: rospy.logwarn("Did not get good response") ####################################### #### Button Commands #### ####################################### def get_button_dict(self, response): availible_buttons = [] for i in range(len(response.msg)): availible_buttons.append("BUTTON_{}".format(response.msg[i].id)) # availible_buttons[response[i].id] = self.find_transform("dorna_base", child_frame) return availible_buttons def show_availible_buttons(self, availible_buttons): rospy.loginfo("These are the buttons we can see: ") for button in availible_buttons: rospy.loginfo(button) def button_input(self, availible_buttons): self.show_availible_buttons(availible_buttons) button_id = input("Which button do you want to move to?\n\rEnter Here: ") try: if button_id in availible_buttons: if self.can_reach_button(button_id): return button_id else: rospy.logerr("Robot cant reach that button safely") self.button_input(availible_buttons) else: rospy.logerr("[Error]: Response was not found in availible buttons. Try again.") self.button_input(availible_buttons) except KeyboardInterrupt: raise def get_xyz(self, button_id): child_frame = button_id parent_frame = 'dorna_base' self.service_check('get_tf_transform') xyz_transform_meters = self._srv_prx_list['tf_transform']([child_frame, parent_frame]) xyz_transform_mm = [] for val in xyz_transform_meters.transform: xyz_transform_mm.append(val*1000.) # xyz_transform_mm = [300, 0, 360] return xyz_transform_mm def can_reach_button(self, button_id): xyz = self.get_xyz(button_id) print(xyz) response = self._srv_prx_list['xyz_check'](xyz) print(response.can_reach) if response.can_reach: rospy.loginfo("Can reach button location") return True else: rospy.logerr("Cannot reach button location") return False def pick_button(self, response): availible_buttons = self.get_button_dict(response) button_id = self.button_input(availible_buttons) xyz = self.get_xyz(button_id) return xyz def xyz_to_joint(self, xyz, x_offset = None): if x_offset: xyz[0] -= x_offset response = self._srv_prx_list['xyz_to_joint'](xyz) return response.joint_angles ####################################### #### Jog Commands #### ####################################### def jog_cmd(self, axis, axis_value, step_size, max_step, min_step, units): rospy.loginfo("Axis {} current value [{}]: {}".format(axis, units, axis_value)) rospy.loginfo("Current jog step size is {} [{}]".format(step_size, units)) command = input("Enter w to jog up\n\rEnter s to jog down\n\rEnter e to change step size\n\rEnter y when ok\n\rHere: ") if command == 'w': response = self._srv_prx_list['jog']("joint", axis, step_size) return True elif command == 's': response = self._srv_prx_list['jog']("joint", axis, -step_size) return True elif command == 'e': step_size = int(input("Enter value for step size in {} (Max is {}, Min is {}): ".format(units, max_step, min_step))) step_size = min(max(step_size, min_step), max_step) self.jog_cmd(axis, axis_value, step_size, max_step, min_step, units) elif command == 'y': return False else: rospy.logerr('Invalid Entry') pass return True def jog_axis(self, axis): not_ok = True units = rospy.get_param('/dorna_real/units') index = self._axis_names.index(axis) while not_ok: axis_value = self.robot_xyz_pos[index] if axis == "a" or axis == "b": step_size = 5 not_ok = self.jog_cmd(axis, axis_value, step_size, 10, 1, "degrees") elif units == "mm": step_size = 25 not_ok = self.jog_cmd(axis, axis_value, step_size, 50, 10, "millimeters") elif units == "inch": step_size = 1 not_ok = self.jog_cmd(axis, axis_value, step_size, 2, 0.4, "inches") def jog_motor(self, motor): not_ok = True step_size = 5 # [deg] name = self._joint_names[motor] while not_ok: joint_value = self.robot_joint_angles[motor] not_ok = self.jog_cmd(name, joint_value, step_size, 10, 1, "degrees") def jog_input(self): jogging = True while jogging: mode = int(input("To move each motor enter 0\n\rTo move end effector enter 1\n\rOr 2 to quit\n\rHere: ")) if mode == 1: axis = input("Enter Axis [x, y, z, pitch, roll] or q to quit jogging: ") if axis not in self._axis_names and axis != "q": rospy.logerr("Invalid Entry") pass elif axis == "q": jogging = False else: self.jog_axis(axis) elif mode == 0: motor = input("Enter Motor number (0-4) or q to quit jogging: ") if motor not in ['0','1','2','3','4','q']: rospy.logerr("Invalid Entry") pass elif motor == 'q': jogging = False else: self.jog_motor(int(motor)) else: jogging = False ########################################### #### Robot Info Callback #### ########################################### def cartesian_position_callback(self, pos): self.robot_xyz_pos = [pos.x, pos.y, pos.z, pos.a, pos.b] def joint_angles_callback(self, joints): self.robot_joint_angles = [joints.j0, joints.j1, joints.j2, joints.j3, joints.j4] ########################################### #### Thread #### ########################################### def service_check(self, name): try: rospy.wait_for_service(name, timeout=5.0) except rospy.ROSException: rospy.logerr('{} service is not responding'.format(name)) self.run() def run(self): try: while not rospy.is_shutdown(): if self.trajectory is not None: play = input("Press s to view path again in Rvis\n\rPress p to play current trajectory\n\r Press e to erase current trajectory\n\r Here: ") if play == 'p': response = self._srv_prx_list['play'](self.trajectory) elif play == 'e': self.trajectory = None elif play == 's': response = self._srv_prx_list['view']() else: rospy.logerr("You did not pick one of the options try again.") pass elif self._button_data is not None: button_xyz = self.pick_button(self._button_data) #Returns selected button xyz in robot frame (only returns if robot can reach) joint_angles = self.xyz_to_joint(button_xyz, x_offset=30.0) #Returns joint_angles at end position with 10 mm offset # name = 'move_button' # self.service_check(self._ns+'/moveit_cmd/'+name) # response = self._srv_prx_list[name](list(joint_angles)) #Returns trajectory for button press # self.trajectory = response.trajectory.joint_trajectory # rospy.loginfo("Sending trajectory to Robot") # response = self._srv_prx_list['play'](self.trajectory) self.service_check('/dorna_real/robot_cmd/move_joints') response = self._srv_prx_list['move_joints']('joint', DornaMovement.GLOBAL.value, DornaMovement.DEFAULT_XYZ_SPEED.value, list(joint_angles)) if response.response: rospy.loginfo("Arrived at button location") else: rospy.logwarn("Did not get good response") response = input("Does robot hand seem to be aligned correctly? ") if response == '' or response == 'y': self.move_forward_test() else: rospy.logerr("Hand does not seem to be aligned correctly.") response = input("Would you like to jog the robot into the correct place? ") if response == '' or response == 'y': self.jog_input() response = input("Would you like to return robot to home position? ") if response == '' or response == 'y': self.home_pose() response = input("Was demo successful, ready to quit and disconnect? ") if response == '' or response == 'y': self.home_pose() rospy.loginfo("CONGRATS") elif response == 'n': self.button_demo() else: path = input("[Note] These are commands for Moveit Node make sure dorna_real_moveit.py has started.\n\rEnter h to move to Home position\n\rEnter e to move to Extended position\n\rEnter d to draw heart\n\rEnter r to move to random valid position\n\rEnter s to move in a straight line\n\rEnter b for buttons \n\rEnter j to jog joints\n\rEnter q to quit\n\rHere: ") if path == "h": name = "move_home" self.service_check(self._ns+'/moveit_cmd/'+name) response = self._srv_prx_list[name]() self.trajectory = response.trajectory.joint_trajectory elif path == "e": name = 'move_extend' self.service_check(self._ns+'/moveit_cmd/'+name) response = self._srv_prx_list[name]() self.trajectory = response.trajectory.joint_trajectory elif path == "d": name = 'move_heart' self.service_check(self._ns+'/moveit_cmd/'+name) response = self._srv_prx_list[name]() self.trajectory = response.trajectory.joint_trajectory elif path == "r": name = 'move_rand' self.service_check(self._ns+'/moveit_cmd/'+name) response = self._srv_prx_list[name]() self.trajectory = response.trajectory.joint_trajectory elif path == "b": self.button_demo() elif path == 'j': self.jog_input() elif path == 't': self.tuck_away() elif path == 'f': self.move_forward_test() elif path == 'x': self.move_xyz_test() elif path == 'p': self.pick_and_place(300, 0, -250, 0) elif path == 'q': rospy.loginfo("Quiting Program") if self.connection_status: response = self._srv_prx_list['quit']() rospy.signal_shutdown('Quit') except KeyboardInterrupt: pass def sent_pic_callback(self, data): rospy.loginfo("Picture was sent to nn.") self.home_pose() def buttons_world_callback(self, data): self._button_data = data def button_demo(self): self.tuck_away() time.sleep(5) ##TODO: Fix this to be dependant on robot state # name = 'pix_2_world' # self.service_check(name) # response = self._srv_prx_list[name]() #Starts button demo response is dictionary of buttons and xyz in camera frame self._take_pic_pub.publish(Empty()) rospy.loginfo("Take_picture was requested.") # self.home_pose() def pick_and_place(self, xi, yi, xf, yf): tool_head = 0 package_height = 150 safety = 50 above = package_height+tool_head+safety child_frame = 'tag_2' parent_frame = 'dorna_base' pin = 2 response = self._srv_prx_list['digital_out'](pin, False) response = self._srv_prx_list['move_xyzab']("joint", DornaMovement.GLOBAL.value, DornaMovement.DEFAULT_XYZ_SPEED.value, [xi,yi, 300, -90, 0]) time.sleep(2) response = self._srv_prx_list['tf_transform']([child_frame, parent_frame]) location = response.transform x = location[0]*1000. y = location[1]*1000. z = round(location[2]*1000., 1) response = self._srv_prx_list['move_xyzab']("joint", DornaMovement.GLOBAL.value, DornaMovement.DEFAULT_XYZ_SPEED.value, [x+30, y, safety, -90, 0]) response = self._srv_prx_list['digital_out'](pin, True) response = self._srv_prx_list['move_xyzab']("line", DornaMovement.RELATIVE.value, DornaMovement.DEFAULT_XYZ_SPEED.value, [0, 0, -60, 0, 0]) response = self._srv_prx_list['move_xyzab']("line", DornaMovement.RELATIVE.value, DornaMovement.DEFAULT_XYZ_SPEED.value, [0,0, 100, 0, 0]) response = self._srv_prx_list['move_xyzab']("joint", DornaMovement.GLOBAL.value, DornaMovement.DEFAULT_XYZ_SPEED.value, [0, -300, 100, -90, 0]) response = self._srv_prx_list['move_xyzab']("joint", DornaMovement.RELATIVE.value, DornaMovement.DEFAULT_XYZ_SPEED.value, [xf, 300, 0, 0, 0]) response = self._srv_prx_list['move_xyzab']("line", DornaMovement.RELATIVE.value, DornaMovement.DEFAULT_XYZ_SPEED.value, [0, 0, -100, 0, 0]) response = self._srv_prx_list['digital_out'](pin, False) time.sleep(2) response = self._srv_prx_list['move_xyzab']("line", DornaMovement.RELATIVE.value, DornaMovement.DEFAULT_XYZ_SPEED.value, [0, 0, safety, 0, 0]) response = self.home_pose() if __name__=="__main__": rospy.init_node('human_ros') rospy.loginfo('Starting node "human_ros"') human = HumanRos() try: human.init() except (rospy.service.ServiceException, KeyboardInterrupt): rospy.logerr('Check if the robot node has started') raise try: runner = Thread(target=human.run) runner.start() rospy.spin() runner.join() except (rospy.ROSInterruptException, KeyboardInterrupt): raise # finally: # human.quit
threading.py
# Copyright (C) 2015-2021 Regents of the University of California # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # 5.14.2018: copied into Toil from https://github.com/BD2KGenomics/bd2k-python-lib # Note: renamed from "threading.py" to "threading.py" to avoid conflicting imports # from the built-in "threading" from psutil in python3.9 import atexit import fcntl import logging import math import os import sys import tempfile import threading import traceback from contextlib import contextmanager from typing import Any, Dict, Iterator, Optional import psutil # type: ignore from toil.lib.exceptions import raise_ from toil.lib.io import robust_rmtree logger = logging.getLogger(__name__) class ExceptionalThread(threading.Thread): """ A thread whose join() method re-raises exceptions raised during run(). While join() is idempotent, the exception is only during the first invocation of join() that successfully joined the thread. If join() times out, no exception will be re reraised even though an exception might already have occured in run(). When subclassing this thread, override tryRun() instead of run(). >>> def f(): ... assert 0 >>> t = ExceptionalThread(target=f) >>> t.start() >>> t.join() Traceback (most recent call last): ... AssertionError >>> class MyThread(ExceptionalThread): ... def tryRun( self ): ... assert 0 >>> t = MyThread() >>> t.start() >>> t.join() Traceback (most recent call last): ... AssertionError """ exc_info = None def run(self) -> None: try: self.tryRun() except: self.exc_info = sys.exc_info() raise def tryRun(self) -> None: super().run() def join(self, *args: Optional[float], **kwargs: Optional[float]) -> None: super().join(*args, **kwargs) if not self.is_alive() and self.exc_info is not None: exc_type, exc_value, traceback = self.exc_info self.exc_info = None raise_(exc_type, exc_value, traceback) def cpu_count() -> Any: """ Get the rounded-up integer number of whole CPUs available. Counts hyperthreads as CPUs. Uses the system's actual CPU count, or the current v1 cgroup's quota per period, if the quota is set. Ignores the cgroup's cpu shares value, because it's extremely difficult to interpret. See https://github.com/kubernetes/kubernetes/issues/81021. Caches result for efficiency. :return: Integer count of available CPUs, minimum 1. :rtype: int """ cached = getattr(cpu_count, 'result', None) if cached is not None: # We already got a CPU count. return cached # Get the fallback answer of all the CPUs on the machine total_machine_size = psutil.cpu_count(logical=True) logger.debug('Total machine size: %d cores', total_machine_size) try: with open('/sys/fs/cgroup/cpu/cpu.cfs_quota_us') as stream: # Read the quota quota = int(stream.read()) logger.debug('CPU quota: %d', quota) if quota == -1: # Assume we can use the whole machine return total_machine_size with open('/sys/fs/cgroup/cpu/cpu.cfs_period_us') as stream: # Read the period in which we are allowed to burn the quota period = int(stream.read()) logger.debug('CPU quota period: %d', period) # The thread count is how many multiples of a wall clcok period we can burn in that period. cgroup_size = int(math.ceil(float(quota)/float(period))) logger.debug('Cgroup size in cores: %d', cgroup_size) except: # We can't actually read these cgroup fields. Maybe we are a mac or something. logger.debug('Could not inspect cgroup: %s', traceback.format_exc()) cgroup_size = float('inf') # type: ignore # Return the smaller of the actual thread count and the cgroup's limit, minimum 1. result = max(1, min(cgroup_size, total_machine_size)) logger.debug('cpu_count: %s', str(result)) # Make sure to remember it for the next call setattr(cpu_count, 'result', result) return result # PIDs are a bad identifier, because they are not shared between containers # and also may be reused. # So instead we have another system for file store implementations to # coordinate among themselves, based on file locks. # TODO: deduplicate with DeferredFunctionManager? # TODO: Wrap in a class as static methods? # Note that we don't offer a way to enumerate these names. You can only get # your name and poll others' names (or your own). So we don't have # distinguishing prefixes or WIP suffixes to allow for enumeration. # We keep one name per unique Toil workDir (i.e. /tmp or whatever existing # directory Toil tries to put its workflow directory under.) # We have a global lock to control looking things up current_process_name_lock = threading.Lock() # And a global dict from work directory to name in that work directory. # We also have a file descriptor per work directory but it is just leaked. current_process_name_for: Dict[str, str] = {} def collect_process_name_garbage() -> None: """ Delete all the process names that point to files that don't exist anymore (because the work directory was temporary and got cleaned up). This is known to happen during the tests, which get their own temp directories. Caller must hold current_process_name_lock. """ global current_process_name_for # Collect the workDirs of the missing names to delete them after iterating. missing = [] for workDir, name in current_process_name_for.items(): if not os.path.exists(os.path.join(workDir, name)): # The name file is gone, probably because the work dir is gone. missing.append(workDir) for workDir in missing: del current_process_name_for[workDir] def destroy_all_process_names() -> None: """ Delete all our process name files because our process is going away. We let all our FDs get closed by the process death. We assume there is nobody else using the system during exit to race with. """ global current_process_name_for for workDir, name in current_process_name_for.items(): robust_rmtree(os.path.join(workDir, name)) # Run the cleanup at exit atexit.register(destroy_all_process_names) def get_process_name(workDir: str) -> str: """ Return the name of the current process. Like a PID but visible between containers on what to Toil appears to be a node. :param str workDir: The Toil work directory. Defines the shared namespace. :return: Process's assigned name :rtype: str """ global current_process_name_lock global current_process_name_for with current_process_name_lock: # Make sure all the names still exist. # TODO: a bit O(n^2) in the number of workDirs in flight at any one time. collect_process_name_garbage() if workDir in current_process_name_for: # If we already gave ourselves a name, return that. return current_process_name_for[workDir] # We need to get a name file. nameFD, nameFileName = tempfile.mkstemp(dir=workDir) # Lock the file. The lock will automatically go away if our process does. try: fcntl.lockf(nameFD, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError as e: # Someone else might have locked it even though they should not have. raise RuntimeError("Could not lock process name file {}: {}".format(nameFileName, str(e))) # Save the basename current_process_name_for[workDir] = os.path.basename(nameFileName) # Return the basename return current_process_name_for[workDir] # TODO: we leave the file open forever. We might need that in order for # it to stay locked while we are alive. def process_name_exists(workDir: str, name: str) -> bool: """ Return true if the process named by the given name (from process_name) exists, and false otherwise. Can see across container boundaries using the given node workflow directory. :param str workDir: The Toil work directory. Defines the shared namespace. :param str name: Process's name to poll :return: True if the named process is still alive, and False otherwise. :rtype: bool """ global current_process_name_lock global current_process_name_for with current_process_name_lock: if current_process_name_for.get(workDir, None) == name: # We are asking about ourselves. We are alive. return True # Work out what the corresponding file name is nameFileName = os.path.join(workDir, name) if not os.path.exists(nameFileName): # If the file is gone, the process can't exist. return False nameFD = None try: # Otherwise see if we can lock it shared, for which we need an FD, but # only for reading. nameFD = os.open(nameFileName, os.O_RDONLY) try: fcntl.lockf(nameFD, fcntl.LOCK_SH | fcntl.LOCK_NB) except OSError as e: # Could not lock. Process is alive. return True else: # Could lock. Process is dead. # Remove the file. We race to be the first to do so. try: os.remove(nameFileName) except: pass # Unlock fcntl.lockf(nameFD, fcntl.LOCK_UN) # Report process death return False finally: if nameFD is not None: try: os.close(nameFD) except: pass # Similar to the process naming system above, we define a global mutex system # for critical sections, based just around file locks. @contextmanager def global_mutex(workDir: str, mutex: str) -> Iterator[None]: """ Context manager that locks a mutex. The mutex is identified by the given name, and scoped to the given directory. Works across all containers that have access to the given diectory. Mutexes held by dead processes are automatically released. Only works between processes, NOT between threads. :param str workDir: The Toil work directory. Defines the shared namespace. :param str mutex: Mutex to lock. Must be a permissible path component. """ # Define a filename lock_filename = os.path.join(workDir, 'toil-mutex-' + mutex) logger.debug('PID %d acquiring mutex %s', os.getpid(), lock_filename) # We can't just create/open and lock a file, because when we clean up # there's a race where someone can open the file before we unlink it and # get a lock on the deleted file. while True: # Try to create the file, ignoring if it exists or not. fd = os.open(lock_filename, os.O_CREAT | os.O_WRONLY) # Wait until we can exclusively lock it. fcntl.lockf(fd, fcntl.LOCK_EX) # Holding the lock, make sure we are looking at the same file on disk still. fd_stats = os.fstat(fd) try: path_stats = os.stat(lock_filename) except FileNotFoundError: path_stats = None if path_stats is None or fd_stats.st_dev != path_stats.st_dev or fd_stats.st_ino != path_stats.st_ino: # The file we have a lock on is not the file linked to the name (if # any). This usually happens, because before someone releases a # lock, they delete the file. Go back and contend again. TODO: This # allows a lot of queue jumping on our mutex. fcntl.lockf(fd, fcntl.LOCK_UN) os.close(fd) continue else: # We have a lock on the file that the name points to. Since we # hold the lock, nobody will be deleting it or can be in the # process of deleting it. Stop contending; we have the mutex. break try: # When we have it, do the thing we are protecting. logger.debug('PID %d now holds mutex %s', os.getpid(), lock_filename) yield finally: # Delete it while we still own it, so we can't delete it from out from # under someone else who thinks they are holding it. logger.debug('PID %d releasing mutex %s', os.getpid(), lock_filename) os.unlink(lock_filename) fcntl.lockf(fd, fcntl.LOCK_UN) # Note that we are unlinking it and then unlocking it; a lot of people # might have opened it before we unlinked it and will wake up when they # get the worthless lock on the now-unlinked file. We have to do some # stat gymnastics above to work around this. os.close(fd) class LastProcessStandingArena: """ Class that lets a bunch of processes detect and elect a last process standing. Process enter and leave (sometimes due to sudden existence failure). We guarantee that the last process to leave, if it leaves properly, will get a chance to do some cleanup. If new processes try to enter during the cleanup, they will be delayed until after the cleanup has happened and the previous "last" process has finished leaving. The user is responsible for making sure you always leave if you enter! Consider using a try/finally; this class is not a context manager. """ def __init__(self, workDir: str, name: str) -> None: """ Connect to the arena specified by the given workDir and name. Any process that can access workDir, in any container, can connect to the arena. Many arenas can be active with different names. Doesn't enter or leave the arena. :param str workDir: The Toil work directory. Defines the shared namespace. :param str name: Name of the arena. Must be a permissible path component. """ # Save the workDir which namespaces everything self.workDir = workDir # We need a mutex name to allow only one process to be entering or # leaving at a time. self.mutex = name + '-arena-lock' # We need a way to track who is actually in, and who was in but died. # So everybody gets a locked file (again). # TODO: deduplicate with the similar logic for process names, and also # deferred functions. self.lockfileDir = os.path.join(workDir, name + '-arena-members') # When we enter the arena, we fill this in with the FD of the locked # file that represents our presence. self.lockfileFD = None # And we fill this in with the file name self.lockfileName = None def enter(self) -> None: """ This process is entering the arena. If cleanup is in progress, blocks until it is finished. You may not enter the arena again before leaving it. """ logger.debug('Joining arena %s', self.lockfileDir) # Make sure we're not in it already. assert self.lockfileName is None assert self.lockfileFD is None with global_mutex(self.workDir, self.mutex): # Now nobody else should also be trying to join or leave. try: # Make sure the lockfile directory exists. os.mkdir(self.lockfileDir) except FileExistsError: pass # Make ourselves a file in it and lock it to prove we are alive. self.lockfileFD, self.lockfileName = tempfile.mkstemp(dir=self.lockfileDir) # type: ignore # Nobody can see it yet, so lock it right away fcntl.lockf(self.lockfileFD, fcntl.LOCK_EX) # type: ignore # Now we're properly in, so release the global mutex logger.debug('Now in arena %s', self.lockfileDir) def leave(self) -> Iterator[bool]: """ This process is leaving the arena. If this process happens to be the last process standing, yields something, with other processes blocked from joining the arena until the loop body completes and the process has finished leaving. Otherwise, does not yield anything. Should be used in a loop: for _ in arena.leave(): # If we get here, we were the last process. Do the cleanup pass """ # Make sure we're in it to start. assert self.lockfileName is not None assert self.lockfileFD is not None logger.debug('Leaving arena %s', self.lockfileDir) with global_mutex(self.workDir, self.mutex): # Now nobody else should also be trying to join or leave. # Take ourselves out. try: os.unlink(self.lockfileName) except: pass self.lockfileName = None fcntl.lockf(self.lockfileFD, fcntl.LOCK_UN) os.close(self.lockfileFD) self.lockfileFD = None for item in os.listdir(self.lockfileDir): # There is someone claiming to be here. Are they alive? full_path = os.path.join(self.lockfileDir, item) fd = os.open(full_path, os.O_RDONLY) try: fcntl.lockf(fd, fcntl.LOCK_SH | fcntl.LOCK_NB) except OSError as e: # Could not lock. It's alive! break else: # Could lock. Process is dead. try: os.remove(full_path) except: pass fcntl.lockf(fd, fcntl.LOCK_UN) # Continue with the loop normally. else: # Nothing alive was found. Nobody will come in while we hold # the global mutex, so we are the Last Process Standing. logger.debug('We are the Last Process Standing in arena %s', self.lockfileDir) yield True try: # Delete the arena directory so as to leave nothing behind. os.rmdir(self.lockfileDir) except: logger.warning('Could not clean up arena %s completely: %s', self.lockfileDir, traceback.format_exc()) # Now we're done, whether we were the last one or not, and can # release the mutex. logger.debug('Now out of arena %s', self.lockfileDir)
monitor.py
# -*- coding: utf-8 -*- # File: monitor.py import json import numpy as np import operator import os import re import shutil import time from collections import defaultdict from datetime import datetime import six import threading from ..compat import tfv1 as tf from ..libinfo import __git_version__ from ..tfutils.summary import create_image_summary, create_scalar_summary from ..utils import fs, logger from ..utils.develop import HIDE_DOC from .base import Callback __all__ = ['MonitorBase', 'Monitors', 'TFEventWriter', 'JSONWriter', 'ScalarPrinter', 'SendMonitorData', 'CometMLMonitor'] def image_to_nhwc(arr): if arr.ndim == 4: pass elif arr.ndim == 3: if arr.shape[-1] in [1, 3, 4]: arr = arr[np.newaxis, :] else: arr = arr[:, :, :, np.newaxis] elif arr.ndim == 2: arr = arr[np.newaxis, :, :, np.newaxis] else: raise ValueError("Array of shape {} is not an image!".format(arr.shape)) return arr class MonitorBase(Callback): """ Base class for monitors which monitor a training progress, by processing different types of summary/statistics from trainer. .. document private functions .. automethod:: _setup_graph """ _chief_only = False def setup_graph(self, trainer): # Set attributes following Callback.setup_graph self.trainer = trainer self.graph = tf.get_default_graph() self._setup_graph() def _setup_graph(self): """ Override this method to setup the monitor.""" pass def process_summary(self, summary): """ Process a tf.Summary. """ pass def process(self, name, val): """ Process a key-value pair. """ pass def process_scalar(self, name, val): """ Args: val: a scalar """ pass def process_image(self, name, val): """ Args: val (np.ndarray): 4D (NHWC) numpy array of images in range [0,255]. If channel is 3, assumed to be RGB. """ pass def process_event(self, evt): """ Args: evt (tf.Event): the most basic format acceptable by tensorboard. It could include Summary, RunMetadata, LogMessage, and more. """ pass # TODO process other types class NoOpMonitor(MonitorBase): def __init__(self, name=None): self._name = name def __str__(self): if self._name is None: return "NoOpMonitor" return "NoOpMonitor({})".format(self._name) class Monitors(Callback): """ Merge monitors together for trainer to use. In training, each trainer will create a :class:`Monitors` instance, and you can access it through ``trainer.monitors``. You should use ``trainer.monitors`` for logging and it will dispatch your logs to each sub-monitor. """ _chief_only = False def __init__(self, monitors): self._scalar_history = ScalarHistory() self._monitors = monitors + [self._scalar_history] for m in self._monitors: assert isinstance(m, MonitorBase), m def _setup_graph(self): # scalar_history's other methods were not called. # but they are not useful for now self._scalar_history.setup_graph(self.trainer) def _dispatch(self, func): for m in self._monitors: func(m) def put_summary(self, summary): """ Put a `tf.Summary`. """ if isinstance(summary, six.binary_type): summary = tf.Summary.FromString(summary) assert isinstance(summary, tf.Summary), type(summary) # TODO other types for val in summary.value: if val.WhichOneof('value') == 'simple_value': val.tag = re.sub('tower[0-9]+/', '', val.tag) # TODO move to subclasses # TODO This hack is still needed, seem to disappear only when # compiled from source. suffix = '-summary' # tensorflow#6150, tensorboard#59 if val.tag.endswith(suffix): val.tag = val.tag[:-len(suffix)] self._dispatch(lambda m: m.process_scalar(val.tag, val.simple_value)) self._dispatch(lambda m: m.process_summary(summary)) def put_scalar(self, name, val): """ Put a scalar. """ if isinstance(val, np.floating): val = float(val) if isinstance(val, np.integer): val = int(val) self._dispatch(lambda m: m.process_scalar(name, val)) s = create_scalar_summary(name, val) self._dispatch(lambda m: m.process_summary(s)) def put_image(self, name, val): """ Put an image. Args: name (str): val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images in range [0,255]. If channel is 3, assumed to be RGB. """ assert isinstance(val, np.ndarray) arr = image_to_nhwc(val) self._dispatch(lambda m: m.process_image(name, arr)) s = create_image_summary(name, arr) self._dispatch(lambda m: m.process_summary(s)) def put_event(self, evt): """ Put an :class:`tf.Event`. `step` and `wall_time` fields of :class:`tf.Event` will be filled automatically. Args: evt (tf.Event): """ evt.step = self.global_step evt.wall_time = time.time() self._dispatch(lambda m: m.process_event(evt)) def get_latest(self, name): """ Get latest scalar value of some data. If you run multiprocess training, keep in mind that the data is perhaps only available on chief process. Returns: scalar """ return self._scalar_history.get_latest(name)[1] def get_history(self, name): """ Get a history of the scalar value of some data. If you run multiprocess training, keep in mind that the data is perhaps only available on chief process. Returns: a list of (global_step, value) pairs: history data for this scalar """ return self._scalar_history.get_history(name) class TFEventWriter(MonitorBase): """ Write summaries to TensorFlow event file. """ def __init__(self, logdir=None, max_queue=10, flush_secs=120, split_files=False): """ Args: logdir: ``logger.get_logger_dir()`` by default. max_queue, flush_secs: Same as in :class:`tf.summary.FileWriter`. split_files: if True, split events to multiple files rather than append to a single file. Useful on certain filesystems where append is expensive. """ if logdir is None: logdir = logger.get_logger_dir() assert tf.gfile.IsDirectory(logdir), logdir self._logdir = fs.normpath(logdir) self._max_queue = max_queue self._flush_secs = flush_secs self._split_files = split_files def __new__(cls, logdir=None, max_queue=10, flush_secs=120, **kwargs): if logdir is None: logdir = logger.get_logger_dir() if logdir is not None: return super(TFEventWriter, cls).__new__(cls) else: logger.warn("logger directory was not set. Ignore TFEventWriter.") return NoOpMonitor("TFEventWriter") def _setup_graph(self): self._writer = tf.summary.FileWriter( self._logdir, max_queue=self._max_queue, flush_secs=self._flush_secs) def _write_graph(self): self._writer.add_graph(self.graph) def _before_train(self): # Writing the graph is expensive (takes ~2min) when the graph is large. # Therefore use a separate thread. It will then run in the # background while TF is warming up in the first several iterations. self._write_graph_thread = threading.Thread(target=self._write_graph) self._write_graph_thread.daemon = True self._write_graph_thread.start() @HIDE_DOC def process_summary(self, summary): self._writer.add_summary(summary, self.global_step) @HIDE_DOC def process_event(self, evt): self._writer.add_event(evt) def _trigger(self): # flush every epoch self._writer.flush() if self._split_files: self._writer.close() self._writer.reopen() # open new file def _after_train(self): self._writer.close() class JSONWriter(MonitorBase): """ Write all scalar data to a json file under ``logger.get_logger_dir()``, grouped by their global step. If found an earlier json history file, will append to it. """ FILENAME = 'stats.json' """ The name of the json file. Do not change it. """ def __new__(cls): if logger.get_logger_dir(): return super(JSONWriter, cls).__new__(cls) else: logger.warn("logger directory was not set. Ignore JSONWriter.") return NoOpMonitor("JSONWriter") @staticmethod def load_existing_json(): """ Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json", and return the loaded list of statistics if found. Returns None otherwise. """ dir = logger.get_logger_dir() fname = os.path.join(dir, JSONWriter.FILENAME) if tf.gfile.Exists(fname): with open(fname) as f: stats = json.load(f) assert isinstance(stats, list), type(stats) return stats return None @staticmethod def load_existing_epoch_number(): """ Try to load the latest epoch number from an existing json stats file (if any). Returns None if not found. """ stats = JSONWriter.load_existing_json() try: return int(stats[-1]['epoch_num']) except Exception: return None # initialize the stats here, because before_train from other callbacks may use it def _setup_graph(self): self._stats = [] self._stat_now = {} self._last_gs = -1 def _before_train(self): stats = JSONWriter.load_existing_json() self._fname = os.path.join(logger.get_logger_dir(), JSONWriter.FILENAME) if stats is not None: try: epoch = stats[-1]['epoch_num'] + 1 except Exception: epoch = None # check against the current training settings # therefore this logic needs to be in before_train stage starting_epoch = self.trainer.loop.starting_epoch if epoch is None or epoch == starting_epoch: logger.info("Found existing JSON inside {}, will append to it.".format(logger.get_logger_dir())) self._stats = stats else: logger.warn( "History epoch={} from JSON is not the predecessor of the current starting_epoch={}".format( epoch - 1, starting_epoch)) logger.warn("If you want to resume old training, either use `AutoResumeTrainConfig` " "or correctly set the new starting_epoch yourself to avoid inconsistency. ") backup_fname = JSONWriter.FILENAME + '.' + datetime.now().strftime('%m%d-%H%M%S') backup_fname = os.path.join(logger.get_logger_dir(), backup_fname) logger.warn("Now, we will train with starting_epoch={} and backup old json to {}".format( self.trainer.loop.starting_epoch, backup_fname)) shutil.move(self._fname, backup_fname) # in case we have something to log here. self._trigger() def _trigger_step(self): # will do this in trigger_epoch if self.local_step != self.trainer.steps_per_epoch - 1: self._trigger() def _trigger_epoch(self): self._trigger() @HIDE_DOC def process_scalar(self, name, val): self._stat_now[name] = val def _trigger(self): """ Add stats to json and dump to disk. Note that this method is idempotent. """ if len(self._stat_now): self._stat_now['epoch_num'] = self.epoch_num self._stat_now['global_step'] = self.global_step self._stats.append(self._stat_now) self._stat_now = {} self._write_stat() def _write_stat(self): tmp_filename = self._fname + '.tmp' try: with open(tmp_filename, 'w') as f: json.dump(self._stats, f) shutil.move(tmp_filename, self._fname) except IOError: # disk error sometimes.. logger.exception("Exception in JSONWriter._write_stat()!") class ScalarPrinter(MonitorBase): """ Print scalar data into terminal. """ def __init__(self, enable_step=False, enable_epoch=True, whitelist=None, blacklist=None): """ Args: enable_step, enable_epoch (bool): whether to print the monitor data (if any) between steps or between epochs. whitelist (list[str] or None): A list of regex. Only names matching some regex will be allowed for printing. Defaults to match all names. blacklist (list[str] or None): A list of regex. Names matching any regex will not be printed. Defaults to match no names. """ def compile_regex(rs): if rs is None: return None rs = {re.compile(r) for r in rs} return rs self._whitelist = compile_regex(whitelist) if blacklist is None: blacklist = [] self._blacklist = compile_regex(blacklist) self._enable_step = enable_step self._enable_epoch = enable_epoch self._dic = {} # in case we have something to log here. def _before_train(self): self._trigger() def _trigger_step(self): if self._enable_step: if self.local_step != self.trainer.steps_per_epoch - 1: # not the last step self._trigger() else: if not self._enable_epoch: self._trigger() # otherwise, will print them together def _trigger_epoch(self): if self._enable_epoch: self._trigger() @HIDE_DOC def process_scalar(self, name, val): self._dic[name] = float(val) def _trigger(self): # Print stats here def match_regex_list(regexs, name): for r in regexs: if r.search(name) is not None: return True return False for k, v in sorted(self._dic.items(), key=operator.itemgetter(0)): if self._whitelist is None or \ match_regex_list(self._whitelist, k): if not match_regex_list(self._blacklist, k): logger.info('{}: {:.5g}'.format(k, v)) self._dic = {} class ScalarHistory(MonitorBase): """ Only internally used by monitors. """ def __init__(self): self._dic = defaultdict(list) @HIDE_DOC def process_scalar(self, name, val): self._dic[name].append((self.global_step, float(val))) def get_latest(self, name): hist = self._dic[name] if len(hist) == 0: raise KeyError("No available data for the key: {}".format(name)) else: return hist[-1] def get_history(self, name): return self._dic[name] class SendMonitorData(MonitorBase): """ Execute a command with some specific scalar monitor data. This is useful for, e.g. building a custom statistics monitor. It will try to send once receiving all the stats """ def __init__(self, command, names): """ Args: command(str): a command to execute. Use format string with stat names as keys. names(list or str): data name(s) to use. Example: Send the stats to your phone through pushbullet: .. code-block:: python SendMonitorData('curl -u your_id: https://api.pushbullet.com/v2/pushes \\ -d type=note -d title="validation error" \\ -d body={validation_error} > /dev/null 2>&1', 'validation_error') """ self.command = command if not isinstance(names, list): names = [names] self.names = names self.dic = {} @HIDE_DOC def process_scalar(self, name, val): if name in self.names: self.dic[name] = val def _trigger_step(self): self._trigger() def _trigger(self): try: v = {k: self.dic[k] for k in self.names} except KeyError: return cmd = self.command.format(**v) ret = os.system(cmd) if ret != 0: logger.error("Command '{}' failed with ret={}!".format(cmd, ret)) self.dic = {} class CometMLMonitor(MonitorBase): """ Send scalar data and the graph to https://www.comet.ml. Note: 1. comet_ml requires you to `import comet_ml` before importing tensorflow or tensorpack. 2. The "automatic output logging" feature of comet_ml will make the training progress bar appear to freeze. Therefore the feature is disabled by default. """ def __init__(self, experiment=None, tags=None, **kwargs): """ Args: experiment (comet_ml.Experiment): if provided, invalidate all other arguments tags (list[str]): experiment tags kwargs: arguments used to initialize :class:`comet_ml.Experiment`, such as project name, API key, etc. Refer to its documentation for details. """ if experiment is not None: self._exp = experiment assert tags is None and len(kwargs) == 0 else: from comet_ml import Experiment kwargs.setdefault('log_code', True) # though it's not functioning, git patch logging requires it kwargs.setdefault('auto_output_logging', None) self._exp = Experiment(**kwargs) if tags is not None: self._exp.add_tags(tags) self._exp.set_code("Code logging is impossible ...") self._exp.log_dependency('tensorpack', __git_version__) @property def experiment(self): """ The :class:`comet_ml.Experiment` instance. """ return self._exp def _before_train(self): self._exp.set_model_graph(tf.get_default_graph()) @HIDE_DOC def process_scalar(self, name, val): self._exp.log_metric(name, val, step=self.global_step) @HIDE_DOC def process_image(self, name, val): self._exp.set_step(self.global_step) for idx, v in enumerate(val): log_name = "{}_step{}{}".format( name, self.global_step, "_" + str(idx) if len(val) > 1 else "") self._exp.log_image(v, image_format="jpeg", name=log_name, image_minmax=(0, 255)) def _after_train(self): self._exp.end() def _after_epoch(self): self._exp.log_epoch_end(self.epoch_num)
wrappers.py
# Copyright 2019 The PlaNet 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. """Environment wrappers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import atexit import datetime import io import os import sys import traceback import uuid import gym import gym.spaces import numpy as np import skimage.transform import tensorflow as tf from planet.tools import nested class ObservationDict(object): def __init__(self, env, key='observ'): self._env = env self._key = key def __getattr__(self, name): return getattr(self._env, name) @property def observation_space(self): spaces = {self._key: self._env.observation_space} return gym.spaces.Dict(spaces) @property def action_space(self): return self._env.action_space def step(self, action): obs, reward, done, info = self._env.step(action) obs = {self._key: np.array(obs)} return obs, reward, done, info def reset(self): obs = self._env.reset() obs = {self._key: np.array(obs)} return obs class ConcatObservation(object): """Select observations from a dict space and concatenate them.""" def __init__(self, env, keys): self._env = env self._keys = keys def __getattr__(self, name): return getattr(self._env, name) @property def observation_space(self): spaces = self._env.observation_space.spaces spaces = [spaces[key] for key in self._keys] low = np.concatenate([space.low for space in spaces], 0) high = np.concatenate([space.high for space in spaces], 0) dtypes = [space.dtype for space in spaces] if not all(dtype == dtypes[0] for dtype in dtypes): message = 'Spaces must have the same data type; are {}.' raise KeyError(message.format(', '.join(str(x) for x in dtypes))) return gym.spaces.Box(low, high, dtype=dtypes[0]) def step(self, action): obs, reward, done, info = self._env.step(action) obs = self._select_keys(obs) return obs, reward, done, info def reset(self): obs = self._env.reset() obs = self._select_keys(obs) return obs def _select_keys(self, obs): return np.concatenate([obs[key] for key in self._keys], 0) class SelectObservations(object): def __init__(self, env, keys): self._env = env self._keys = keys def __getattr__(self, name): return getattr(self._env, name) @property def observation_space(self): spaces = self._env.observation_space.spaces return gym.spaces.Dict({key: spaces[key] for key in self._keys}) @property def action_space(self): return self._env.action_space def step(self, action, *args, **kwargs): obs, reward, done, info = self._env.step(action, *args, **kwargs) obs = {key: obs[key] for key in self._keys} return obs, reward, done, info def reset(self, *args, **kwargs): obs = self._env.reset(*args, **kwargs) obs = {key: obs[key] for key in self._keys} return obs class PixelStack(object): def __init__(self, env, n_stack_history=2, size=(64, 64), dtype=np.uint8, key='image'): self._env = env self._n_stack_history = n_stack_history self._dtype = dtype self._key = key self._size = size self._image_history = [np.zeros(self._size + (3,), dtype=self._dtype) for _ in range(self._n_stack_history)] def __getattr__(self, name): return getattr(self._env, name) @property def observation_space(self): high = {np.uint8: 255, np.float: 1.0}[self._dtype] image = gym.spaces.Box(0, high, self._size + (3 * self._n_stack_history,), dtype=self._dtype) spaces = self._env.observation_space.spaces.copy() assert self._key in spaces spaces[self._key] = image return gym.spaces.Dict(spaces) @property def action_space(self): return self._env.action_space def step(self, action): obs, reward, done, info = self._env.step(action) self._image_history = self._image_history[1:] + [obs['image'].copy()] obs[self._key] = np.concatenate(self._image_history, axis=-1) return obs, reward, done, info def reset(self): obs = self._env.reset() obs[self._key] = np.concatenate([np.zeros(self._size + (3,), dtype=self._dtype) for _ in range(self._n_stack_history - 1)] + [obs['image'].copy()], axis=-1) return obs class PixelObservations(object): def __init__(self, env, size=(64, 64), dtype=np.uint8, key='image'): assert isinstance(env.observation_space, gym.spaces.Dict) self._env = env self._size = size self._dtype = dtype self._key = key def __getattr__(self, name): return getattr(self._env, name) @property def observation_space(self): high = {np.uint8: 255, np.float: 1.0}[self._dtype] image = gym.spaces.Box(0, high, self._size + (3,), dtype=self._dtype) spaces = self._env.observation_space.spaces.copy() assert self._key not in spaces spaces[self._key] = image return gym.spaces.Dict(spaces) @property def action_space(self): return self._env.action_space def step(self, action): obs, reward, done, info = self._env.step(action) obs[self._key] = self._render_image() return obs, reward, done, info def reset(self): obs = self._env.reset() obs[self._key] = self._render_image() return obs def _render_image(self): image = self._env.render('rgb_array') if image.shape[:2] != self._size: kwargs = dict( output_shape=self._size, mode='edge', order=1, preserve_range=True) image = skimage.transform.resize(image, **kwargs).astype(image.dtype) if self._dtype and image.dtype != self._dtype: if image.dtype in (np.float32, np.float64) and self._dtype == np.uint8: image = (image * 255).astype(self._dtype) elif image.dtype == np.uint8 and self._dtype in (np.float32, np.float64): image = image.astype(self._dtype) / 255 else: message = 'Cannot convert observations from {} to {}.' raise NotImplementedError(message.format(image.dtype, self._dtype)) return image class ObservationToRender(object): def __init__(self, env, key='image'): self._env = env self._key = key self._image = None def __getattr__(self, name): return getattr(self._env, name) @property def observation_space(self): return gym.spaces.Dict({}) def step(self, action): obs, reward, done, info = self._env.step(action) self._image = obs.pop(self._key) return obs, reward, done, info def reset(self): obs = self._env.reset() self._image = obs.pop(self._key) return obs def render(self, *args, **kwargs): return self._image class OverwriteRender(object): def __init__(self, env, render_fn): self._env = env self._render_fn = render_fn self._env.render('rgb_array') # Set up viewer. def __getattr__(self, name): return getattr(self._env, name) def render(self, *args, **kwargs): return self._render_fn(self._env, *args, **kwargs) class ActionRepeat(object): """Repeat the agent action multiple steps.""" def __init__(self, env, amount): self._env = env self._amount = amount def __getattr__(self, name): return getattr(self._env, name) def step(self, action): done = False total_reward = 0 current_step = 0 while current_step < self._amount and not done: observ, reward, done, info = self._env.step(action) total_reward += reward current_step += 1 return observ, total_reward, done, info class NormalizeActions(object): def __init__(self, env): self._env = env low, high = env.action_space.low, env.action_space.high self._enabled = np.logical_and(np.isfinite(low), np.isfinite(high)) self._low = np.where(self._enabled, low, -np.ones_like(low)) self._high = np.where(self._enabled, high, np.ones_like(low)) def __getattr__(self, name): return getattr(self._env, name) @property def action_space(self): space = self._env.action_space low = np.where(self._enabled, -np.ones_like(space.low), space.low) high = np.where(self._enabled, np.ones_like(space.high), space.high) return gym.spaces.Box(low, high, dtype=space.dtype) def step(self, action): action = (action + 1) / 2 * (self._high - self._low) + self._low return self._env.step(action) class DeepMindWrapper(object): """Wraps a DM Control environment into a Gym interface.""" metadata = {'render.modes': ['rgb_array']} reward_range = (-np.inf, np.inf) def __init__(self, env, render_size=(64, 64), camera_id=0): self._env = env self._render_size = render_size self._camera_id = camera_id def __getattr__(self, name): return getattr(self._env, name) @property def observation_space(self): components = {} for key, value in self._env.observation_spec().items(): components[key] = gym.spaces.Box( -np.inf, np.inf, value.shape, dtype=np.float32) return gym.spaces.Dict(components) @property def action_space(self): action_spec = self._env.action_spec() return gym.spaces.Box( action_spec.minimum, action_spec.maximum, dtype=np.float32) def step(self, action): time_step = self._env.step(action) obs = dict(time_step.observation) reward = time_step.reward or 0 done = time_step.last() info = {'discount': time_step.discount} return obs, reward, done, info def reset(self): time_step = self._env.reset() return dict(time_step.observation) def render(self, *args, **kwargs): if kwargs.get('mode', 'rgb_array') != 'rgb_array': raise ValueError("Only render mode 'rgb_array' is supported.") del args # Unused del kwargs # Unused return self._env.physics.render( *self._render_size, camera_id=self._camera_id) class MaximumDuration(object): """Limits the episode to a given upper number of decision points.""" def __init__(self, env, duration): self._env = env self._duration = duration self._step = None def __getattr__(self, name): return getattr(self._env, name) def step(self, action): if self._step is None: raise RuntimeError('Must reset environment.') observ, reward, done, info = self._env.step(action) self._step += 1 if self._step >= self._duration: done = True self._step = None return observ, reward, done, info def reset(self): self._step = 0 return self._env.reset() class MinimumDuration(object): """Extends the episode to a given lower number of decision points.""" def __init__(self, env, duration): self._env = env self._duration = duration self._step = None def __getattr__(self, name): return getattr(self._env, name) def step(self, action): observ, reward, done, info = self._env.step(action) self._step += 1 if self._step < self._duration: done = False return observ, reward, done, info def reset(self): self._step = 0 return self._env.reset() class ProcessObservation(object): def __init__(self, env, process_fn): self._env = env self._process_fn = process_fn def __getattr__(self, name): return getattr(self._env, name) @property def observation_space(self): return nested.map( lambda box: gym.spaces.Box( self._process_fn(box.low), self._process_fn(box.high), dtype=self._process_fn(box.low).dtype), self._env.observation_space) def step(self, action): observ, reward, done, info = self._env.step(action) observ = self._process_fn(observ) return observ, reward, done, info def reset(self): observ = self._env.reset() observ = self._process_fn(observ) return observ class PadActions(object): """Pad action space to the largest action space.""" def __init__(self, env, spaces): self._env = env self._action_space = self._pad_box_space(spaces) @property def observation_space(self): return self._env.observation_space @property def action_space(self): return self._action_space def step(self, action, *args, **kwargs): action = action[:len(self._env.action_space.low)] return self._env.step(action, *args, **kwargs) def reset(self, *args, **kwargs): return self._env.reset(*args, **kwargs) def _pad_box_space(self, spaces): assert all(len(space.low.shape) == 1 for space in spaces) length = max(len(space.low) for space in spaces) low, high = np.inf * np.ones(length), -np.inf * np.ones(length) for space in spaces: low[:len(space.low)] = np.minimum(space.low, low[:len(space.low)]) high[:len(space.high)] = np.maximum(space.high, high[:len(space.high)]) return gym.spaces.Box(low, high, dtype=np.float32) class CollectGymDataset(object): """Collect transition tuples and store episodes as Numpy files. The time indices of the collected epiosde use the convention that at each time step, the agent first decides on an action, and the environment then returns the reward and observation. This means the action causes the environment state and thus observation and rewards at the same time step. A dynamics model can thus predict the sequence of observations and rewards from the sequence of actions. The first transition tuple contains the observation returned from resetting the environment, together with zeros for the action and reward. Thus, the episode length is one more than the number of decision points. """ def __init__(self, env, outdir): self._env = env self._outdir = outdir and os.path.expanduser(outdir) self._episode = None def __getattr__(self, name): return getattr(self._env, name) def step(self, action, *args, **kwargs): if kwargs.get('blocking', True): transition = self._env.step(action, *args, **kwargs) return self._process_step(action, *transition) else: future = self._env.step(action, *args, **kwargs) return lambda: self._process_step(action, *future()) def reset(self, *args, **kwargs): if kwargs.get('blocking', True): observ = self._env.reset(*args, **kwargs) return self._process_reset(observ) else: future = self._env.reset(*args, **kwargs) return lambda: self._process_reset(future()) def _process_step(self, action, observ, reward, done, info): transition = self._process_observ(observ).copy() transition['action'] = action transition['reward'] = reward self._episode.append(transition) if done: episode = self._get_episode() # info['episode'] = episode if self._outdir: filename = self._get_filename() self._write(episode, filename) return observ, reward, done, info def _process_reset(self, observ): # Resetting the environment provides the observation for time step zero. # The action and reward are not known for this time step, so we zero them. transition = self._process_observ(observ).copy() transition['action'] = np.zeros_like(self.action_space.low) transition['reward'] = 0.0 self._episode = [transition] return observ def _process_observ(self, observ): if not isinstance(observ, dict): observ = {'observ': observ} return observ def _get_filename(self): timestamp = datetime.datetime.now().strftime('%Y%m%dT%H%M%S') identifier = str(uuid.uuid4()).replace('-', '') filename = '{}-{}.npz'.format(timestamp, identifier) filename = os.path.join(self._outdir, filename) return filename def _get_episode(self): episode = {k: [t[k] for t in self._episode] for k in self._episode[0]} episode = {k: np.array(v) for k, v in episode.items()} for key, sequence in episode.items(): if sequence.dtype == 'object': message = "Sequence '{}' is not numeric:\n{}" raise RuntimeError(message.format(key, sequence)) return episode def _write(self, episode, filename): if not tf.gfile.Exists(self._outdir): tf.gfile.MakeDirs(self._outdir) with io.BytesIO() as file_: np.savez_compressed(file_, **episode) file_.seek(0) with tf.gfile.Open(filename, 'w') as ff: ff.write(file_.read()) folder = os.path.basename(self._outdir) name = os.path.splitext(os.path.basename(filename))[0] print('Recorded episode {} to {}.'.format(name, folder)) class ConvertTo32Bit(object): """Convert data types of an OpenAI Gym environment to 32 bit.""" def __init__(self, env): self._env = env def __getattr__(self, name): return getattr(self._env, name) def step(self, action): observ, reward, done, info = self._env.step(action) observ = nested.map(self._convert_observ, observ) reward = self._convert_reward(reward) return observ, reward, done, info def reset(self): observ = self._env.reset() observ = nested.map(self._convert_observ, observ) return observ def _convert_observ(self, observ): if not np.isfinite(observ).all(): raise ValueError('Infinite observation encountered.') if observ.dtype == np.float64: return observ.astype(np.float32) if observ.dtype == np.int64: return observ.astype(np.int32) return observ def _convert_reward(self, reward): if not np.isfinite(reward).all(): raise ValueError('Infinite reward encountered.') return np.array(reward, dtype=np.float32) class Async(object): """Step environment in a separate process for lock free paralellism.""" # Message types for communication via the pipe. _ACCESS = 1 _CALL = 2 _RESULT = 3 _EXCEPTION = 4 _CLOSE = 5 def __init__(self, constructor, strategy='thread'): """Step environment in a separate process for lock free parallelism. The environment will be created in the external process by calling the specified callable. This can be an environment class, or a function creating the environment and potentially wrapping it. The returned environment should not access global variables. Args: constructor: Callable that creates and returns an OpenAI gym environment. Attributes: observation_space: The cached observation space of the environment. action_space: The cached action space of the environment. """ if strategy == 'thread': import multiprocessing.dummy as mp elif strategy == 'process': import multiprocessing as mp else: raise NotImplementedError(strategy) self._conn, conn = mp.Pipe() self._process = mp.Process(target=self._worker, args=(constructor, conn)) atexit.register(self.close) self._process.start() self._observ_space = None self._action_space = None @property def observation_space(self): if not self._observ_space: self._observ_space = self.__getattr__('observation_space') return self._observ_space @property def action_space(self): if not self._action_space: self._action_space = self.__getattr__('action_space') return self._action_space def __getattr__(self, name): """Request an attribute from the environment. Note that this involves communication with the external process, so it can be slow. Args: name: Attribute to access. Returns: Value of the attribute. """ self._conn.send((self._ACCESS, name)) return self._receive() def call(self, name, *args, **kwargs): """Asynchronously call a method of the external environment. Args: name: Name of the method to call. *args: Positional arguments to forward to the method. **kwargs: Keyword arguments to forward to the method. Returns: Promise object that blocks and provides the return value when called. """ payload = name, args, kwargs self._conn.send((self._CALL, payload)) return self._receive def close(self): """Send a close message to the external process and join it.""" try: self._conn.send((self._CLOSE, None)) self._conn.close() except IOError: # The connection was already closed. pass self._process.join() def step(self, action, blocking=True): """Step the environment. Args: action: The action to apply to the environment. blocking: Whether to wait for the result. Returns: Transition tuple when blocking, otherwise callable that returns the transition tuple. """ promise = self.call('step', action) if blocking: return promise() else: return promise def reset(self, blocking=True): """Reset the environment. Args: blocking: Whether to wait for the result. Returns: New observation when blocking, otherwise callable that returns the new observation. """ promise = self.call('reset') if blocking: return promise() else: return promise def _receive(self): """Wait for a message from the worker process and return its payload. Raises: Exception: An exception was raised inside the worker process. KeyError: The received message is of an unknown type. Returns: Payload object of the message. """ try: message, payload = self._conn.recv() except OSError: raise RuntimeError('Environment worker crashed.') # Re-raise exceptions in the main process. if message == self._EXCEPTION: stacktrace = payload raise Exception(stacktrace) if message == self._RESULT: return payload raise KeyError('Received message of unexpected type {}'.format(message)) def _worker(self, constructor, conn): """The process waits for actions and sends back environment results. Args: constructor: Constructor for the OpenAI Gym environment. conn: Connection for communication to the main process. Raises: KeyError: When receiving a message of unknown type. """ try: env = constructor() while True: try: # Only block for short times to have keyboard exceptions be raised. if not conn.poll(0.1): continue message, payload = conn.recv() except (EOFError, KeyboardInterrupt): break if message == self._ACCESS: name = payload result = getattr(env, name) conn.send((self._RESULT, result)) continue if message == self._CALL: name, args, kwargs = payload result = getattr(env, name)(*args, **kwargs) conn.send((self._RESULT, result)) continue if message == self._CLOSE: assert payload is None break raise KeyError('Received message of unknown type {}'.format(message)) except Exception: stacktrace = ''.join(traceback.format_exception(*sys.exc_info())) print('Error in environment process: {}'.format(stacktrace)) try: conn.send((self._EXCEPTION, stacktrace)) except Exception: print('Failed to send exception back to main process.') try: conn.close() except Exception: print('Failed to properly close connection.')
dokku-installer.py
#!/usr/bin/env python3 import cgi import json import os import re import shutil try: import SimpleHTTPServer import SocketServer except ImportError: import http.server as SimpleHTTPServer import socketserver as SocketServer import subprocess import sys import threading VERSION = 'v0.23.3' def bytes_to_string(b): if type(b) == bytes: encoding = sys.stdout.encoding if encoding is None: encoding = 'utf-8' b = b.decode(encoding) b = b.strip() return b def string_to_bytes(s): if type(s) == str: encoding = sys.stdout.encoding if encoding is None: encoding = 'utf-8' s = s.encode(encoding) return s hostname = '' try: command = "bash -c '[[ $(dig +short $HOSTNAME) ]] && echo $HOSTNAME || wget -q -O - icanhazip.com'" hostname = bytes_to_string(subprocess.check_output(command, shell=True)) except subprocess.CalledProcessError: pass key_file = os.getenv('KEY_FILE', None) if os.path.isfile('/home/ec2-user/.ssh/authorized_keys'): key_file = '/home/ec2-user/.ssh/authorized_keys' elif os.path.isfile('/home/ubuntu/.ssh/authorized_keys'): key_file = '/home/ubuntu/.ssh/authorized_keys' else: key_file = '/root/.ssh/authorized_keys' admin_keys = [] if os.path.isfile(key_file): try: command = "cat {0}".format(key_file) admin_keys = bytes_to_string(subprocess.check_output(command, shell=True)).strip().split("\n") except subprocess.CalledProcessError: pass ufw_display = 'block' try: command = "sudo ufw status" ufw_output = bytes_to_string(subprocess.check_output(command, shell=True).strip()) if "inactive" in ufw_output: ufw_display = 'none' except subprocess.CalledProcessError: ufw_display = 'none' nginx_dir = '/etc/nginx' nginx_init = '/etc/init.d/nginx' try: command = "test -x /usr/bin/openresty" subprocess.check_output(command, shell=True) nginx_dir = '/usr/local/openresty/nginx/conf' nginx_init = '/etc/init.d/openresty' except subprocess.CalledProcessError: pass def check_boot(): if 'onboot' not in sys.argv: return init_dir = os.getenv('INIT_DIR', '/etc/init') systemd_dir = os.getenv('SYSTEMD_DIR', '/etc/systemd/system') nginx_conf_dir = os.getenv('NGINX_CONF_DIR', '{0}/conf.d'.format(nginx_dir)) if os.path.exists(init_dir): with open('{0}/dokku-installer.conf'.format(init_dir), 'w') as f: f.write("start on runlevel [2345]\n") f.write("exec {0} selfdestruct\n".format(os.path.abspath(__file__))) if os.path.exists(systemd_dir): with open('{0}/dokku-installer.service'.format(systemd_dir), 'w') as f: f.write("[Unit]\n") f.write("Description=Dokku web-installer\n") f.write("\n") f.write("[Service]\n") f.write("ExecStart={0} selfdestruct\n".format(os.path.abspath(__file__))) f.write("\n") f.write("[Install]\n") f.write("WantedBy=multi-user.target\n") f.write("WantedBy=graphical.target\n") if os.path.exists(nginx_conf_dir): with open('{0}/dokku-installer.conf'.format(nginx_conf_dir), 'w') as f: f.write("upstream dokku-installer { server 127.0.0.1:2000; }\n") f.write("server {\n") f.write(" listen 80;\n") f.write(" location / {\n") f.write(" proxy_pass http://dokku-installer;\n") f.write(" }\n") f.write("}\n") subprocess.call('rm -f {0}/sites-enabled/*'.format(nginx_dir), shell=True) sys.exit(0) class GetHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def write_content(self, content): try: self.wfile.write(content) except TypeError: self.wfile.write(string_to_bytes(content)) def do_GET(self): content = PAGE.replace('{VERSION}', VERSION) content = content.replace('{UFW_DISPLAY}', ufw_display) content = content.replace('{HOSTNAME}', hostname) content = content.replace('{AUTHORIZED_KEYS_LOCATION}', key_file) content = content.replace('{ADMIN_KEYS}', "\n".join(admin_keys)) self.send_response(200) self.end_headers() self.write_content(content) def do_POST(self): if self.path not in ['/setup', '/setup/']: return params = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type']}) dokku_root = os.getenv('DOKKU_ROOT', '/home/dokku') dokku_user = os.getenv('DOKKU_SYSTEM_GROUP', 'dokku') dokku_group = os.getenv('DOKKU_SYSTEM_USER', 'dokku') vhost_enable = 'false' vhost_filename = '{0}/VHOST'.format(dokku_root) if 'vhost' in params and params['vhost'].value == 'true': vhost_enable = 'true' with open(vhost_filename, 'w') as f: f.write(params['hostname'].value.strip("/")) shutil.chown(vhost_filename, dokku_user, dokku_group) else: try: os.remove(vhost_filename) except OSError: pass hostname_filename = '{0}/HOSTNAME'.format(dokku_root) with open(hostname_filename, 'w') as f: f.write(params['hostname'].value.strip("/")) shutil.chown(hostname_filename, dokku_user, dokku_group) for (index, key) in enumerate(params['keys'].value.splitlines(), 1): user = 'admin' if self.admin_user_exists() is not None: user = 'web-admin' if self.web_admin_user_exists() is not None: index = int(self.web_admin_user_exists()) + 1 elif self.web_admin_user_exists() is None: index = 1 elif self.admin_user_exists() is None: pass else: index = int(self.admin_user_exists()) + 1 user = user + str(index) command = ['sshcommand', 'acl-add', 'dokku', user] proc = subprocess.Popen(command, stdin=subprocess.PIPE) try: proc.stdin.write(key) except TypeError: proc.stdin.write(string_to_bytes(key)) proc.stdin.close() proc.wait() set_debconf_selection('boolean', 'nginx_enable', 'true') set_debconf_selection('boolean', 'skip_key_file', 'true') set_debconf_selection('boolean', 'vhost_enable', vhost_enable) set_debconf_selection('boolean', 'web_config', 'false') set_debconf_selection('string', 'hostname', params['hostname'].value) if 'selfdestruct' in sys.argv: DeleteInstallerThread() content = json.dumps({'status': 'ok'}) self.send_response(200) self.end_headers() self.write_content(content) def web_admin_user_exists(self): return self.user_exists('web-admin(\d+)') def admin_user_exists(self): return self.user_exists('admin(\d+)') def user_exists(self, name): command = 'dokku ssh-keys:list' pattern = re.compile(r'NAME="' + name + '"') proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) max_num = 0 exists = False for line in proc.stdout: m = pattern.search(bytes_to_string(line)) if m: # User of the form `user` or `user#` exists exists = True max_num = max(max_num, int(m.group(1))) if exists: return max_num else: return None def set_debconf_selection(debconf_type, key, value): found = False with open('/etc/os-release', 'r') as f: for line in f: if 'debian' in line: found = True if not found: return ps = subprocess.Popen(['echo', 'dokku dokku/{0} {1} {2}'.format( key, debconf_type, value )], stdout=subprocess.PIPE) try: subprocess.check_output(['debconf-set-selections'], stdin=ps.stdout) except subprocess.CalledProcessError: pass ps.wait() class DeleteInstallerThread(object): def __init__(self, interval=1): thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start() def run(self): command = "rm {0}/conf.d/dokku-installer.conf && {1} stop && {1} start".format(nginx_dir, nginx_init) try: subprocess.call(command, shell=True) except: pass command = "rm -f /etc/init/dokku-installer.conf /etc/systemd/system/dokku-installer.service && (stop dokku-installer || systemctl stop dokku-installer.service)" try: subprocess.call(command, shell=True) except: pass def main(): check_boot() port = int(os.getenv('PORT', 2000)) httpd = SocketServer.TCPServer(("", port), GetHandler) print("Listening on 0.0.0.0:{0}, CTRL+C to stop".format(port)) httpd.serve_forever() PAGE = """ <html> <head> <meta charset="utf-8" /> <title>Dokku Setup</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <style> .bd-callout { padding: 1.25rem; margin-top: 1.25rem; margin-bottom: 1.25rem; border: 1px solid #eee; border-left-width: .25rem; border-radius: .25rem; } .bd-callout p:last-child { margin-bottom: 0; } .bd-callout-info { border-left-color: #5bc0de; } pre { font-size: 80%; margin-bottom: 0; } h1 small { font-size: 50%; } h5 { font-size: 1rem; } .container { width: 640px; } .result { padding-left: 20px; } input.form-control, textarea.form-control { background-color: #fafbfc; font-size: 14px; } input.form-control::placeholder, textarea.form-control::placeholder { color: #adb2b8 } </style> </head> <body> <div class="container"> <form id="form" role="form"> <h1 class="pt-3">Dokku Setup <small class="text-muted">{VERSION}</small></h1> <div class="alert alert-warning small" role="alert"> <strong>Warning:</strong> The SSH key filled out here can grant root access to the server. Please complete the setup as soon as possible. </div> <div class="row"> <div class="col"> <h3>Admin Access</h3> <div class="form-group"> <label for="key">Public SSH Keys</label><br /> <textarea class="form-control" name="keys" rows="5" id="key" placeholder="Begins with 'ssh-rsa', 'ssh-dss', 'ssh-ed25519', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', or 'ecdsa-sha2-nistp521'">{ADMIN_KEYS}</textarea> <small class="form-text text-muted">Public keys allow users to ssh onto the server as the <code>dokku</code> user, as well as remotely execute Dokku commands. They are currently auto-populated from: <code>{AUTHORIZED_KEYS_LOCATION}</code>, and can be changed later via the <a href="http://dokku.viewdocs.io/dokku/deployment/user-management/" target="_blank"><code>dokku ssh-keys</code></a> plugin.</small> </div> </div> </div> <div class="row"> <div class="col"> <h3>Hostname Configuration</h3> <div class="form-group"> <label for="hostname">Hostname</label> <input class="form-control" type="text" id="hostname" name="hostname" value="{HOSTNAME}" placeholder="A hostname or ip address such as {HOSTNAME}" /> <small class="form-text text-muted">This will be used as the default host for all applications, and can be changed later via the <a href="http://dokku.viewdocs.io/dokku/configuration/domains/" target="_blank"><code>dokku domains:set-global</code></a> command.</small> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" id="vhost" name="vhost" value="true"> <label class="form-check-label" for="vhost">Use virtualhost naming for apps</label> <small class="form-text text-muted">When enabled, Nginx will be run on port 80 and proxy requests to apps based on hostname.</small> <small class="form-text text-muted">When disabled, a specific port will be setup for each application on first deploy, and requests to that port will be proxied to the relevant app.</small> </div> <div class="alert alert-warning small mt-3 d-{UFW_DISPLAY}" role="alert"> <strong>Warning:</strong> UFW is active. To allow traffic to specific ports, run <code>sudo ufw allow PORT</code> for the port in question. </div> <div class="bd-callout bd-callout-info"> <h5>What will app URLs look like?</h5> <pre><code id="example">http://hostname:port</code></pre> </div> </div> </div> <button type="button" onclick="setup()" class="btn btn-primary">Finish Setup</button> <span class="result"></span> </form> </div> <div id="error-output"></div> <script> var $ = document.querySelector.bind(document) function setup() { if ($("#key").value.trim() == "") { alert("Your admin public key cannot be blank.") return } if ($("#hostname").value.trim() == "") { alert("Your hostname cannot be blank.") return } var data = new FormData($("#form")) var inputs = [].slice.call(document.querySelectorAll("input, textarea, button")) inputs.forEach(function (input) { input.disabled = true }) var result = $(".result") fetch("/setup", {method: "POST", body: data}) .then(function(response) { if (response.ok) { return response.json() } else { throw new Error('Server returned error') } }) .then(function(response) { result.classList.add("text-success"); result.textContent = "Success! Redirecting in 3 seconds. .." setTimeout(function() { window.location.href = "http://dokku.viewdocs.io/dokku~{VERSION}/deployment/application-deployment/"; }, 3000); }) .catch(function (error) { result.classList.add("text-danger"); result.textContent = "Could not send the request" }) } function update() { if ($("#vhost").matches(":checked") && $("#hostname").value.match(/^(\d{1,3}\.){3}\d{1,3}$/)) { alert("In order to use virtualhost naming, the hostname must not be an IP but a valid domain name.") $("#vhost").checked = false; } if ($("#vhost").matches(':checked')) { $("#example").textContent = "http://<app-name>."+$("#hostname").value } else { $("#example").textContent = "http://"+$("#hostname").value+":<app-port>" } } $("#vhost").addEventListener("change", update); $("#hostname").addEventListener("input", update); update(); </script> </body> </html> """ if __name__ == "__main__": main()
oase_apply.py
# Copyright 2019 NEC Corporation # # 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. # """ [概要] ルールの作成更新削除アップロードを行う。 ルールファイルのDLを行う。 """ import os import django import sys import socket import pytz import datetime import json import base64 import threading import subprocess import re import requests import time import zipfile import traceback my_path = os.path.dirname(os.path.abspath(__file__)) tmp_path = my_path.split('oase-root') root_dir_path = tmp_path[0] + 'oase-root' sys.path.append(root_dir_path) os.environ['DJANGO_SETTINGS_MODULE'] = 'confs.frameworkconfs.settings' django.setup() from django.db import transaction from django.db.models import Q from django.conf import settings from libs.commonlibs.oase_logger import OaseLogger logger = OaseLogger.get_instance() # ロガー初期化 from libs.commonlibs.define import * from libs.commonlibs.createxl import DecisionTableFactory from libs.commonlibs.createxl import DecisionTableCustomizer from libs.commonlibs.testrequest_createxl import TestRequestXlFactory from libs.commonlibs.dt_component import DecisionTableComponent from libs.commonlibs.aes_cipher import AESCipher from libs.backyardlibs.backyard_common import disconnect from web_app.models.models import RuleFile from web_app.models.models import RuleType from web_app.models.models import System from web_app.models.models import User from web_app.models.models import RuleManage from web_app.models.models import DataObject from web_app.models.models import AccessPermission from web_app.templatetags.common import get_message APPLY_LOCK = threading.Lock() DOWNLOAD_LOCK = threading.Lock() APPLY_USER_ID = -2140000003 def conv_tz(dt, tzname): return dt.astimezone(pytz.timezone(tzname)).strftime('%Y-%m-%d %H:%M:%S.%f') def make_send_data(data, need_keys=[], omit_keys=[]): logger.logic_log('LOSI00001', 'need_keys: %s' % need_keys) ret_data = data.copy() if len(need_keys) > 0: for k, v in ret_data.items(): if k not in need_keys: omit_keys.append(k) for k in omit_keys: if k in ret_data: ret_data.pop(k) logger.logic_log('LOSI00002', 'None') return ret_data def create(request): disconnect() logger.logic_log('LOSI00001', request) result = '' msg = '' # リクエストのパラメーター取得 uid = int(request['user_id']) table_info = request['table_info'] data_objs = request['data_obj_info'] label_cnt = request['label_count'] lang = request['lang'] notificationInfo = request['notificationInfo'] type_name = table_info['rule_type_name'] summary = table_info['summary'] table_name = table_info['rule_table_name'] now = datetime.datetime.now(pytz.timezone('UTC')) user = User.objects.get(user_id=uid) dtcomp = DecisionTableComponent(table_name) unknown_event_notification = notificationInfo['unknown_event_notification'] mail_address = notificationInfo['mail_address'] servicenow_driver_id = notificationInfo['servicenow_driver_id'] rule_type_id = 0 ret_info = { 'result': 'OK', 'msg': '', } try: with transaction.atomic(): ######################################## # DB保存 ######################################## # ルール種別 rule_type = RuleType( rule_type_name=type_name, summary=summary, rule_table_name=table_name, generation_limit=3, group_id=dtcomp.group_id, artifact_id=dtcomp.artifact_id, container_id_prefix_staging=dtcomp.contid_stg, container_id_prefix_product=dtcomp.contid_prd, label_count=label_cnt, unknown_event_notification=unknown_event_notification, mail_address=mail_address, servicenow_driver_id=servicenow_driver_id, last_update_timestamp=now, last_update_user=user.user_name ) rule_type.save(force_insert=True) # データオブジェクト data_obj_list = [] for dob in data_objs: data_object = DataObject( rule_type_id=rule_type.rule_type_id, conditional_name=dob['conditional_name'], label=dob['label'], conditional_expression_id=int(dob['conditional_expression_id']), last_update_timestamp=now, last_update_user=user.user_name ) data_obj_list.append(data_object) if len(data_obj_list) > 0: DataObject.objects.bulk_create(data_obj_list) ######################################## # RHDMコンポーネント作成 ######################################## rule_type_id = rule_type.rule_type_id dtcomp.make_component_all(rule_type_id) ######################################## # Excel作成 ######################################## dt_fact = DecisionTableFactory( rule_type_id, dtcomp.rule_set, dtcomp.table_name, dtcomp.class_name, dtcomp.fact_name, dtcomp.get_dtable_path(), lang) success_flg = dt_fact.create_decision_table() if not success_flg: msg = 'MOSJA03501' logger.system_log('LOSM12021', 'rule_type_id: %s, rule_type_name: %s' % (rule_type_id, type_name)) raise Exception() ######################################## # Excel作成(TestRequest) ######################################## testreq_fact = TestRequestXlFactory(rule_type_id, dtcomp.table_name, dtcomp.get_dtable_path(), request) success_flg = testreq_fact.create_testrequest_table() if not success_flg: msg = 'MOSJA03503' logger.system_log('LOSM12053', 'rule_type_id: %s, rule_type_name: %s' % (rule_type_id, type_name)) raise Exception() except FileExistsError as e: # RHDMコンポーネント作成において、新規作成するルール種別のディレクトリが既に存在していた場合 logger.system_log('LOSM12051', 'traceback: %s' % traceback.format_exc()) ret_info = { 'result': 'NG', 'msg': 'MOSJA03502', } except Exception as e: if rule_type_id > 0: dtcomp.remove_component(rule_type_id) if not msg: msg = 'MOSJA03001' logger.system_log('LOSM12007', 'traceback: %s' % traceback.format_exc()) ret_info = { 'result': 'NG', 'msg': msg, } logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info def upload(request): disconnect() logger.logic_log('LOSI00001', 'ruletypeid: %s, filename: %s' % (request['ruletypeid'], request['filename'])) result = '' msg = '' errmsg = '' userlog = 'user_id=' + str(request['upload_user_id']) errlog_prefix = True ret_info = { 'result': 'OK', 'msg': '', } try: now = datetime.datetime.now(pytz.timezone('UTC')) now_tz = conv_tz(now, 'Asia/Tokyo') user = User.objects.get(user_id=request['upload_user_id']) lang = user.get_lang_mode() ruletypeid = int(request['ruletypeid']) rulefile = None rule_manage = None try: with transaction.atomic(): # ルールファイルDB登録 rulefile = RuleFile( rule_type_id=ruletypeid, rule_file_name=request['filename'], last_update_timestamp=now, last_update_user=user.user_name ) rulefile.save(force_insert=True) # ルール適用管理登録 rule_manage = RuleManage( rule_type_id=ruletypeid, request_type_id=STAGING, rule_file_id=rulefile.pk, system_status=RULE_STS_SYSTEM.UPLOAD, operation_status=RULE_STS_OPERATION.STAGING_NOAPPLY, last_update_timestamp=now, last_update_user=user.user_name ) rule_manage.save(force_insert=True) except Exception as e: ret_info = { 'result': 'NG', 'msg': 'MOSJA03101', } logger.system_log('LOSM12022', traceback.format_exc()) logger.logic_log('LOSI00002', ret_info) return ret_info # ルール種別情報取得 ruleType = RuleType.objects.get(rule_type_id=ruletypeid) artifactid = ruleType.artifact_id groupid = ruleType.group_id dtcomp = DecisionTableComponent(ruleType.rule_table_name) dtcomp.set_path(rule_path['rule_srcpath'], '%s%s/' % (rule_path['rule_rootpath'], ruletypeid)) srcpath = dtcomp.get_pom_path() dstpath = '%s%s/%s/' % (request['rule_dstpath'], ruletypeid, rulefile.pk) filepath = request['rule_filepath'] % (ruletypeid, rulefile.pk) + ruleType.rule_table_name + '/' # kjar構築用ファイルをコピー os.makedirs(dstpath, exist_ok=True) if not os.path.exists(srcpath): try: with transaction.atomic(): rule_manage.system_status = RULE_STS_SYSTEM.UPLOAD_NG rule_manage.last_update_timestamp = now rule_manage.last_update_user = user.user_name rule_manage.save(force_update=True) except Exception as e: errmsg = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03104', lang) errmsg = errmsg + '\n' + str(now_tz) + ' ' + userlog + ' ' + str(e) msg = 'MOSJA03104' logger.system_log('LOSM12023',userlog) raise Exception(errmsg) errmsg = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03102', lang) msg = 'MOSJA03102' logger.system_log('LOSM12024', srcpath) raise Exception(errmsg) dtcomp.copy_tree(dstpath) # ルールファイルの保存 os.makedirs(filepath, exist_ok=True) filename = request['filename'] filedata = request['filedata'] filedata = base64.b64decode(filedata.encode('utf-8')) with open(filepath + filename, 'wb') as fp: fp.write(filedata) # 保存したルールファイルのチェック dtcomp.set_rule_type_id(ruletypeid) errmsg_list = dtcomp.check_decision_table_file(filepath + filename, lang) if len(errmsg_list) > 0: errmsg += str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03121', lang) + '\n' for em in errmsg_list: errmsg += str(now_tz) + ' ' + userlog + ' ' + em + '\n' errlog_prefix = False logger.user_log('LOSM12061') raise Exception(errmsg) except User.DoesNotExist: ret_info = { 'result': 'NG', 'msg': 'MOSJA03101', } logger.system_log('LOSM12022', traceback.format_exc()) logger.logic_log('LOSI00002', ret_info) return ret_info except Exception as e: rule_manage.system_status = RULE_STS_SYSTEM.UPLOAD_NG rule_manage.last_update_timestamp = now rule_manage.last_update_user = user.user_name rule_manage.save(force_update=True) errfilename = '%s_err.log' % (request['filename'].rsplit('.')[0]) errfilepath = dstpath + errfilename errmsg = '' if errlog_prefix: errmsg = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03106', lang).replace('\n', '\n') errmsg = errmsg + '\n' + str(now_tz) + ' ' + userlog + ' ' + str(e) + '\n' else: errmsg = str(e) + '\n' if not os.path.exists(dstpath): os.makedirs(dstpath, exist_ok=True) with open(errfilepath, 'a') as f: f.write(errmsg) msg = 'MOSJA03007' if not msg else msg ret_info = { 'result': 'NG', 'msg': msg, } logger.system_log('LOSM12025', traceback.format_exc()) logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info ret_info.update( msg='MOSJA03002', ruletypeid=ruletypeid, rule_file_id=rulefile.pk, artifactid=artifactid, groupid=groupid, pompath=dstpath, request_type_id=STAGING, apply_user_id=request['upload_user_id'], rule_manage_id=rule_manage.rule_manage_id ) logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info def apply_req(request): disconnect() logger.logic_log('LOSI00001', 'request: %s' % (request)) result = 'OK' msg = '' try: ruletypeid = request['ruletypeid'] rulefileid = request['rule_file_id'] reqtypeid = request['request_type_id'] manageid = request['rule_manage_id'] now = datetime.datetime.now(pytz.timezone('UTC')) user = User.objects.get(user_id=request['apply_user_id']) # プロダクション環境以外のリクエストは拒否 if reqtypeid != PRODUCTION: msg = 'MOSJA03202' logger.system_log('LOSM12026', str(request['apply_user_id']), reqtypeid) raise Exception() # プロダクション環境データ作成処理 with transaction.atomic(): # ロック取得 ruleManageLock = RuleManage.objects.get(rule_manage_id=manageid) # データ作成状況チェック rcnt = RuleManage.objects.filter( rule_type_id=ruleManageLock.rule_type_id, request_type_id=ruleManageLock.request_type_id, rule_file_id=ruleManageLock.rule_file_id, operation_status=RULE_STS_OPERATION.PRODUCT ).count() if rcnt > 0: msg = 'MOSJA03201' logger.system_log('LOSM12027', str(request['apply_user_id']), ruleManageLock.rule_type_id, ruleManageLock.request_type_id, ruleManageLock.rule_file_id) raise Exception() # プロダクション環境データ作成 ruleManage = RuleManage( rule_type_id=ruletypeid, request_type_id=reqtypeid, rule_file_id=rulefileid, system_status=RULE_STS_SYSTEM.PRODUCT, operation_status=RULE_STS_OPERATION.PRODUCT_NOAPPLY, last_update_timestamp=now, last_update_user=user.user_name ) ruleManage.save(force_insert=True) request['rule_manage_id'] = ruleManage.rule_manage_id except User.DoesNotExist: result = 'NG' msg = 'MOSJA32010' logger.system_log('LOSM12068', traceback.format_exc()) except RuleManage.DoesNotExist: result = 'NG' msg = 'MOSJA03302' logger.system_log('LOSM12035', str(request['apply_user_id']), manageid, traceback.format_exc()) except Exception as e: result = 'NG' msg = msg if msg else 'MOSJA03018' logger.system_log('LOSM12069', traceback.format_exc()) ret_info = { 'result': result, 'msg': 'MOSJA03017' if result == 'OK' else msg, } return ret_info def apply(request): disconnect() logger.logic_log('LOSI00001', 'request: %s' % (request)) try: # データ取得 ruletypeid = request['ruletypeid'] groupid = request['groupid'] artifactid = request['artifactid'] rulefileid = request['rule_file_id'] reqtypeid = request['request_type_id'] manageid = request['rule_manage_id'] rulefile = RuleFile.objects.get(rule_file_id=rulefileid) filename = '%s_err.log' % (rulefile.rule_file_name.rsplit('.')[0]) errfilepath = '%s%s/%s/%s' % (request['rule_dstpath'], ruletypeid, rulefileid, filename) userlog = 'user_id=' + str(request['apply_user_id']) msg = '' data = {} data['release-id'] = {} now = datetime.datetime.now(pytz.timezone('UTC')) now_tz = conv_tz(now, 'Asia/Tokyo') user = User.objects.get(user_id=request['apply_user_id']) lang = user.get_lang_mode() ret_info = { 'result': 'OK', 'msg': msg, } if reqtypeid not in [PRODUCTION, STAGING]: errmessage = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03206', lang, reqtypeid=reqtypeid).replace('\n', '\n') + '\n' with open(errfilepath, 'a') as f: f.write(errmessage) ret_info = { 'result': 'NG', 'msg': 'MOSJA03202' } logger.system_log('LOSM12026', str(request['apply_user_id']), reqtypeid) logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info with transaction.atomic(): ruleManageLock = RuleManage.objects.get(rule_manage_id=manageid) if reqtypeid == PRODUCTION: rcnt = RuleManage.objects.filter( rule_type_id=ruleManageLock.rule_type_id, request_type_id=ruleManageLock.request_type_id, rule_file_id=ruleManageLock.rule_file_id, operation_status=RULE_STS_OPERATION.PRODUCT ).count() if rcnt > 0: msg = 'MOSJA03201' errmessage = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03201', lang) logger.system_log('LOSM12027', str(request['apply_user_id']), ruleManageLock.rule_type_id, ruleManageLock.request_type_id, ruleManageLock.rule_file_id) raise Exception(errmessage) # コンテナID取得 rule_type = RuleType.objects.select_for_update().get(rule_type_id=ruletypeid) # ルール適用管理検索 tmp_working_rule = RuleManage.objects.select_for_update().filter( rule_type_id=ruletypeid, request_type_id=reqtypeid) if reqtypeid == PRODUCTION: tmp_working_rule = tmp_working_rule.filter( system_status=RULE_STS_SYSTEM.PRODUCT_OK, operation_status=RULE_STS_OPERATION.PRODUCT ) elif reqtypeid == STAGING: tmp_working_rule = tmp_working_rule.filter( system_status=RULE_STS_SYSTEM.STAGING_OK, operation_status__in=[ RULE_STS_OPERATION.STAGING_NOTYET, RULE_STS_OPERATION.STAGING_VERIFY, RULE_STS_OPERATION.STAGING_NG, RULE_STS_OPERATION.STAGING ] ) old_manage_ids = list(tmp_working_rule.values_list('rule_manage_id', flat=True)) # 適用対象となるルール適用管理情報を取得 ruleManage = RuleManage.objects.get(rule_manage_id=manageid) if reqtypeid == PRODUCTION: ContID = rule_type.container_id_prefix_product oldContID = rule_type.current_container_id_product elif reqtypeid == STAGING: ContID = rule_type.container_id_prefix_staging oldContID = rule_type.current_container_id_staging # デプロイ実施 headers = { 'accept': 'application/json', 'content-type': 'application/json', } ContID = ContID + '_' + datetime.datetime.now(pytz.timezone('UTC')).strftime('%Y%m%d%H%M%S%f') data['container-id'] = ContID data['status'] = 'STARTED' data['release-id']['group-id'] = groupid data['release-id']['artifact-id'] = artifactid data['release-id']['version'] = rulefileid send_data = json.dumps(data) send_data = send_data.encode() PROTOCOL, IPADDRPORT, dmuser, dmpass = get_dm_conf() HTTP = '%s://%s/decision-central/rest/controller/management/servers/default-kieserver/containers/%s' % ( PROTOCOL, IPADDRPORT, ContID) response = requests.put(HTTP, headers=headers, data=send_data, auth=(dmuser, dmpass)) logger.system_log('LOSI12000', 'response: %s, ContID: %s' % (response, ContID)) # デプロイ失敗 if response.status_code != 201: ret_info = { 'result': 'NG', 'msg': 'MOSJA03204', } # システム処理状態更新 # 適用異常終了 if reqtypeid == PRODUCTION: ruleManage.system_status = RULE_STS_SYSTEM.PRODUCT_NG elif reqtypeid == STAGING: ruleManage.system_status = RULE_STS_SYSTEM.STAGING_NG ruleManage.last_update_timestamp = now ruleManage.last_update_user = user.user_name ruleManage.save(force_update=True) if response.status_code == 400: msg = 'MOSJA03208' errmessage = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03208', lang) logger.system_log('LOSM12029', str(request['apply_user_id']), reqtypeid, ContID) raise Exception(errmessage) elif response.status_code == 404: msg = 'MOSJA03209' errmessage = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03209', lang) logger.system_log('LOSM12030', str(request['apply_user_id']), reqtypeid, ContID) raise Exception(errmessage) else: msg = 'MOSJA03210' errmessage = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03210', lang) logger.system_log('LOSM12031', str(request['apply_user_id']), reqtypeid, ContID) raise Exception(errmessage) logger.system_log('LOSM12028', str(request['apply_user_id']), reqtypeid, ContID) # デプロイ成功 else: # 現コンテナID更新 if reqtypeid == PRODUCTION: RuleType.objects.filter( rule_type_id=ruletypeid ).update( current_container_id_product=ContID, last_update_timestamp=now, last_update_user=user.user_name ) elif reqtypeid == STAGING: RuleType.objects.filter( rule_type_id=ruletypeid ).update( current_container_id_staging=ContID, last_update_timestamp=now, last_update_user=user.user_name ) # システム処理状態更新 # 適用完了 if reqtypeid == PRODUCTION: ruleManage.system_status = RULE_STS_SYSTEM.PRODUCT_OK ruleManage.operation_status = RULE_STS_OPERATION.PRODUCT elif reqtypeid == STAGING: ruleManage.system_status = RULE_STS_SYSTEM.STAGING_OK ruleManage.operation_status = RULE_STS_OPERATION.STAGING_NOTYET ruleManage.last_update_timestamp = now ruleManage.last_update_user = user.user_name ruleManage.save(force_update=True) # 古いコンテナが存在する場合は削除 if oldContID: # スリープ処理 time.sleep(5) # 古いコンテナ削除 headers = { 'accept': 'application/json', 'content-type': 'application/json', } HTTP2 = '%s://%s/decision-central/rest/controller/management/servers/default-kieserver/containers/%s' % ( PROTOCOL, IPADDRPORT, oldContID) response2 = requests.delete(HTTP2, headers=headers, auth=(dmuser, dmpass)) logger.system_log('LOSI12000', 'response2: %s, oldContID: %s' % (response2, oldContID)) # プロダクション処理の場合 # システム処理状態更新 mod_sts = RULE_STS_OPERATION.STAGING_END if reqtypeid == PRODUCTION: mod_sts = RULE_STS_OPERATION.PRODUCT_END if len(old_manage_ids) > 0: RuleManage.objects.filter( rule_manage_id__in=old_manage_ids).exclude( rule_manage_id=manageid ).update( operation_status=mod_sts, last_update_timestamp=now, last_update_user=user.user_name ) if response2.status_code != 204: if response2.status_code == 400: msg = 'MOSJA03215' errmessage = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03215', lang) logger.system_log('LOSM12032', str(request['apply_user_id']), reqtypeid, ContID) raise Exception(errmessage) # コンテナ削除時の接続エラーはすでに削除済みであるためファイルに記載し、準正常とする。 elif response2.status_code == 404: errmessage = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03216', lang) + '\n' with open(errfilepath, 'a') as f: f.write(errmessage) logger.system_log('LOSM12033', str(request['apply_user_id']), reqtypeid, ContID) else: msg = 'MOSJA03217' errmessage = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03217', lang) logger.system_log('LOSM12034', str(request['apply_user_id']), reqtypeid, ContID) raise Exception(errmessage) # 世代管理 table_name = rule_type.rule_table_name dtcomp = DecisionTableComponent(table_name) dtcomp.set_rule_type_id(ruletypeid) if reqtypeid == PRODUCTION: production_generation = int(System.objects.get(config_id='PRODUCTION_GENERATION').value) if production_generation > 0: # プロダクション適用履歴管理の方を消す production_rules_queryset = RuleManage.objects.filter( rule_type_id=ruletypeid, request_type_id=reqtypeid ).filter( system_status=RULE_STS_SYSTEM.PRODUCT_OK ) p_rules_cnt = production_rules_queryset.count() if p_rules_cnt > production_generation: p_rules = list(production_rules_queryset.order_by('rule_manage_id').reverse()) p_rules_del = p_rules[production_generation:] logger.system_log('LOSI12007', ', '.join([str(r.rule_manage_id) for r in p_rules_del])) for p_rule_manage in p_rules_del: # ルールファイル削除 # ただしステージングで使用されているものはチェックして消さない p_rule_file_id = p_rule_manage.rule_file_id qs = RuleManage.objects.filter( rule_type_id=ruletypeid, request_type_id=STAGING, rule_file_id=p_rule_file_id) if qs.count() == 0: dstpath = '%s%s/%s/' % (request['rule_dstpath'], ruletypeid, p_rule_file_id) dtcomp.remove_component_related_one_file(dstpath) dtcomp.remove_mavenrepository_related_one_file(p_rule_file_id) else: logger.system_log('LOSM12058', p_rule_file_id) # manage削除 p_rule_manage.delete() # プロダクション適用中のエラーがあった方を消す RuleManage.objects.filter( rule_type_id=ruletypeid, request_type_id=reqtypeid ).filter( system_status=RULE_STS_SYSTEM.PRODUCT_NG ).delete() elif reqtypeid == STAGING: staging_generation = int(System.objects.get(config_id='STAGING_GENERATION').value) if staging_generation > 0: # ステージング削除 staging_rules_queryset = RuleManage.objects.filter( rule_type_id=ruletypeid, request_type_id=reqtypeid ).exclude( system_status__in=[ RULE_STS_SYSTEM.UPLOAD, RULE_STS_SYSTEM.UPLOAD_OK, RULE_STS_SYSTEM.BUILD, RULE_STS_SYSTEM.BUILD_OK, ]) s_rules_cnt = staging_rules_queryset.count() if s_rules_cnt > staging_generation: s_rules = list(staging_rules_queryset.order_by('rule_manage_id').reverse()) s_rules_del = s_rules[staging_generation:] logger.system_log('LOSI12008', ', '.join([str(r.rule_manage_id) for r in s_rules_del])) for s_rule_manage in s_rules_del: # ルールファイル削除 # ただしプロダクションで使用されているものはチェックして消さない s_rule_file_id = s_rule_manage.rule_file_id qs = RuleManage.objects.filter( rule_type_id=ruletypeid, request_type_id=PRODUCTION, rule_file_id=s_rule_file_id) if qs.count() == 0: dstpath = '%s%s/%s/' % (request['rule_dstpath'], ruletypeid, s_rule_file_id) dtcomp.remove_component_related_one_file(dstpath) dtcomp.remove_mavenrepository_related_one_file(s_rule_file_id) else: logger.system_log('LOSM12059', s_rule_manage.rule_file_id) # manage削除 s_rule_manage.delete() ret_info = { 'result': 'OK', 'msg': 'MOSJA03003', } except RuleFile.DoesNotExist: logger.system_log('LOSM12019', traceback.format_exc()) ret_info = { 'result': 'NG', 'msg': 'MOSJA03013', } except User.DoesNotExist: logger.system_log('LOSM12022', traceback.format_exc()) ret_info = { 'result': 'NG', 'msg': 'MOSJA32010', } except RuleManage.DoesNotExist: errmessage = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03218', lang, manageid=manageid).replace('\n', '\n') errmessage = errmessage + '\n' with open(errfilepath, 'a') as f: f.write(errmessage) logger.system_log('LOSM12035', str(request['apply_user_id']), manageid, traceback.format_exc()) ret_info = { 'result': 'NG', 'msg': 'MOSJA03302', } except Exception as e: try: rulemanage = RuleManage.objects.get(rule_manage_id=manageid) if reqtypeid == STAGING: rulemanage.system_status = RULE_STS_SYSTEM.STAGING_NG rulemanage.last_update_timestamp = now rulemanage.last_update_user = user.user_name rulemanage.save(force_update=True) elif reqtypeid == PRODUCTION: rulemanage.system_status = RULE_STS_SYSTEM.PRODUCT_NG rulemanage.last_update_timestamp = now rulemanage.last_update_user = user.user_name rulemanage.save(force_update=True) errmessage = str(now_tz) + ' ' + userlog + ' ' + get_message('MOSJA03219', lang).replace('\n', '\n') errmessage = errmessage + '\n' + str(now_tz) + ' ' + userlog + ' ' + str(e) + '\n' with open(errfilepath, 'a') as f: f.write(errmessage) logger.system_log('LOSM12036', str(request['apply_user_id']), reqtypeid, manageid, traceback.format_exc()) ret_info = { 'result': 'NG', 'msg': msg, } except Exception as e: logger.system_log('LOSM12036', str(request['apply_user_id']), reqtypeid, manageid, traceback.format_exc()) ret_info = { 'result': 'NG', 'msg': 'MOSJA03219', } logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info def download(request): logger.logic_log('LOSI00001', 'manageid: %s, ruletypeid: %s' % (request['rule_manage_id'], request['ruletypeid'])) manageid = request['rule_manage_id'] ruletypeid = request['ruletypeid'] testrequestflag = request['file_name_expansion'] rule_file_id, rule_filename, rule_table_name, errmsg = _get_downloadfile_info( ruletypeid, manageid, testrequestflag, request) ret_info = { 'result': 'OK', 'msg': 'OK', 'filename': rule_filename, 'filedata': '', } if errmsg: ret_info.update( result='NG', msg=errmsg, filename='', filedata='', ) logger.system_log('LOSM12037', ruletypeid, manageid) logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info # テストリクエスト用エクセルDLの場合 if len(request['file_name_expansion']) > 0: dtcomp = DecisionTableComponent(rule_table_name) dtcomp.set_rule_type_id(ruletypeid) dtcomp.set_path() rule_filepath = dtcomp.get_dtable_path() + rule_filename ret_info['filename'] = rule_filename else: # ルールファイル読み込み rule_filepath = request['rule_filepath'] % (ruletypeid, rule_file_id) + rule_table_name + '/' + rule_filename if os.path.exists(rule_filepath): with open(rule_filepath, 'rb') as fp: ruledata = base64.b64encode(fp.read()).decode('utf-8') ret_info.update(filedata=ruledata) else: ret_info.update( result='NG', msg='MOSJA03304', filename='', filedata='' ) logger.system_log('LOSM12038', rule_filepath) logger.logic_log('LOSI00002', 'result: %s, msg: %s, filename: %s' % (ret_info['result'], ret_info['msg'], ret_info['filename'])) return ret_info def download_zip(request): """ [概要] excelファイルとエラーログファイルをまとめたzipファイルをダウンロード """ logger.logic_log('LOSI00001','manageid: %s, ruletypeid: %s' % (request['rule_manage_id'], request['ruletypeid'])) with DOWNLOAD_LOCK: manageid = request['rule_manage_id'] ruletypeid = request['ruletypeid'] rule_file_id, rule_filename, rule_table_name, errmsg = _get_downloadfile_info( ruletypeid, manageid, '', request=request) ret_info = { 'result': 'OK', 'msg': 'OK', 'filename': rule_filename, 'filedata': '', } if errmsg: ret_info.update( result='NG', msg=errmsg, filename='', filedata='' ) logger.system_log('LOSM12037', ruletypeid, manageid) logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info # excelファイルパス, errorlogファイルパス,保存先パスをset rule_filename_body = rule_filename.split('.')[0] rule_filepath = request['rule_filepath'] % (ruletypeid, rule_file_id) + rule_table_name + '/' + rule_filename dstpath = '%s%s/%s/' % (request['rule_dstpath'], ruletypeid, rule_file_id) errlog_filepath = dstpath + rule_filename_body + '_err.log' # zipファイルを取得 zip_filename = rule_filename_body + '.zip' filepath = _get_zipfile(rule_filepath, errlog_filepath, dstpath, zip_filename) if os.path.exists(filepath): # zipファイルを読み込みデータを返す with open(filepath, 'rb') as fp: ruledata = base64.b64encode(fp.read()).decode('utf-8') ret_info.update( filename=zip_filename, filedata=ruledata ) else: ret_info.update( result='NG', msg='MOSJA03304', filename='', filedata='' ) logger.system_log('LOSM12038', filepath) logger.logic_log('LOSI00002', 'result: %s, msg: %s, filename: %s' % (ret_info['result'], ret_info['msg'], ret_info['filename'])) return ret_info def _get_downloadfile_info(ruletypeid, manageid, testrequestflag, request): """ [概要] dtまたはdtとエラーログをまとめたzipファイルに必要な情報を取得 [引数] ruletypeid : ルール種別id manageid : ルール管理id [戻り値] rule_file_id : ルール管理id rule_filename : ルールファイル名 msg : エラーメッセージ """ disconnect() # ルール種別情報を取得 logger.logic_log('LOSI00001', 'ruletypeid: %s, manageid: %s' % (ruletypeid, manageid)) ruletype = '' artifactid = '' try: ruletype = RuleType.objects.get(pk=ruletypeid) artifactid = ruletype.artifact_id rule_table_name = ruletype.rule_table_name except BaseException: logger.system_log('LOSM12039', ruletypeid, traceback.format_exc()) logger.logic_log('LOSI00002', "'', '', '', '', 'MOSJA03301'") return '', '', '', 'MOSJA03301' # ルールファイル情報を取得 try: rule_file_id = RuleManage.objects.get(rule_manage_id=manageid).rule_file_id rule_filename = RuleFile.objects.get(pk=rule_file_id).rule_file_name # テストリクエスト用エクセルDLの場合 if len(testrequestflag) > 0: rule_filename = rule_table_name + testrequestflag except RuleManage.DoesNotExist: logger.system_log('LOSM12040', manageid, traceback.format_exc()) logger.logic_log('LOSI00002', 'ruletypeid: %s' % ruletypeid) return '', '', '', 'MOSJA03302' except RuleFile.DoesNotExist: logger.system_log('LOSM12041', rule_file_id, traceback.format_exc()) logger.logic_log('LOSI00002', 'ruletypeid: %s' % ruletypeid) return '', '', '', 'MOSJA03303' logger.logic_log('LOSI00002', 'rule_id: %s, rule_filename: %s, msg: None' % (rule_file_id, rule_filename)) return rule_file_id, rule_filename, rule_table_name, None def _get_zipfile(rule_filepath, errlog_filepath, dstpath, filename): """ [概要] 引数の情報からzipファイルを作成してzipファイルパスを返す ファイルが存在しない場合は return None [引数] rule_filepath : ルールファイルのパス errlog_filepath : エラーログファイルのパス dstpath : 保存先のパス filename : 保存ファイル名 """ disconnect() logger.logic_log('LOSI00001', 'rule_filepath: %s, errlog_filepath: %s, dstpath: %s, filename: %s' % (rule_filepath, errlog_filepath, dstpath, filename)) filepath = dstpath + filename #zipファイルが存在する場合は削除する if os.path.exists(filepath): os.remove(filepath) #zipファイルを作成する with zipfile.ZipFile(filepath, 'w', compression=zipfile.ZIP_DEFLATED) as new_zip: if os.path.exists(errlog_filepath): new_zip.write(errlog_filepath, arcname=os.path.basename(errlog_filepath)) if os.path.exists(rule_filepath): new_zip.write(rule_filepath, arcname=os.path.basename(rule_filepath)) logger.logic_log('LOSI00002', 'filepath: %s' % filepath) return filepath def download_dt(request): disconnect() logger.logic_log('LOSI00001', request) filename = '' ruledata = '' ruletypeid = int(request['ruletypeid']) try: ruletype = RuleType.objects.get(rule_type_id=ruletypeid) except RuleType.DoesNotExist: logger.system_log('LOSM12039', ruletypeid, traceback.format_exc()) ret_info = { 'result': 'NG', 'msg': 'MOSJA03302', 'filename': '', 'filedata': '', } logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info dtcomp = DecisionTableComponent(ruletype.rule_table_name) dtcomp.set_rule_type_id(ruletypeid) dtcomp.set_path(src_path=rule_path['rule_srcpath'], root_path=('%s%s/' % (request['rule_rootpath'], ruletypeid))) rule_filepath = dtcomp.get_dtable_path() filename = '%s.xlsx' % (ruletype.rule_table_name) # ルールファイル読み込み filepath = rule_filepath + filename if not os.path.exists(filepath): ret_info = { 'result': 'NG', 'msg': 'MOSJA03304', 'filename': '', 'filedata': '', } logger.system_log('LOSM12038', filepath) logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info # ルールファイルのアクション種別の選択肢を更新する ruledata = None try: customizer = DecisionTableCustomizer(filepath) customizer.custom_action_type() ruledata = customizer.output() except Exception as e: logger.system_log('LOSM12065', 'error: %s' % e) logger.logic_log('LOSI00005', traceback.format_exc()) if not ruledata: ret_info = { 'result': 'NG', 'msg': 'MOSJA03304', 'filename': '', 'filedata': '', } logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info ruledata = base64.b64encode(ruledata).decode('utf-8') ret_info = { 'result': 'OK', 'msg': 'OK', 'filename': filename, 'filedata': ruledata, } logger.logic_log('LOSI00002', 'result: %s, msg: %s, filename: %s' % (ret_info['result'], ret_info['msg'], ret_info['filename'])) return ret_info def get_dm_conf(): """ [概要] DecisionManagerの設定値を取得する [戻り値] protocol : str プロトコル ipaddress : str ipアドレス dmuser : str DecisionManagerのユーザ名 dmpass : str DecisionManagerのパスワード """ logger.logic_log('LOSI00001', 'None') rset = list(System.objects.filter(category='DMSETTINGS').values('config_id', 'value')) dmconf = {r['config_id']: r['value'] for r in rset} # passwordを復号 cipher = AESCipher(settings.AES_KEY) dmconf['DM_PASSWD'] = cipher.decrypt(dmconf['DM_PASSWD']) protocol = dmconf["DM_PROTOCOL"] ipaddrport = dmconf["DM_IPADDRPORT"] dmuser = dmconf["DM_USERID"] dmpass = dmconf["DM_PASSWD"] logger.logic_log( 'LOSI00002', '(protocol, ipaddrport, dmuser, dmpass) = (%s, %s, %s, %s)' % (protocol, ipaddrport, dmuser, dmpass)) return protocol, ipaddrport, dmuser, dmpass def delete(request): disconnect() logger.logic_log('LOSI00001', request) msg = '' now = datetime.datetime.now(pytz.timezone('UTC')) user_name = User.objects.get(user_id=request['user_id']).user_name ret_info = { 'result': 'OK', 'msg': '', } try: with transaction.atomic(): ruletypeid = int(request['ruletypeid']) rule_type = RuleType.objects.select_for_update().get(rule_type_id=ruletypeid) ######################################### # コンテナ削除 ######################################### headers = { 'accept': 'application/json', 'content-type': 'application/json', } # コンテナID取得 product_ContID = rule_type.current_container_id_product staging_ContID = rule_type.current_container_id_staging PROTOCOL, IPADDRPORT, dmuser, dmpass = get_dm_conf() if product_ContID is not None: HTTP2 = '%s://%s/decision-central/rest/controller/management/servers/default-kieserver/containers/%s' % ( PROTOCOL, IPADDRPORT, product_ContID) response2 = requests.delete(HTTP2, headers=headers, auth=(dmuser, dmpass)) logger.system_log('LOSI12000', 'response2: %s, product_ContID: %s' % (response2, product_ContID)) if response2.status_code != 204 and response2.status_code != 404: msg = 'MOSJA03607' logger.system_log('LOSM12071', 'response2: %s, product_ContID: %s' % (response2, product_ContID)) raise Exception() if staging_ContID is not None: HTTP2 = '%s://%s/decision-central/rest/controller/management/servers/default-kieserver/containers/%s' % ( PROTOCOL, IPADDRPORT, staging_ContID) response2 = requests.delete(HTTP2, headers=headers, auth=(dmuser, dmpass)) logger.system_log('LOSI12000', 'response2: %s, staging_ContID: %s' % (response2, staging_ContID)) if response2.status_code != 204 and response2.status_code != 404: msg = 'MOSJA03607' logger.system_log('LOSM12071', 'response2: %s, staging_ContID: %s' % (response2, staging_ContID)) raise Exception() ######################################### # MRディレクトリ削除 ######################################### dtcomp = DecisionTableComponent(rule_type.rule_table_name) if ruletypeid > 0: dtcomp.remove_mavenrepository() ######################################### # DTディレクトリ削除 ######################################### if ruletypeid > 0: dtcomp.remove_component(ruletypeid) ######################################### # アクセス権限管理レコード削除 ######################################### try: ap_list = AccessPermission.objects.filter(rule_type_id=ruletypeid) for a in ap_list: a.disuse_flag = 1 a.last_update_user = user_name a.last_update_timestamp = now a.save(force_update=True) except Exception as e: msg = 'MOSJA03605' logger.system_log('LOSM12066', ruletypeid, traceback.format_exc()) raise Exception() ######################################### # ルール適用管理レコード削除 ######################################### try: RuleManage.objects.filter(rule_type_id=ruletypeid).delete() except Exception as e: msg = 'MOSJA03601' logger.system_log('LOSM12042', ruletypeid, traceback.format_exc()) raise Exception() ######################################### # ルールファイル情報管理レコード削除 ######################################### try: RuleFile.objects.filter(rule_type_id=ruletypeid).delete() except Exception as e: msg = 'MOSJA03602' logger.system_log('LOSM12043', ruletypeid, traceback.format_exc()) raise Exception() ######################################### # データオブジェクト管理レコード削除 ######################################### try: DataObject.objects.filter(rule_type_id=ruletypeid).delete() except Exception as e: msg = 'MOSJA03603' logger.system_log('LOSM12044', ruletypeid, traceback.format_exc()) raise Exception() ######################################### # ルール種別管理レコード削除 ######################################### try: rule_type.disuse_flag = 1 rule_type.rule_type_name = rule_type.rule_type_name + '_deleted_' + now.strftime('%Y%m%d%H%M%s') rule_type.rule_table_name = rule_type.rule_table_name + '_deleted_' + now.strftime('%Y%m%d%H%M%s') rule_type.last_update_user = user_name rule_type.last_update_timestamp = now rule_type.save(force_update=True) except Exception as e: msg = 'MOSJA03604' logger.system_log('LOSM12045', ruletypeid, traceback.format_exc()) raise Exception() except RuleType.DoesNotExist: logger.system_log('LOSM12039', ruletypeid, traceback.format_exc()) ret_info = { 'result': 'NG', 'msg': 'MOSJA03301', } except Exception as e: if not msg: logger.system_log('LOSM00001', traceback.format_exc()) msg = 'MOSJA03217' ret_info = { 'result': 'NG', 'msg': msg, } logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info def build_kjar(request): disconnect() logger.logic_log('LOSI00001', request) logger.logic_log('LOSI12001') with APPLY_LOCK: logger.logic_log('LOSI12002') try: # データ取得 now = datetime.datetime.now(pytz.timezone('UTC')) now_tz = conv_tz(now, 'Asia/Tokyo') user = User.objects.get(user_id=request['apply_user_id']) ruletypeid = request['ruletypeid'] ruleid = request['rule_file_id'] artifactid = request['artifactid'] groupid = request['groupid'] filepath = request['pompath'] + 'pom.xml' reqtypeid = request['request_type_id'] manageid = request['rule_manage_id'] rulefile = RuleFile.objects.get(rule_file_id=ruleid) filename = '%s_err.log' % (rulefile.rule_file_name.rsplit('.')[0]) errfilepath = request['pompath'] + filename userlog = 'user_id=' + str(request['apply_user_id']) # システム処理状態更新 try: with transaction.atomic(): ruleManage = RuleManage.objects.select_for_update().get(rule_manage_id=manageid) ruleManage.system_status = RULE_STS_SYSTEM.BUILD ruleManage.last_update_timestamp = now ruleManage.last_update_user = user.user_name ruleManage.save(force_update=True) except Exception as e: RuleManage.objects.filter( rule_manage_id=manageid ).update( system_status=RULE_STS_SYSTEM.BUILD_NG, last_update_timestamp=now, last_update_user=user.user_name ) errmessage = str(now_tz) + ' ' + userlog + ' ' + \ get_message('MOSJA03404', user.get_lang_mode()).replace('\n', '\n') errmessage = errmessage + '\n' + str(now_tz) + ' ' + userlog + ' ' + str(e) + '\n' with open(errfilepath, 'a') as f: f.write(errmessage) logger.system_log('LOSM12046', str(request['apply_user_id']), reqtypeid, manageid, traceback.format_exc()) ret_info = { 'result': 'NG', 'msg': 'MOSJA03401', } logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info # pomファイル編集 regex_groupid = r'<groupId>.*</groupId>' regex_artifactid = r'<artifactId>.*</artifactId>' regex_version = r'<version>.*</version>' with open(filepath, 'r+') as fp: pom_xml = fp.read() pom_xml = re.sub(regex_groupid, '<groupId>%s</groupId>' % (groupid), pom_xml, 1) pom_xml = re.sub(regex_artifactid, '<artifactId>%s</artifactId>' % (artifactid), pom_xml, 1) pom_xml = re.sub(regex_version, '<version>%s</version>' % (ruleid), pom_xml, 1) fp.seek(0) fp.write(pom_xml) fp.truncate() # ビルド実行 exec_cmd = [] exec_cmd.append('mvn') exec_cmd.append('install') exec_cmd.append('-Ddrools.dateformat=yyyy-MM-dd HH:mm') exec_cmd.append('-f') exec_cmd.append(filepath) ret = subprocess.run(exec_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # システム処理状態更新 sys_sts = RULE_STS_SYSTEM.BUILD_OK if ret.returncode == 0 else RULE_STS_SYSTEM.BUILD_NG try: with transaction.atomic(): ruleManage = RuleManage.objects.select_for_update().get(rule_manage_id=manageid) ruleManage.system_status = sys_sts ruleManage.last_update_timestamp = now ruleManage.last_update_user = user.user_name ruleManage.save(force_update=True) except Exception as e: RuleManage.objects.filter( rule_manage_id=manageid).update( system_status=RULE_STS_SYSTEM.BUILD_NG, last_update_timestamp=now, last_update_user=user.user_name) errmessage = str(now_tz) + ' ' + userlog + ' ' + \ get_message('MOSJA03405', user.get_lang_mode()).replace('\n', '\n') errmessage = errmessage + '\n' + str(now_tz) + ' ' + userlog + ' ' + str(e) + '\n' with open(errfilepath, 'a') as f: f.write(errmessage) logger.system_log('LOSM12047', str(request['apply_user_id']), reqtypeid, manageid, traceback.format_exc()) ret_info = { 'result': 'NG', 'msg': 'MOSJA03402', } logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info if ret.returncode != 0: ruleManage.system_status = RULE_STS_SYSTEM.BUILD_NG ruleManage.last_update_timestamp = now ruleManage.last_update_user = user.user_name ruleManage.save(force_update=True) errmessage = str(now_tz) + ' ' + userlog + ' ' + \ get_message('MOSJA03406', user.get_lang_mode()).replace('\n', '\n') errmessage = errmessage + '\n' + str(now_tz) + ' ' + userlog + ' ' + ret.stdout.decode("utf8") + '\n' with open(errfilepath, 'a') as f: f.write(errmessage) logger.system_log('LOSM12048', str(request['apply_user_id']), reqtypeid, manageid, ret.returncode) ret_info = { 'result': 'NG', 'msg': 'MOSJA03403', } logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info except User.DoesNotExist: ret_info = { 'result': 'NG', 'msg': 'MOSJA03101', } logger.system_log('LOSM12022', traceback.format_exc()) logger.logic_log('LOSI00002', ret_info) return ret_info except RuleFile.DoesNotExist: ret_info = { 'result': 'NG', 'msg': 'MOSJA03013', } logger.system_log('LOSM12019', traceback.format_exc()) logger.logic_log('LOSI00002', ret_info) return ret_info except Exception as e: RuleManage.objects.filter( rule_manage_id=manageid).update( system_status=RULE_STS_SYSTEM.BUILD_NG, last_update_timestamp=now, last_update_user=user.user_name) errmessage = str(now_tz) + ' ' + userlog + ' ' + \ get_message('MOSJA03406', user.get_lang_mode()).replace('\n', '\n') errmessage = errmessage + '\n' + str(now_tz) + ' ' + userlog + ' ' + str(e) + '\n' with open(errfilepath, 'a') as f: f.write(errmessage) logger.system_log('LOSM12048', str(request['apply_user_id']), reqtypeid, manageid, traceback.format_exc()) ret_info = { 'result': 'NG', 'msg': 'MOSJA03403', } logger.logic_log('LOSI00002', 'ret_info: %s' % ret_info) return ret_info logger.logic_log('LOSI12003') res = apply(request) logger.logic_log('LOSI00002', 'res: %s' % res) return res # ルールファイル関連パス取得 def load_filepath(): disconnect() logger.logic_log('LOSI00001', 'None') rule_path = {} rule_path['rule_rootpath'] = '' rule_path['rule_srcpath'] = '' rule_path['rule_dstpath'] = '' rule_path['rule_filepath'] = '' # "System" != "os.system" | OASE_T_SYSTEM => System(model) class system_list = System.objects.filter(Q(config_id='RULEFILE_ROOTPATH') | Q(config_id='RULEFILE_SRCPATH')) for system in system_list: if system.config_id == 'RULEFILE_ROOTPATH': rule_path['rule_rootpath'] = system.value if not rule_path['rule_rootpath'].endswith('/'): rule_path['rule_rootpath'] = '%s/' % (rule_path['rule_rootpath']) rule_path['rule_dstpath'] = rule_path['rule_rootpath'] rule_path['rule_filepath'] = '%s%%s/%%s/%s' % (rule_path['rule_dstpath'], 'src/main/resources/com/oase/') elif system.config_id == 'RULEFILE_SRCPATH': rule_path['rule_srcpath'] = '%s%s' % (settings.BASE_DIR, system.value) logger.logic_log('LOSI00002', 'rule_path: %s' % rule_path) return rule_path def load_settings(): """ [メソッド概要] 適用君設定情報を読み込む """ disconnect() logger.logic_log('LOSI00001', 'None') apply_settings = {} apply_settings['host'] = '127.0.0.1' apply_settings['port'] = 50001 rset = list(System.objects.filter(category='APPLYSETTINGS').values('config_id', 'value')) for r in rset: if r['config_id'] == 'APPLY_IPADDRPORT': apval = r['value'] apval = apval.split(':') if len(apval) == 2: apply_settings['host'] = apval[0] apply_settings['port'] = int(apval[1]) logger.logic_log('LOSI00002', 'apply_settings: %s' % apply_settings) return apply_settings if __name__ == '__main__': logger.logic_log('LOSI00001', 'None') apply_settings = load_settings() host = apply_settings['host'] port = apply_settings['port'] func_info = { 'CREATE': {'func': create, 'thread': None, 'use_recv': False, 'need_keys': ['result', 'msg']}, 'UPLOAD': {'func': upload, 'thread': build_kjar, 'use_recv': False, 'need_keys': ['result', 'msg']}, 'APPLY': {'func': apply_req, 'thread': apply, 'use_recv': True, 'need_keys': ['result', 'msg']}, 'DOWNLOAD' : {'func':download, 'thread':None, 'use_recv':False, 'need_keys':['result', 'msg', 'filename', 'filedata']}, 'DOWNLOAD_ZIP': {'func':download_zip, 'thread':None, 'use_recv':False, 'need_keys':['result', 'msg', 'filename', 'filedata']}, 'DOWNLOAD_DT' : {'func':download_dt, 'thread':None, 'use_recv':False, 'need_keys':['result', 'msg', 'filename', 'filedata']}, 'DELETE': {'func': delete, 'thread': None, 'use_recv': False, 'need_keys': ['result', 'msg']}, } with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 8192) sock.bind((host, port)) sock.listen(5) logger.logic_log('LOSI12004') while True: try: logger.logic_log('LOSI12005', host, port) recv_data = bytes(b'') clientsocket, (client_address, client_port) = sock.accept() logger.logic_log('LOSI12006', client_address, client_port) with clientsocket: while True: rcvtmp = clientsocket.recv(4096) if not rcvtmp: logger.logic_log('LOSI12013', len(recv_data)) break recv_data = b'%s%s' % (recv_data, rcvtmp) rule_path = load_filepath() recv_data = recv_data.decode() recv_data = json.loads(recv_data) recv_data.update(rule_path) need_keys = [] send_data = {} if recv_data['request'] in func_info: need_keys = func_info[recv_data['request']]['need_keys'] send_data = func_info[recv_data['request']]['func'](recv_data) req_data = recv_data if not func_info[recv_data['request']]['use_recv']: req_data = make_send_data(send_data, omit_keys=['result', 'msg']) req_data.update(rule_path) if func_info[recv_data['request']]['thread']: if 'result' in send_data and send_data['result'] == 'OK': thrd = threading.Thread( target=func_info[recv_data['request']]['thread'], args=(req_data,)) thrd.start() else: logger.system_log('LOSM12049', 'request: %s' % recv_data['request']) need_keys = ['result', 'msg'] send_data = { 'result': 'NG', 'msg': 'MOSJA03001' } send_data = make_send_data(send_data, need_keys=need_keys) ret_info = send_data send_data = json.dumps(send_data) send_data = send_data.encode() clientsocket.sendall(send_data) clientsocket.shutdown(socket.SHUT_RDWR) clientsocket.close() logger.logic_log('LOSI00002', 'result: %s, msg: %s' % (ret_info['result'], ret_info['msg'])) except Exception as e: logger.system_log('LOSM12049', traceback.format_exc()) logger.logic_log('LOSI00002', 'apply_settings: %s' % apply_settings) sock.close()
conftest.py
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2020 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser Public License for more details. # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. import datetime import os import sys import re from collections import defaultdict from queue import Queue from threading import Thread, Event from time import sleep import pytest from telegram import (Bot, Message, User, Chat, MessageEntity, Update, InlineQuery, CallbackQuery, ShippingQuery, PreCheckoutQuery, ChosenInlineResult) from telegram.ext import Dispatcher, JobQueue, Updater, BaseFilter, Defaults from telegram.utils.helpers import _UtcOffsetTimezone from tests.bots import get_bot GITHUB_ACTION = os.getenv('GITHUB_ACTION', False) if GITHUB_ACTION: pytest_plugins = ['tests.plugin_github_group'] # THIS KEY IS OBVIOUSLY COMPROMISED # DO NOT USE IN PRODUCTION! PRIVATE_KEY = b"-----BEGIN RSA PRIVATE KEY-----\r\nMIIEowIBAAKCAQEA0AvEbNaOnfIL3GjB8VI4M5IaWe+GcK8eSPHkLkXREIsaddum\r\nwPBm/+w8lFYdnY+O06OEJrsaDtwGdU//8cbGJ/H/9cJH3dh0tNbfszP7nTrQD+88\r\nydlcYHzClaG8G+oTe9uEZSVdDXj5IUqR0y6rDXXb9tC9l+oSz+ShYg6+C4grAb3E\r\nSTv5khZ9Zsi/JEPWStqNdpoNuRh7qEYc3t4B/a5BH7bsQENyJSc8AWrfv+drPAEe\r\njQ8xm1ygzWvJp8yZPwOIYuL+obtANcoVT2G2150Wy6qLC0bD88Bm40GqLbSazueC\r\nRHZRug0B9rMUKvKc4FhG4AlNzBCaKgIcCWEqKwIDAQABAoIBACcIjin9d3Sa3S7V\r\nWM32JyVF3DvTfN3XfU8iUzV7U+ZOswA53eeFM04A/Ly4C4ZsUNfUbg72O8Vd8rg/\r\n8j1ilfsYpHVvphwxaHQlfIMa1bKCPlc/A6C7b2GLBtccKTbzjARJA2YWxIaqk9Nz\r\nMjj1IJK98i80qt29xRnMQ5sqOO3gn2SxTErvNchtBiwOH8NirqERXig8VCY6fr3n\r\nz7ZImPU3G/4qpD0+9ULrt9x/VkjqVvNdK1l7CyAuve3D7ha3jPMfVHFtVH5gqbyp\r\nKotyIHAyD+Ex3FQ1JV+H7DkP0cPctQiss7OiO9Zd9C1G2OrfQz9el7ewAPqOmZtC\r\nKjB3hUECgYEA/4MfKa1cvaCqzd3yUprp1JhvssVkhM1HyucIxB5xmBcVLX2/Kdhn\r\nhiDApZXARK0O9IRpFF6QVeMEX7TzFwB6dfkyIePsGxputA5SPbtBlHOvjZa8omMl\r\nEYfNa8x/mJkvSEpzvkWPascuHJWv1cEypqphu/70DxubWB5UKo/8o6cCgYEA0HFy\r\ncgwPMB//nltHGrmaQZPFT7/Qgl9ErZT3G9S8teWY4o4CXnkdU75tBoKAaJnpSfX3\r\nq8VuRerF45AFhqCKhlG4l51oW7TUH50qE3GM+4ivaH5YZB3biwQ9Wqw+QyNLAh/Q\r\nnS4/Wwb8qC9QuyEgcCju5lsCaPEXZiZqtPVxZd0CgYEAshBG31yZjO0zG1TZUwfy\r\nfN3euc8mRgZpSdXIHiS5NSyg7Zr8ZcUSID8jAkJiQ3n3OiAsuq1MGQ6kNa582kLT\r\nFPQdI9Ea8ahyDbkNR0gAY9xbM2kg/Gnro1PorH9PTKE0ekSodKk1UUyNrg4DBAwn\r\nqE6E3ebHXt/2WmqIbUD653ECgYBQCC8EAQNX3AFegPd1GGxU33Lz4tchJ4kMCNU0\r\nN2NZh9VCr3nTYjdTbxsXU8YP44CCKFG2/zAO4kymyiaFAWEOn5P7irGF/JExrjt4\r\nibGy5lFLEq/HiPtBjhgsl1O0nXlwUFzd7OLghXc+8CPUJaz5w42unqT3PBJa40c3\r\nQcIPdQKBgBnSb7BcDAAQ/Qx9juo/RKpvhyeqlnp0GzPSQjvtWi9dQRIu9Pe7luHc\r\nm1Img1EO1OyE3dis/rLaDsAa2AKu1Yx6h85EmNjavBqP9wqmFa0NIQQH8fvzKY3/\r\nP8IHY6009aoamLqYaexvrkHVq7fFKiI6k8myMJ6qblVNFv14+KXU\r\n-----END RSA PRIVATE KEY-----" # noqa: E501 @pytest.fixture(scope='session') def bot_info(): return get_bot() @pytest.fixture(scope='session') def bot(bot_info): return make_bot(bot_info) DEFAULT_BOTS = {} @pytest.fixture(scope='function') def default_bot(request, bot_info): param = request.param if hasattr(request, 'param') else {} defaults = Defaults(**param) default_bot = DEFAULT_BOTS.get(defaults) if default_bot: return default_bot else: default_bot = make_bot(bot_info, **{'defaults': defaults}) DEFAULT_BOTS[defaults] = default_bot return default_bot @pytest.fixture(scope='session') def chat_id(bot_info): return bot_info['chat_id'] @pytest.fixture(scope='session') def super_group_id(bot_info): return bot_info['super_group_id'] @pytest.fixture(scope='session') def channel_id(bot_info): return bot_info['channel_id'] @pytest.fixture(scope='session') def provider_token(bot_info): return bot_info['payment_provider_token'] def create_dp(bot): # Dispatcher is heavy to init (due to many threads and such) so we have a single session # scoped one here, but before each test, reset it (dp fixture below) dispatcher = Dispatcher(bot, Queue(), job_queue=JobQueue(), workers=2, use_context=False) dispatcher.job_queue.set_dispatcher(dispatcher) thr = Thread(target=dispatcher.start) thr.start() sleep(2) yield dispatcher sleep(1) if dispatcher.running: dispatcher.stop() thr.join() @pytest.fixture(scope='session') def _dp(bot): for dp in create_dp(bot): yield dp @pytest.fixture(scope='function') def dp(_dp): # Reset the dispatcher first while not _dp.update_queue.empty(): _dp.update_queue.get(False) _dp.chat_data = defaultdict(dict) _dp.user_data = defaultdict(dict) _dp.bot_data = {} _dp.persistence = None _dp.handlers = {} _dp.groups = [] _dp.error_handlers = [] _dp.__stop_event = Event() _dp.__exception_event = Event() _dp.__async_queue = Queue() _dp.__async_threads = set() _dp.persistence = None _dp.use_context = False if _dp._Dispatcher__singleton_semaphore.acquire(blocking=0): Dispatcher._set_singleton(_dp) yield _dp Dispatcher._Dispatcher__singleton_semaphore.release() @pytest.fixture(scope='function') def cdp(dp): dp.use_context = True yield dp dp.use_context = False @pytest.fixture(scope='function') def updater(bot): up = Updater(bot=bot, workers=2) yield up if up.running: up.stop() @pytest.fixture(scope='function') def thumb_file(): f = open(u'tests/data/thumb.jpg', 'rb') yield f f.close() @pytest.fixture(scope='class') def class_thumb_file(): f = open(u'tests/data/thumb.jpg', 'rb') yield f f.close() def pytest_configure(config): if sys.version_info >= (3,): config.addinivalue_line('filterwarnings', 'ignore::ResourceWarning') # TODO: Write so good code that we don't need to ignore ResourceWarnings anymore def make_bot(bot_info, **kwargs): return Bot(bot_info['token'], private_key=PRIVATE_KEY, **kwargs) CMD_PATTERN = re.compile(r'/[\da-z_]{1,32}(?:@\w{1,32})?') DATE = datetime.datetime.now() def make_message(text, **kwargs): """ Testing utility factory to create a fake ``telegram.Message`` with reasonable defaults for mimicking a real message. :param text: (str) message text :return: a (fake) ``telegram.Message`` """ return Message(message_id=1, from_user=kwargs.pop('user', User(id=1, first_name='', is_bot=False)), date=kwargs.pop('date', DATE), chat=kwargs.pop('chat', Chat(id=1, type='')), text=text, bot=kwargs.pop('bot', make_bot(get_bot())), **kwargs) def make_command_message(text, **kwargs): """ Testing utility factory to create a message containing a single telegram command. Mimics the Telegram API in that it identifies commands within the message and tags the returned ``Message`` object with the appropriate ``MessageEntity`` tag (but it does this only for commands). :param text: (str) message text containing (or not) the command :return: a (fake) ``telegram.Message`` containing only the command """ match = re.search(CMD_PATTERN, text) entities = [MessageEntity(type=MessageEntity.BOT_COMMAND, offset=match.start(0), length=len(match.group(0)))] if match else [] return make_message(text, entities=entities, **kwargs) def make_message_update(message, message_factory=make_message, edited=False, **kwargs): """ Testing utility factory to create an update from a message, as either a ``telegram.Message`` or a string. In the latter case ``message_factory`` is used to convert ``message`` to a ``telegram.Message``. :param message: either a ``telegram.Message`` or a string with the message text :param message_factory: function to convert the message text into a ``telegram.Message`` :param edited: whether the message should be stored as ``edited_message`` (vs. ``message``) :return: ``telegram.Update`` with the given message """ if not isinstance(message, Message): message = message_factory(message, **kwargs) update_kwargs = {'message' if not edited else 'edited_message': message} return Update(0, **update_kwargs) def make_command_update(message, edited=False, **kwargs): """ Testing utility factory to create an update from a message that potentially contains a command. See ``make_command_message`` for more details. :param message: message potentially containing a command :param edited: whether the message should be stored as ``edited_message`` (vs. ``message``) :return: ``telegram.Update`` with the given message """ return make_message_update(message, make_command_message, edited, **kwargs) @pytest.fixture(scope='function') def mock_filter(): class MockFilter(BaseFilter): def __init__(self): self.tested = False def filter(self, message): self.tested = True return MockFilter() def get_false_update_fixture_decorator_params(): message = Message(1, User(1, '', False), DATE, Chat(1, ''), text='test') params = [ {'callback_query': CallbackQuery(1, User(1, '', False), 'chat', message=message)}, {'channel_post': message}, {'edited_channel_post': message}, {'inline_query': InlineQuery(1, User(1, '', False), '', '')}, {'chosen_inline_result': ChosenInlineResult('id', User(1, '', False), '')}, {'shipping_query': ShippingQuery('id', User(1, '', False), '', None)}, {'pre_checkout_query': PreCheckoutQuery('id', User(1, '', False), '', 0, '')}, {'callback_query': CallbackQuery(1, User(1, '', False), 'chat')} ] ids = tuple(key for kwargs in params for key in kwargs) return {'params': params, 'ids': ids} @pytest.fixture(scope='function', **get_false_update_fixture_decorator_params()) def false_update(request): return Update(update_id=1, **request.param) @pytest.fixture(params=[1, 2], ids=lambda h: 'UTC +{hour:0>2}:00'.format(hour=h)) def utc_offset(request): return datetime.timedelta(hours=request.param) @pytest.fixture() def timezone(utc_offset): return _UtcOffsetTimezone(utc_offset)
board.py
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ APIs to control the button (and button LED) that's attached to the Vision Bonnet and Voice Bonnet/HAT's button connector. For example: .. literalinclude:: ../src/examples/button_led.py :language: python .. module:: aiy.board .. autoclass:: Board :members: :undoc-members: :show-inheritance: .. autoclass:: Button :members: :undoc-members: :show-inheritance: .. py:class:: Led Controls the LED in the button. Get an instance from :attr:`Board.led`. This class is primarily intended for compatibility with the Voice HAT (V1 Voice Kit), and it also works on the Voice/Vision Bonnet. However, if you're using *only* the Voice/Vision Bonnet, then you should instead use :mod:`aiy.leds`, which provides more controls for the button's unique RGB LED. .. py:method:: brightness(value) Sets the button LED brightness :param value: The brighness, between 0.0 and 1.0 .. py:attribute:: state Sets the button LED state. Can be one of the values below. .. py:attribute:: OFF .. py:attribute:: ON .. py:attribute:: BLINK .. py:attribute:: BLINK_3 .. py:attribute:: BEACON .. py:attribute:: BEACON_DARK .. py:attribute:: DECAY .. py:attribute:: PULSE_SLOW .. py:attribute:: PULSE_QUICK """ import contextlib import itertools import queue import threading import time from collections import namedtuple from RPi import GPIO from aiy.leds import Color, Leds, Pattern class Button: """ An interface for the button connected to the AIY board's button connector.""" @staticmethod def _trigger(event_queue, callback): try: while True: event_queue.get_nowait().set() except queue.Empty: pass if callback: callback() def _run(self): when_pressed = 0.0 pressed = False while not self._done.is_set(): now = time.monotonic() if now - when_pressed > self._debounce_time: if GPIO.input(self._channel) == self._expected: if not pressed: pressed = True when_pressed = now self._trigger(self._pressed_queue, self._pressed_callback) else: if pressed: pressed = False self._trigger(self._released_queue, self._released_callback) self._done.wait(0.05) def __init__(self, channel, edge='falling', pull_up_down='up', debounce_time=0.08): if pull_up_down not in ('up', 'down'): raise ValueError('Must be "up" or "down"') if edge not in ('falling', 'rising'): raise ValueError('Must be "falling" or "rising"') self._channel = channel GPIO.setup(channel, GPIO.IN, pull_up_down={'up': GPIO.PUD_UP, 'down': GPIO.PUD_DOWN}[pull_up_down]) self._pressed_callback = None self._released_callback = None self._debounce_time = debounce_time self._expected = True if edge == 'rising' else False self._pressed_queue = queue.Queue() self._released_queue = queue.Queue() self._done = threading.Event() self._thread = threading.Thread(target=self._run) self._thread.start() def close(self): """Internal method to clean up the object when done.""" self._done.set() self._thread.join() GPIO.cleanup(self._channel) def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): self.close() def _when_pressed(self, callback): self._pressed_callback = callback when_pressed = property(None, _when_pressed) """A function to run when the button is pressed.""" def _when_released(self, callback): self._released_callback = callback when_released = property(None, _when_released) """A function to run when the button is released.""" def wait_for_press(self, timeout=None): """Pauses the script until the button is pressed or the timeout is reached. Args: timeout: Seconds to wait before proceeding. By default, this is ``None``, which means wait indefinitely.""" event = threading.Event() self._pressed_queue.put(event) return event.wait(timeout) def wait_for_release(self, timeout=None): """Pauses the script until the button is released or the timeout is reached. Args: timeout: Seconds to wait before proceeding. By default, this is ``None``, which means wait indefinitely.""" event = threading.Event() self._released_queue.put(event) return event.wait(timeout) class MultiColorLed: Config = namedtuple('Config', ['channels', 'pattern']) OFF = Config(channels=lambda color: Leds.rgb_off(), pattern=None) ON = Config(channels=Leds.rgb_on, pattern=None) BLINK = Config(channels=Leds.rgb_pattern, pattern=Pattern.blink(500)) BLINK_3 = BLINK BEACON = BLINK BEACON_DARK = BLINK DECAY = BLINK PULSE_SLOW = Config(channels=Leds.rgb_pattern, pattern=Pattern.breathe(500)) PULSE_QUICK = Config(channels=Leds.rgb_pattern, pattern=Pattern.breathe(100)) def _update(self, state, brightness): with self._lock: if state is not None: self._state = state if brightness is not None: self._brightness = brightness color = (int(255 * self._brightness), 0, 0) if self._state.pattern: self._leds.pattern = self._state.pattern self._leds.update(self._state.channels(color)) def __init__(self, channel): self._lock = threading.Lock() self._brightness = 1.0 # Read and written atomically. self._state = self.OFF self._leds = Leds() def close(self): """Internal method to clean up the object when done.""" self._leds.reset() def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): self.close() @property def brightness(self): return self._brightness @brightness.setter def brightness(self, value): if value < 0.0 or value > 1.0: raise ValueError('Brightness must be between 0.0 and 1.0.') self._update(state=None, brightness=value) def _set_state(self, state): self._update(state=state, brightness=None) state = property(None, _set_state) class SingleColorLed: Config = namedtuple('Config', ['duty_cycles', 'pause']) OFF = Config(duty_cycles=lambda: [0], pause=1.0) ON = Config(duty_cycles=lambda: [100], pause=1.0) BLINK = Config(duty_cycles=lambda: [0, 100], pause=0.5) BLINK_3 = Config(duty_cycles=lambda: [0, 100] * 3 + [0, 0], pause=0.25) BEACON = Config(duty_cycles=lambda: itertools.chain([30] * 100, [100] * 8, range(100, 30, -5)), pause=0.05) BEACON_DARK = Config(duty_cycles=lambda: itertools.chain([0] * 100, range(0, 30, 3), range(30, 0, -3)), pause=0.05) DECAY = Config(duty_cycles=lambda: range(100, 0, -2), pause=0.05) PULSE_SLOW = Config(duty_cycles=lambda: itertools.chain(range(0, 100, 2), range(100, 0, -2)), pause=0.1) PULSE_QUICK = Config(duty_cycles=lambda: itertools.chain(range(0, 100, 5), range(100, 0, -5)), pause=0.05) def _run(self): while True: try: state = self._queue.get_nowait() if state is None: break it = itertools.cycle(state.duty_cycles()) except queue.Empty: pass self._pwm.ChangeDutyCycle(int(self._brightness * next(it))) self._updated.wait(state.pause) self._updated.clear() def __init__(self, channel): self._brightness = 1.0 # Read and written atomically. self._channel = channel self._queue = queue.Queue(maxsize=1) self._queue.put(self.OFF) self._updated = threading.Event() GPIO.setup(channel, GPIO.OUT) self._pwm = GPIO.PWM(channel, 100) self._pwm.start(0) self._thread = threading.Thread(target=self._run) self._thread.start() def close(self): self._queue.put(None) self._thread.join() self._pwm.stop() GPIO.cleanup(self._channel) def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): self.close() @property def brightness(self): return self._brightness @brightness.setter def brightness(self, value): if value < 0.0 or value > 1.0: raise ValueError('Brightness must be between 0.0 and 1.0.') self._brightness = value def _set_state(self, state): self._queue.put(state) self._updated.set() state = property(None, _set_state) if Leds.installed(): Led = MultiColorLed else: Led = SingleColorLed BUTTON_PIN = 23 LED_PIN = 25 class Board: """An interface for the connected AIY board.""" def __init__(self, button_pin=BUTTON_PIN, led_pin=LED_PIN): self._stack = contextlib.ExitStack() self._lock = threading.Lock() self._button_pin = button_pin self._button = None self._led = None self._led_pin = led_pin GPIO.setmode(GPIO.BCM) def close(self): self._stack.close() with self._lock: self._button = None self._led = None def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): self.close() @property def button(self): """Returns a :class:`Button` representing the button connected to the button connector.""" with self._lock: if not self._button: self._button = self._stack.enter_context(Button(self._button_pin)) return self._button @property def led(self): """Returns an :class:`Led` representing the LED in the button.""" with self._lock: if not self._led: self._led = self._stack.enter_context(Led(self._led_pin)) return self._led
prepro_feats.py
""" Preprocess a raw json dataset into features files for use in data_loader.py Input: json file that has the form [{ file_path: 'path/img.jpg', captions: ['a caption', ...] }, ...] example element in this list would look like {'captions': [u'A man with a red helmet on a small moped on a dirt road. ', u'Man riding a motor bike on a dirt road on the countryside.', u'A man riding on the back of a motorcycle.', u'A dirt path with a young person on a motor bike rests to the foreground of a verdant area with a bridge and a background of cloud-wreathed mountains. ', u'A man in a red shirt and a red hat is on a motorcycle on a hill side.'], 'file_path': u'val2014/COCO_val2014_000000391895.jpg', 'id': 391895} This script reads this json, does some basic preprocessing on the captions (e.g. lowercase, etc.), creates a special UNK token, and encodes everything to arrays Output: two folders of features """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3" import json import argparse from random import shuffle, seed import string # non-standard dependencies: import h5py from six.moves import cPickle import numpy as np import torch import torchvision.models as models import skimage.io from tqdm import tqdm from torchvision import transforms as trn from multiprocessing import Process, freeze_support, set_start_method import torch.multiprocessing as mp preprocess = trn.Compose([ #trn.ToTensor(), trn.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) import captioning.utils.resnet as resnet from captioning.utils.resnet_utils import myResnet def train(i,indices,imgs,params,dir_fc,dir_att): if i % 4 == 0: torch.cuda.set_device(0) if i % 4 == 1: torch.cuda.set_device(1) if i % 4 == 2: torch.cuda.set_device(2) if i % 4 == 3: torch.cuda.set_device(3) net = getattr(resnet, params['model'])() net.load_state_dict(torch.load(os.path.join(params['model_root'],params['model']+'.pth'))) my_resnet = myResnet(net) my_resnet.cuda() my_resnet.eval() for j in tqdm(range(indices[i+1]-indices[i])): # load the image img = imgs[j+indices[i]] if os.path.isfile('data/all_att/'+str(j+indices[i])+'.npz'): continue I = skimage.io.imread(os.path.join(params['images_root'], img['filename'])) # handle grayscale input images if len(I.shape) == 2: I = I[:,:,np.newaxis] I = np.concatenate((I,I,I), axis=2) I = I.astype('float32')/255.0 I = torch.from_numpy(I.transpose([2,0,1])).cuda() I = preprocess(I) with torch.no_grad(): # tmp_fc, tmp_att = my_resnet(I, params['att_size']) tmp_att = my_resnet(I, params['att_size']) # write to pkl # np.save(os.path.join(dir_fc,str(j+indices[i]) ), tmp_fc.data.cpu().float().numpy()) np.savez_compressed(os.path.join(dir_att, str(j+indices[i])), feat=tmp_att.data.cpu().float().numpy()) # if i % 1000 == 0: # print('processing %d/%d (%.2f%% done)' % (i, N, i*100.0/N)) # print('wrote ', params['output_dir']) if __name__ == "__main__": parser = argparse.ArgumentParser() # input json parser.add_argument('--input_json', required=True, help='input json file to process into hdf5') parser.add_argument('--output_dir', default='data', help='output h5 file') # options parser.add_argument('--images_root', default='', help='root location in which images are stored, to be prepended to file_path in input json') parser.add_argument('--att_size', default=14, type=int, help='14x14 or 7x7') parser.add_argument('--model', default='resnet101', type=str, help='resnet101, resnet152') parser.add_argument('--model_root', default='./data/imagenet_weights', type=str, help='model root') args = parser.parse_args() params = vars(args) # convert to ordinary dict print('parsed input parameters:') print(json.dumps(params, indent = 2)) imgs = json.load(open(params['input_json'], 'r')) imgs = imgs['images'] N = len(imgs) seed(123) # make reproducible dir_fc = params['output_dir']+'_fc' dir_att = params['output_dir']+'_att' if not os.path.isdir(dir_fc): os.mkdir(dir_fc) if not os.path.isdir(dir_att): os.mkdir(dir_att) n_processes = 16 n_total = N length = float(n_total) / float(n_processes) indices = [int(np.ceil(i* length)) for i in range(n_processes+1)] set_start_method('spawn') for i in range(n_processes): p = 'process'+str(i) p = mp.Process(target=train,args=(i,indices,imgs,params,dir_fc,dir_att,)) p.start()
download_worker.py
"""A utility for downloading multiple granules simultaneously""" from copy import deepcopy from multiprocessing import Manager, Process from os import cpu_count from pathlib import Path import queue import re from urllib.parse import urlparse from harmony.logging import build_logger from harmony.util import download def multi_core_download(urls, destination_dir, access_token, cfg, process_count=None): """ A method which automagically scales downloads to the number of CPU cores. For further explaination, see documentation on "multi-track drifting" Parameters ---------- urls : list list of urls to download destination_dir : str output path for downloaded files access_token : str access token as provided in Harmony input cfg : dict Harmony configuration information process_count : int Number of worker processes to run (expected >= 1) Returns ------- list list of downloaded files as pathlib.Path objects """ if process_count is None: process_count = cpu_count() with Manager() as manager: url_queue = manager.Queue(len(urls)) path_list = manager.list() for url in urls: url_queue.put(url) # Spawn worker processes processes = [] for _ in range(process_count): download_process = Process(target=_download_worker, args=(url_queue, path_list, destination_dir, access_token, cfg)) processes.append(download_process) download_process.start() # Ensure worker processes exit successfully for process in processes: process.join() if process.exitcode != 0: raise RuntimeError(f'Download failed - exit code: {process.exitcode}') process.close() path_list = deepcopy(path_list) # ensure GC can cleanup multiprocessing return [Path(path) for path in path_list] def _download_worker(url_queue, path_list, destination_dir, access_token, cfg): """ A method to be executed in a separate process which processes the url_queue and places paths to completed downloads into the path_list. Downloads are handled by harmony.util.download Parameters ---------- url_queue : queue.Queue URLs to process - should be filled from start and only decreases path_list : list paths to completed file downloads destination_dir : str output path for downloaded files access_token : str access token as provided in Harmony input cfg : dict Harmony configuration information """ logger = build_logger(cfg) while not url_queue.empty(): try: url = url_queue.get_nowait() except queue.Empty: break path = Path(download(url, destination_dir, logger=logger, access_token=access_token, cfg=cfg)) filename_match = re.match(r'.*\/(.+\..+)', urlparse(url).path) if filename_match is not None: filename = filename_match.group(1) dest_path = path.parent.joinpath(filename) path = path.rename(dest_path) else: logger.warning('Origin filename could not be assertained - %s', url) path_list.append(str(path))
swaprebalance.py
import time import datetime import unittest from TestInput import TestInputSingleton import logger from couchbase_helper.cluster import Cluster from membase.api.rest_client import RestConnection, RestHelper from membase.helper.bucket_helper import BucketOperationHelper from membase.helper.cluster_helper import ClusterOperationHelper from membase.helper.rebalance_helper import RebalanceHelper from memcached.helper.data_helper import LoadWithMcsoda from threading import Thread from remote.remote_util import RemoteMachineShellConnection from memcached.helper.data_helper import MemcachedClientHelper from membase.api.exception import RebalanceFailedException from basetestcase import BaseTestCase from security.rbac_base import RbacBase class SwapRebalanceBase(unittest.TestCase): @staticmethod def common_setup(self): self.cluster_helper = Cluster() self.log = logger.Logger.get_logger() self.cluster_run = False self.input = TestInputSingleton.input self.servers = self.input.servers serverInfo = self.servers[0] rest = RestConnection(serverInfo) if len({server.ip for server in self.servers}) == 1: ip = rest.get_nodes_self().ip for server in self.servers: server.ip = ip self.cluster_run = True self.case_number = self.input.param("case_number", 0) self.replica = self.input.param("replica", 1) self.keys_count = self.input.param("keys-count", 1000) self.load_ratio = self.input.param("load-ratio", 1) self.ratio_expiry = self.input.param("ratio-expiry", 0.03) self.ratio_deletes = self.input.param("ratio-deletes", 0.13) self.num_buckets = self.input.param("num-buckets", 1) self.bucket_storage = self.input.param("bucket_storage", 'couchstore') self.failover_factor = self.num_swap = self.input.param("num-swap", 1) self.num_initial_servers = self.input.param("num-initial-servers", 3) self.fail_orchestrator = self.swap_orchestrator = self.input.param("swap-orchestrator", False) self.do_access = self.input.param("do-access", True) self.load_started = False self.loaders = [] for node in self.servers: if node.internal_ip: RestConnection(node).set_alternate_address(node.ip) try: # Clear the state from Previous invalid run if rest._rebalance_progress_status() == 'running': self.log.warning("rebalancing is still running, previous test should be verified") stopped = rest.stop_rebalance() self.assertTrue(stopped, msg="unable to stop rebalance") self.log.info("============== SwapRebalanceBase setup was started for test #{0} {1}=============="\ .format(self.case_number, self._testMethodName)) SwapRebalanceBase.reset(self) # Make sure the test is setup correctly min_servers = int(self.num_initial_servers) + int(self.num_swap) msg = "minimum {0} nodes required for running swap rebalance" self.assertTrue(len(self.servers) >= min_servers, msg=msg.format(min_servers)) self.log.info('picking server : {0} as the master'.format(serverInfo)) node_ram_ratio = BucketOperationHelper.base_bucket_ratio(self.servers) info = rest.get_nodes_self() rest.init_cluster(username=serverInfo.rest_username, password=serverInfo.rest_password) rest.init_cluster_memoryQuota(memoryQuota=int(info.mcdMemoryReserved * node_ram_ratio)) SwapRebalanceBase.enable_diag_eval_on_non_local_hosts(self, serverInfo) # Add built-in user testuser = [{'id': 'cbadminbucket', 'name': 'cbadminbucket', 'password': 'password'}] RbacBase().create_user_source(testuser, 'builtin', self.servers[0]) # Assign user to role role_list = [{'id': 'cbadminbucket', 'name': 'cbadminbucket', 'roles': 'admin'}] RbacBase().add_user_role(role_list, RestConnection(self.servers[0]), 'builtin') if self.num_buckets > 10: BaseTestCase.change_max_buckets(self, self.num_buckets) self.log.info("============== SwapRebalanceBase setup was finished for test #{0} {1} ==============" .format(self.case_number, self._testMethodName)) SwapRebalanceBase._log_start(self) except Exception as e: self.cluster_helper.shutdown() self.fail(e) @staticmethod def common_tearDown(self): self.cluster_helper.shutdown() test_failed = (hasattr(self, '_resultForDoCleanups') and len(self._resultForDoCleanups.failures or self._resultForDoCleanups.errors)) \ or (hasattr(self, '_exc_info') and self._exc_info()[1] is not None) if test_failed and TestInputSingleton.input.param("stop-on-failure", False)\ or self.input.param("skip_cleanup", False): self.log.warning("CLEANUP WAS SKIPPED") else: SwapRebalanceBase.reset(self) SwapRebalanceBase._log_finish(self) # Remove rbac user in teardown try: role_del = ['cbadminbucket'] RbacBase().remove_user_role(role_del, RestConnection( self.servers[0])) except: pass @staticmethod def reset(self): self.log.info("============== SwapRebalanceBase cleanup was started for test #{0} {1} =============="\ .format(self.case_number, self._testMethodName)) self.log.info("Stopping load in Teardown") SwapRebalanceBase.stop_load(self.loaders) for server in self.servers: rest = RestConnection(server) if rest._rebalance_progress_status() == 'running': self.log.warning("rebalancing is still running, test should be verified") stopped = rest.stop_rebalance() self.assertTrue(stopped, msg="unable to stop rebalance") BucketOperationHelper.delete_all_buckets_or_assert(self.servers, self) for server in self.servers: ClusterOperationHelper.cleanup_cluster([server]) if server.data_path: rest = RestConnection(server) rest.set_data_path(data_path=server.data_path) ClusterOperationHelper.wait_for_ns_servers_or_assert(self.servers, self) self.log.info("============== SwapRebalanceBase cleanup was finished for test #{0} {1} =============="\ .format(self.case_number, self._testMethodName)) @staticmethod def enable_diag_eval_on_non_local_hosts(self, master): """ Enable diag/eval to be run on non-local hosts. :param master: Node information of the master node of the cluster :return: Nothing """ remote = RemoteMachineShellConnection(master) output, error = remote.enable_diag_eval_on_non_local_hosts() if "ok" not in output: self.log.error("Error in enabling diag/eval on non-local hosts on {}. {}".format(master.ip, output)) raise Exception("Error in enabling diag/eval on non-local hosts on {}".format(master.ip)) else: self.log.info("Enabled diag/eval for non-local hosts from {}".format(master.ip)) @staticmethod def _log_start(self): try: msg = "{0} : {1} started ".format(datetime.datetime.now(), self._testMethodName) RestConnection(self.servers[0]).log_client_error(msg) except: pass @staticmethod def _log_finish(self): try: msg = "{0} : {1} finished ".format(datetime.datetime.now(), self._testMethodName) RestConnection(self.servers[0]).log_client_error(msg) except: pass @staticmethod def sleep(self, timeout=1, message=""): self.log.info("sleep for {0} secs. {1} ...".format(timeout, message)) time.sleep(timeout) @staticmethod def _create_default_bucket(self, replica=1): name = "default" master = self.servers[0] rest = RestConnection(master) helper = RestHelper(RestConnection(master)) if not helper.bucket_exists(name): node_ram_ratio = BucketOperationHelper.base_bucket_ratio(self.servers) info = rest.get_nodes_self() available_ram = info.memoryQuota * node_ram_ratio rest.create_bucket(bucket=name, ramQuotaMB=int(available_ram), replicaNumber=replica, storageBackend=self.bucket_storage) ready = BucketOperationHelper.wait_for_memcached(master, name) self.assertTrue(ready, msg="wait_for_memcached failed") self.assertTrue(helper.bucket_exists(name), msg="unable to create {0} bucket".format(name)) @staticmethod def _create_multiple_buckets(self, replica=1): master = self.servers[0] created = BucketOperationHelper.create_multiple_buckets(master, replica, howmany=self.num_buckets, bucket_storage=self.bucket_storage) self.assertTrue(created, "unable to create multiple buckets") rest = RestConnection(master) buckets = rest.get_buckets() for bucket in buckets: ready = BucketOperationHelper.wait_for_memcached(master, bucket.name) self.assertTrue(ready, msg="wait_for_memcached failed") # Used for items verification active vs. replica @staticmethod def items_verification(test, master): rest = RestConnection(master) # Verify items count across all node timeout = 600 for bucket in rest.get_buckets(): verified = RebalanceHelper.wait_till_total_numbers_match(master, bucket.name, timeout_in_seconds=timeout) test.assertTrue(verified, "Lost items!!.. failing test in {0} secs".format(timeout)) @staticmethod def start_load_phase(self, master): loaders = [] rest = RestConnection(master) for bucket in rest.get_buckets(): loader = dict() loader["mcsoda"] = LoadWithMcsoda(master, self.keys_count, bucket=bucket.name, rest_password=master.rest_password, prefix=str(bucket.name), port=8091) loader["mcsoda"].cfg["exit-after-creates"] = 1 loader["mcsoda"].cfg["json"] = 0 loader["thread"] = Thread(target=loader["mcsoda"].load_data, name='mcloader_' + bucket.name) loader["thread"].daemon = True loaders.append(loader) for loader in loaders: loader["thread"].start() return loaders @staticmethod def start_access_phase(self, master): loaders = [] rest = RestConnection(master) for bucket in rest.get_buckets(): loader = dict() loader["mcsoda"] = LoadWithMcsoda(master, self.keys_count // 2, bucket=bucket.name, rest_password=master.rest_password, prefix=str(bucket.name), port=8091) loader["mcsoda"].cfg["ratio-sets"] = 0.8 loader["mcsoda"].cfg["ratio-hot"] = 0.2 loader["mcsoda"].cfg["ratio-creates"] = 0.5 loader["mcsoda"].cfg["ratio-deletes"] = self.ratio_deletes loader["mcsoda"].cfg["ratio-expirations"] = self.ratio_expiry loader["mcsoda"].cfg["json"] = 0 loader["thread"] = Thread(target=loader["mcsoda"].load_data, name='mcloader_' + bucket.name) loader["thread"].daemon = True loaders.append(loader) for loader in loaders: loader["thread"].start() return loaders @staticmethod def stop_load(loaders, do_stop=True): if do_stop: for loader in loaders: loader["mcsoda"].load_stop() for loader in loaders: if do_stop: loader["thread"].join(300) else: loader["thread"].join() @staticmethod def create_buckets(self): if self.num_buckets == 1: SwapRebalanceBase._create_default_bucket(self, replica=self.replica) else: SwapRebalanceBase._create_multiple_buckets(self, replica=self.replica) @staticmethod def verification_phase(test, master): # Stop loaders SwapRebalanceBase.stop_load(test.loaders) test.log.info("DONE DATA ACCESS PHASE") test.log.info("VERIFICATION PHASE") rest = RestConnection(master) servers_in_cluster = [] nodes = rest.get_nodes() for server in test.servers: for node in nodes: if node.ip == server.ip and node.port == server.port: servers_in_cluster.append(server) time.sleep(60) SwapRebalanceBase.items_verification(test, master) @staticmethod def _common_test_body_swap_rebalance(self, do_stop_start=False): master = self.servers[0] rest = RestConnection(master) num_initial_servers = self.num_initial_servers creds = self.input.membase_settings intial_severs = self.servers[:num_initial_servers] self.log.info("CREATE BUCKET PHASE") SwapRebalanceBase.create_buckets(self) # Cluster all starting set of servers self.log.info("INITIAL REBALANCE PHASE") status, servers_rebalanced = RebalanceHelper.rebalance_in(intial_severs, len(intial_severs) - 1) self.assertTrue(status, msg="Rebalance was failed") self.log.info("DATA LOAD PHASE") self.loaders = SwapRebalanceBase.start_load_phase(self, master) # Wait till load phase is over SwapRebalanceBase.stop_load(self.loaders, do_stop=False) self.log.info("DONE LOAD PHASE") # Start the swap rebalance current_nodes = RebalanceHelper.getOtpNodeIds(master) self.log.info("current nodes : {0}".format(current_nodes)) toBeEjectedNodes = RebalanceHelper.pick_nodes(master, howmany=self.num_swap) optNodesIds = [node.id for node in toBeEjectedNodes] if self.swap_orchestrator: status, content = ClusterOperationHelper.find_orchestrator(master) self.assertTrue(status, msg="Unable to find orchestrator: {0}:{1}".\ format(status, content)) if self.num_swap is len(current_nodes): optNodesIds.append(content) else: optNodesIds[0] = content for node in optNodesIds: self.log.info("removing node {0} and rebalance afterwards".format(node)) new_swap_servers = self.servers[num_initial_servers:num_initial_servers + self.num_swap] for server in new_swap_servers: otpNode = rest.add_node(creds.rest_username, creds.rest_password, server.cluster_ip, server.port) msg = "unable to add node {0} to the cluster" self.assertTrue(otpNode, msg.format(server.ip)) if self.swap_orchestrator: rest = RestConnection(new_swap_servers[0]) master = new_swap_servers[0] if self.do_access: self.log.info("DATA ACCESS PHASE") self.loaders = SwapRebalanceBase.start_access_phase(self, master) self.log.info("SWAP REBALANCE PHASE") rest.rebalance(otpNodes=[node.id for node in rest.node_statuses()], ejectedNodes=optNodesIds) if do_stop_start: # Rebalance is stopped at 20%, 40% and 60% completion retry = 0 for expected_progress in (20, 40, 60): self.log.info("STOP/START SWAP REBALANCE PHASE WITH PROGRESS {0}%". format(expected_progress)) while True: progress = rest._rebalance_progress() if progress < 0: self.log.error("rebalance progress code : {0}".format(progress)) break elif progress == 100: self.log.warning("Rebalance has already reached 100%") break elif progress >= expected_progress: self.log.info("Rebalance will be stopped with {0}%".format(progress)) stopped = rest.stop_rebalance() self.assertTrue(stopped, msg="unable to stop rebalance") SwapRebalanceBase.sleep(self, 20) rest.rebalance(otpNodes=[node.id for node in rest.node_statuses()], ejectedNodes=optNodesIds) break elif retry > 100: break else: retry += 1 SwapRebalanceBase.sleep(self, 1) self.assertTrue(rest.monitorRebalance(), msg="rebalance operation failed after adding node {0}".format(optNodesIds)) SwapRebalanceBase.verification_phase(self, master) @staticmethod def _common_test_body_failed_swap_rebalance(self): master = self.servers[0] rest = RestConnection(master) num_initial_servers = self.num_initial_servers creds = self.input.membase_settings intial_severs = self.servers[:num_initial_servers] self.log.info("CREATE BUCKET PHASE") SwapRebalanceBase.create_buckets(self) # Cluster all starting set of servers self.log.info("INITIAL REBALANCE PHASE") status, servers_rebalanced = RebalanceHelper.rebalance_in(intial_severs, len(intial_severs) - 1) self.assertTrue(status, msg="Rebalance was failed") self.log.info("DATA LOAD PHASE") self.loaders = SwapRebalanceBase.start_load_phase(self, master) # Wait till load phase is over SwapRebalanceBase.stop_load(self.loaders, do_stop=False) self.log.info("DONE LOAD PHASE") # Start the swap rebalance current_nodes = RebalanceHelper.getOtpNodeIds(master) self.log.info("current nodes : {0}".format(current_nodes)) toBeEjectedNodes = RebalanceHelper.pick_nodes(master, howmany=self.num_swap) optNodesIds = [node.id for node in toBeEjectedNodes] if self.swap_orchestrator: status, content = ClusterOperationHelper.find_orchestrator(master) self.assertTrue(status, msg="Unable to find orchestrator: {0}:{1}".\ format(status, content)) # When swapping all the nodes if self.num_swap is len(current_nodes): optNodesIds.append(content) else: optNodesIds[0] = content for node in optNodesIds: self.log.info("removing node {0} and rebalance afterwards".format(node)) new_swap_servers = self.servers[num_initial_servers:num_initial_servers + self.num_swap] for server in new_swap_servers: otpNode = rest.add_node(creds.rest_username, creds.rest_password, server.ip, server.port) msg = "unable to add node {0} to the cluster" self.assertTrue(otpNode, msg.format(server.ip)) if self.swap_orchestrator: rest = RestConnection(new_swap_servers[0]) master = new_swap_servers[0] self.log.info("DATA ACCESS PHASE") self.loaders = SwapRebalanceBase.start_access_phase(self, master) self.log.info("SWAP REBALANCE PHASE") rest.rebalance(otpNodes=[node.id for node in rest.node_statuses()], ejectedNodes=optNodesIds) SwapRebalanceBase.sleep(self, 10, "Rebalance should start") self.log.info("FAIL SWAP REBALANCE PHASE @ {0}".format(self.percentage_progress)) reached = RestHelper(rest).rebalance_reached(self.percentage_progress) if reached and RestHelper(rest).is_cluster_rebalanced(): # handle situation when rebalance failed at the beginning self.log.error('seems rebalance failed!') rest.print_UI_logs() self.fail("rebalance failed even before killing memcached") bucket = rest.get_buckets()[0].name pid = None if self.swap_orchestrator and not self.cluster_run: # get PID via remote connection if master is a new node shell = RemoteMachineShellConnection(master) pid = shell.get_memcache_pid() shell.disconnect() else: times = 2 if self.cluster_run: times = 20 for i in range(times): try: _mc = MemcachedClientHelper.direct_client(master, bucket) pid = _mc.stats()["pid"] break except (EOFError, KeyError) as e: self.log.error("{0}.Retry in 2 sec".format(e)) SwapRebalanceBase.sleep(self, 2) if pid is None: # sometimes pid is not returned by mc.stats() shell = RemoteMachineShellConnection(master) pid = shell.get_memcache_pid() shell.disconnect() if pid is None: self.fail("impossible to get a PID") command = "os:cmd(\"kill -9 {0} \")".format(pid) self.log.info(command) killed = rest.diag_eval(command) self.log.info("killed {0}:{1}?? {2} ".format(master.ip, master.port, killed)) self.log.info("sleep for 10 sec after kill memcached") SwapRebalanceBase.sleep(self, 10) # we can't get stats for new node when rebalance falls if not self.swap_orchestrator: ClusterOperationHelper._wait_warmup_completed(self, [master], bucket, wait_time=600) i = 0 # we expect that rebalance will be failed try: rest.monitorRebalance() except RebalanceFailedException: # retry rebalance if it failed self.log.warning("Rebalance failed but it's expected") SwapRebalanceBase.sleep(self, 30) self.assertFalse(RestHelper(rest).is_cluster_rebalanced(), msg="cluster need rebalance") knownNodes = rest.node_statuses(); self.log.info("nodes are still in cluster: {0}".format([(node.ip, node.port) for node in knownNodes])) ejectedNodes = list(set(optNodesIds) & {node.id for node in knownNodes}) rest.rebalance(otpNodes=[node.id for node in knownNodes], ejectedNodes=ejectedNodes) SwapRebalanceBase.sleep(self, 10, "Wait for rebalance to start") self.assertTrue(rest.monitorRebalance(), msg="rebalance operation failed after adding node {0}".format(toBeEjectedNodes)) else: self.log.info("rebalance completed successfully") SwapRebalanceBase.verification_phase(self, master) @staticmethod def _add_back_failed_node(self, do_node_cleanup=False): master = self.servers[0] rest = RestConnection(master) creds = self.input.membase_settings self.log.info("CREATE BUCKET PHASE") SwapRebalanceBase.create_buckets(self) # Cluster all servers self.log.info("INITIAL REBALANCE PHASE") status, servers_rebalanced = RebalanceHelper.rebalance_in(self.servers, len(self.servers) - 1) self.assertTrue(status, msg="Rebalance was failed") self.log.info("DATA LOAD PHASE") self.loaders = SwapRebalanceBase.start_load_phase(self, master) # Wait till load phase is over SwapRebalanceBase.stop_load(self.loaders, do_stop=False) self.log.info("DONE LOAD PHASE") # Start the swap rebalance current_nodes = RebalanceHelper.getOtpNodeIds(master) self.log.info("current nodes : {0}".format(current_nodes)) toBeEjectedNodes = RebalanceHelper.pick_nodes(master, howmany=self.failover_factor) optNodesIds = [node.id for node in toBeEjectedNodes] # List of servers that will not be failed over not_failed_over = [] for server in self.servers: if self.cluster_run: if server.port not in [node.port for node in toBeEjectedNodes]: not_failed_over.append(server) self.log.info("Node {0}:{1} not failed over".format(server.ip, server.port)) else: if server.ip not in [node.ip for node in toBeEjectedNodes]: not_failed_over.append(server) self.log.info("Node {0}:{1} not failed over".format(server.ip, server.port)) if self.fail_orchestrator: status, content = ClusterOperationHelper.find_orchestrator(master) self.assertTrue(status, msg="Unable to find orchestrator: {0}:{1}".\ format(status, content)) # When swapping all the nodes if self.num_swap is len(current_nodes): optNodesIds.append(content) else: optNodesIds[0] = content master = not_failed_over[-1] self.log.info("DATA ACCESS PHASE") self.loaders = SwapRebalanceBase.start_access_phase(self, master) # Failover selected nodes for node in optNodesIds: self.log.info("failover node {0} and rebalance afterwards".format(node)) rest.fail_over(node) rest.rebalance(otpNodes=[node.id for node in rest.node_statuses()], \ ejectedNodes=optNodesIds) self.assertTrue(rest.monitorRebalance(), msg="rebalance operation failed after adding node {0}".format(optNodesIds)) # Add back the same failed over nodes # Cleanup the node, somehow # TODO: cluster_run? if do_node_cleanup: pass # Make rest connection with node part of cluster rest = RestConnection(master) # Given the optNode, find ip add_back_servers = [] nodes = rest.get_nodes() for server in nodes: if isinstance(server.ip, str): add_back_servers.append(server) final_add_back_servers = [] for server in self.servers: if self.cluster_run: if server.port not in [serv.port for serv in add_back_servers]: final_add_back_servers.append(server) else: if server.ip not in [serv.ip for serv in add_back_servers]: final_add_back_servers.append(server) for server in final_add_back_servers: otpNode = rest.add_node(creds.rest_username, creds.rest_password, server.ip, server.port) msg = "unable to add node {0} to the cluster" self.assertTrue(otpNode, msg.format(server.ip)) rest.rebalance(otpNodes=[node.id for node in rest.node_statuses()], ejectedNodes=[]) self.assertTrue(rest.monitorRebalance(), msg="rebalance operation failed after adding node {0}".format(add_back_servers)) SwapRebalanceBase.verification_phase(self, master) @staticmethod def _failover_swap_rebalance(self): master = self.servers[0] rest = RestConnection(master) creds = self.input.membase_settings num_initial_servers = self.num_initial_servers intial_severs = self.servers[:num_initial_servers] self.log.info("CREATE BUCKET PHASE") SwapRebalanceBase.create_buckets(self) # Cluster all starting set of servers self.log.info("INITIAL REBALANCE PHASE") status, servers_rebalanced = RebalanceHelper.rebalance_in(intial_severs, len(intial_severs) - 1) self.assertTrue(status, msg="Rebalance was failed") self.log.info("DATA LOAD PHASE") self.loaders = SwapRebalanceBase.start_load_phase(self, master) # Wait till load phase is over SwapRebalanceBase.stop_load(self.loaders, do_stop=False) self.log.info("DONE LOAD PHASE") # Start the swap rebalance self.log.info("current nodes : {0}".format(RebalanceHelper.getOtpNodeIds(master))) toBeEjectedNodes = RebalanceHelper.pick_nodes(master, howmany=self.failover_factor) optNodesIds = [node.id for node in toBeEjectedNodes] if self.fail_orchestrator: status, content = ClusterOperationHelper.find_orchestrator(master) self.assertTrue(status, msg="Unable to find orchestrator: {0}:{1}".\ format(status, content)) optNodesIds[0] = content self.log.info("FAILOVER PHASE") # Failover selected nodes for node in optNodesIds: self.log.info("failover node {0} and rebalance afterwards".format(node)) rest.fail_over(node) self.assertTrue(rest.monitorRebalance(), msg="failed after failover of {0}".format(node)) new_swap_servers = self.servers[num_initial_servers:num_initial_servers + self.failover_factor] for server in new_swap_servers: otpNode = rest.add_node(creds.rest_username, creds.rest_password, server.ip, server.port) msg = "unable to add node {0} to the cluster" self.assertTrue(otpNode, msg.format(server.ip)) if self.fail_orchestrator: rest = RestConnection(new_swap_servers[0]) master = new_swap_servers[0] self.log.info("DATA ACCESS PHASE") self.loaders = SwapRebalanceBase.start_access_phase(self, master) rest.rebalance(otpNodes=[node.id for node in rest.node_statuses()], \ ejectedNodes=optNodesIds) self.assertTrue(rest.monitorRebalance(), msg="rebalance operation failed after adding node {0}".format(new_swap_servers)) SwapRebalanceBase.verification_phase(self, master) class SwapRebalanceBasicTests(unittest.TestCase): def setUp(self): SwapRebalanceBase.common_setup(self) def tearDown(self): SwapRebalanceBase.common_tearDown(self) def do_test(self): SwapRebalanceBase._common_test_body_swap_rebalance(self, do_stop_start=False) class SwapRebalanceStartStopTests(unittest.TestCase): def setUp(self): SwapRebalanceBase.common_setup(self) def tearDown(self): SwapRebalanceBase.common_tearDown(self) def do_test(self): SwapRebalanceBase._common_test_body_swap_rebalance(self, do_stop_start=True) class SwapRebalanceFailedTests(unittest.TestCase): def setUp(self): SwapRebalanceBase.common_setup(self) def tearDown(self): SwapRebalanceBase.common_tearDown(self) def test_failed_swap_rebalance(self): self.percentage_progress = self.input.param("percentage_progress", 50) SwapRebalanceBase._common_test_body_failed_swap_rebalance(self) # Not cluster_run friendly, yet def test_add_back_failed_node(self): SwapRebalanceBase._add_back_failed_node(self, do_node_cleanup=False) def test_failover_swap_rebalance(self): SwapRebalanceBase._failover_swap_rebalance(self)
commands.py
import logging import setproctitle import bigchaindb from bigchaindb.tendermint.lib import BigchainDB from bigchaindb.tendermint.core import App from bigchaindb.web import server, websocket_server from bigchaindb.tendermint import event_stream from bigchaindb.events import Exchange, EventTypes from bigchaindb.utils import Process logger = logging.getLogger(__name__) BANNER = """ **************************************************************************** * * * ┏┓ ╻┏━╸┏━╸╻ ╻┏━┓╻┏┓╻╺┳┓┏┓ ┏━┓ ┏━┓ ╺┳┓┏━╸╻ ╻ * * ┣┻┓┃┃╺┓┃ ┣━┫┣━┫┃┃┗┫ ┃┃┣┻┓ ┏━┛ ┃┃┃ ┃┃┣╸ ┃┏┛ * * ┗━┛╹┗━┛┗━╸╹ ╹╹ ╹╹╹ ╹╺┻┛┗━┛ ┗━╸╹┗━┛╹╺┻┛┗━╸┗┛ * * codename "fluffy cat" * * Initialization complete. BigchainDB Server is ready and waiting. * * * * You can send HTTP requests via the HTTP API documented in the * * BigchainDB Server docs at: * * https://bigchaindb.com/http-api * * * * Listening to client connections on: {:<15} * * * **************************************************************************** """ def start(): # Exchange object for event stream api exchange = Exchange() # start the web api app_server = server.create_server( settings=bigchaindb.config['server'], log_config=bigchaindb.config['log'], bigchaindb_factory=BigchainDB) p_webapi = Process(name='bigchaindb_webapi', target=app_server.run) p_webapi.start() # start message logger.info(BANNER.format(bigchaindb.config['server']['bind'])) # start websocket server p_websocket_server = Process(name='bigchaindb_ws', target=websocket_server.start, args=(exchange.get_subscriber_queue(EventTypes.BLOCK_VALID),)) p_websocket_server.start() # connect to tendermint event stream p_websocket_client = Process(name='bigchaindb_ws_to_tendermint', target=event_stream.start, args=(exchange.get_publisher_queue(),)) p_websocket_client.start() p_exchange = Process(name='bigchaindb_exchange', target=exchange.run) p_exchange.start() # We need to import this after spawning the web server # because import ABCIServer will monkeypatch all sockets # for gevent. from abci import ABCIServer setproctitle.setproctitle('bigchaindb') app = ABCIServer(app=App()) app.run() if __name__ == '__main__': start()
sample_random.py
from rlpyt.envs.dm_control_env import DMControlEnv import math import time import os from os.path import join, exists import itertools from tqdm import tqdm import numpy as np import imageio import multiprocessing as mp def worker(worker_id, start, end): np.random.seed(worker_id) # Initialize environment env_args = dict( domain='rope_sac', task='easy', max_path_length=5, pixel_wrapper_kwargs=dict(observation_key='pixels', pixels_only=False, # to not take away non pixel obs render_kwargs=dict(width=64, height=64, camera_id=0)), #task_kwargs=dict(random_location=True, pixels_only=True) # to not return positions and only pick location ) env = DMControlEnv(**env_args) total = 0 if worker_id == 0: pbar = tqdm(total=end - start) for i in range(start, end): str_i = str(i) run_folder = join(root, 'run{}'.format(str_i.zfill(5))) if not exists(run_folder): os.makedirs(run_folder) actions = [] o = env.reset() np.random.seed(0) for t in itertools.count(): a = env.action_space.sample() a = a / np.linalg.norm(a) * 1 actions.append(np.concatenate((o.location[:2], a))) str_t = str(t) imageio.imwrite(join(run_folder, 'img_{}.png'.format(str_t.zfill(2))), o.pixels.astype('uint8')) o, _, terminal, info = env.step(a) if terminal or info.traj_done: break actions = np.stack(actions, axis=0) np.save(join(run_folder, 'actions.npy'), actions) if worker_id == 0: pbar.update(1) if worker_id == 0: pbar.close() if __name__ == '__main__': start = time.time() root = join('data', 'rope_data') if not exists(root): os.makedirs(root) n_trajectories = 10 n_chunks = 1 #n_chunks = mp.cpu_count() partition_size = math.ceil(n_trajectories / n_chunks) args_list = [] for i in range(n_chunks): args_list.append((i, i * partition_size, min((i + 1) * partition_size, n_trajectories))) print('args', args_list) ps = [mp.Process(target=worker, args=args) for args in args_list] [p.start() for p in ps] [p.join() for p in ps] elapsed = time.time() - start print('Finished in {:.2f} min'.format(elapsed / 60))
PoolModule.py
from Config import proxypool_config import ProxyPool from bs4 import BeautifulSoup import threading import aiohttp import asyncio import ToolBox import time import re default_check_interval = proxypool_config.check_interval default_spider_interval = proxypool_config.spider_interval default_print_interval = proxypool_config.print_interval default_check_proxy_timeout = proxypool_config.check_proxy_timeout default_coroutines_semaphore = proxypool_config.coroutines_semaphore default_evaluate_interval = proxypool_config.evaluate_interval class proxy_pool(): ''' proxy pool use coroutines for spider on free-proxy web ''' def __init__(self): self.__proxy_urls = [ r'https://www.kuaidaili.com/free/inha/{}/', [r'http://www.iphai.com/free/ng', r'http://www.iphai.com/free/wg'], r'http://ip.jiangxianli.com/?page={}', r'https://proxy-list.org/english/index.php?p={}', r'http://www.66ip.cn/nmtq.php?getnum={}', r'http://www.ip3366.net/free/?stype=1&page={}', ] self.__test_ip_url = 'http://httpbin.org/ip' #http://icanhazip.com/ #another test ip self.__pool = [] self.__html_lib = None self.__check_interval = default_check_interval self.__spider_interval = default_spider_interval self.__print_interval = default_print_interval self.__evaluate_interval = default_evaluate_interval self.__db = ProxyPool.DatabaseModule.database() self.__semaphore = asyncio.Semaphore(default_coroutines_semaphore) #limit the number of coroutines async def __get_html(self, url): proxy = self.__db.get_one_string() # print('hhhhhhhhhhhh', proxy) try: async with aiohttp.ClientSession() as session: async with session.get( url=url, headers=ToolBox.tool_get_random_headers(), proxy=proxy, ) as response: return await response.text() except Exception as e: print(f'ERROR IN GET {url} {e}') return [] def __universal_soup(self, flag:str, html): res = html soup = BeautifulSoup(res, features='html5lib') ipandport = soup.find_all('td') for i, ip in enumerate(ipandport): temp = re.findall('\d+\.\d+\.\d+\.\d+', ip.string) if temp: port = ipandport[i + 1].string port = port.strip() new = ProxyPool.proxy(temp[0], port) if new not in self.__pool: self.__pool.append(new) print(f'process_{flag}_html got {new.get_string_address()}') def __evaluate_pool(self): feedback = self.__db.get_feedback() increase_proxies = feedback.get('increase') decrease_proxies = feedback.get('decrease') for proxy in self.__pool: if proxy.get_string_address() in increase_proxies: proxy.points += 1 elif proxy.get_string_address() in decrease_proxies: proxy.points -= 2 delete_proxies = [] add_proxies = [] for proxy in self.__pool: if proxy.points < -3: self.__pool.remove(proxy) delete_proxies.append(proxy) print(f'Delete {proxy}') elif proxy.points > 1: add_proxies.append(proxy) print(f'Add {proxy}') else: # print(proxy.get_string_address(), proxy.points) pass self.__db.delete_proxies(delete_proxies) self.__db.add_proxies(add_proxies) print('Evaluate done!' ,ToolBox.tool_get_current_time()) thread = threading.Timer(self.__evaluate_interval, self.__evaluate_pool) thread.start() async def __process_first_html(self): # tasks = [self.__get_html(self.__proxy_urls[0].format(_i)) for _i in range(1, 4)] page_count = 4 done = [] for _i in range(1, page_count): url = self.__proxy_urls[0].format(_i) html = await self.__get_html(url) done.append(html) time.sleep(1.148) # done = await asyncio.gather(*tasks) for html in done: if html: soup = BeautifulSoup(html, features="html5lib") ips = soup.find_all( 'td', { 'data-title': 'IP' } ) ports = soup.find_all( 'td', { 'data-title': 'PORT' } ) proxies = zip(ips, ports) # print(len(ips)) # os._exit(-1) for item in proxies: proxy = ProxyPool.proxy(item[0].string, item[1].string) if proxy not in self.__pool: self.__pool.append(proxy) print(f'process_first_html got {proxy.get_string_address()}') # print('here', self.get_proxy_num()) # print('final ', self.get_proxy_num()) # os._exit(-1) async def __process_second_html(self): urls = self.__proxy_urls[1] tasks = [self.__get_html(url) for url in urls] done = await asyncio.gather(*tasks) for res in done: if res: self.__universal_soup('second', res) async def __process_third_html(self): page_count = 2 urls = [self.__proxy_urls[2].format(_i+1) for _i in range(page_count)] tasks = [self.__get_html(url) for url in urls] done = await asyncio.gather(*tasks) for html in done: if html: soup = BeautifulSoup(html, features='html5lib') res = soup.find_all( 'td' ) for _i, item in enumerate(res): str_ = str(item.string) temp = re.findall('\d+\.\d+\.\d+\.\d+', str_) if temp: ip = temp[0] port = res[_i+1].string port = str(port) port = port.strip() new = ProxyPool.proxy(ip, port) if new not in self.__pool: self.__pool.append(new) print(f'process_third_html got {new.get_string_address()}') async def __process_fourth_html(self): ''' foreign website :return: ''' page_count = 6 urls = [self.__proxy_urls[3].format(_i+1) for _i in range(page_count)] tasks = [self.__get_html(url) for url in urls] done = await asyncio.gather(*tasks) import base64 for html in done: proxies = re.findall(r"Proxy\('(.*?)'\)", html) for proxy in proxies: temp = base64.b64decode(proxy).decode() ip = re.findall('\d+\.\d+\.\d+\.\d+', temp) ip = ip[0] port = re.findall(':\d+', temp) port = port[0] port = port[1:] new = ProxyPool.proxy(ip, port) if new not in self.__pool: self.__pool.append(new) print(f'process_fourth_html got {new.get_string_address()}') async def __process_fifth_html(self): ''' forbidden website :return: ''' proxy_count = 20 url = self.__proxy_urls[4].format(proxy_count) html = await self.__get_html(url) print(html) items = re.findall('\d+\.\d+\.\d+\.\d+:\d{1,5}', html) for item in items: ip = re.findall('\d+\.\d+\.\d+\.\d+', item) ip = ip[0] port = item.replace(ip, "") port = port[1:] new = ProxyPool.proxy(ip, port) if new not in self.__pool: self.__pool.append(new) print(f'process_fifth_html got {new.get_string_address()}') async def __process_sixth_html(self): page_count = 5 urls = [self.__proxy_urls[5].format(_i+1) for _i in range(page_count)] tasks = [self.__get_html(url) for url in urls] done = await asyncio.gather(*tasks) for html in done: if html: self.__universal_soup('sixth', html) async def __check_available(self, proxy:ProxyPool.proxy): proxy = proxy.get_string_address() print(f'checking {proxy}') try: # async with semaphore: async with aiohttp.ClientSession() as session: response = await session.get( url=self.__test_ip_url, proxy=proxy, timeout=default_check_proxy_timeout, headers=ToolBox.tool_get_random_headers() ) response_status = response.status except Exception as e: print(proxy, '11111111111111111', e) return (proxy, False) if response_status == 503: print(proxy, '22222222222222222') return (proxy, False) try: temp = await response.json() if response_status == 200 and temp.get("origin"): return (proxy, True) else: print(proxy, '3333333333333333') return (proxy, False) except Exception as e: print(proxy, '4444444444444444444', e) return (proxy, False) async def __timer_check(self): if self.get_proxy_num() != 0: tasks = [self.__check_available(item) for item in self.__pool] done = await asyncio.gather(*tasks) # done = await asyncio.wait(tasks) mark_up = [] mark_down = [] for item in done: if item[1]: mark_up.append(item[0]) else: mark_down.append(item[0]) for proxy in self.__pool: str_ = proxy.get_string_address() if str_ in mark_up: proxy.points += 3 elif str_ in mark_down: proxy.points -= 3 else: print('proxy pool is None') def __drive_timer_check(self): # while True: asyncio.run(self.__timer_check()) # time.sleep(self.__check_interval) print('Check done!', ToolBox.tool_get_current_time()) thread = threading.Timer(self.__check_interval, self.__drive_timer_check) thread.start() def get_proxy_num(self): # print(self.__proxy) return len(self.__pool) async def __timer_spider(self): tasks = [ self.__process_first_html(), self.__process_second_html(), self.__process_third_html(), # self.__process_fourth_html(), # self.__process_fifth_html(), self.__process_sixth_html(), ] await asyncio.gather(*tasks) def __drive_timer_spider(self): asyncio.run(self.__timer_spider()) print('Spider done!', ToolBox.tool_get_current_time()) thread = threading.Timer(self.__spider_interval, self.__drive_timer_spider) thread.start() def __print_status(self): info = f'pool_num:{self.get_proxy_num()} database_num:{self.__db.get_num()}' print(info, ToolBox.tool_get_current_time()) thread = threading.Timer(self.__print_interval, self.__print_status) thread.start() def start_work(self): thread_spider = threading.Thread(target=self.__drive_timer_spider) thread_check = threading.Thread(target=self.__drive_timer_check) thread_evaluate = threading.Thread(target=self.__evaluate_pool) thread_print = threading.Thread(target=self.__print_status) thread_spider.start() time.sleep(30) thread_check.start() thread_evaluate.start() thread_print.start() if __name__ == '__main__': test = proxy_pool() test.start_work() url = 'http://www.66ip.cn/nmtq.php?getnum=20' # url = r'https://www.kuaidaili.com/free/inha/1/' # import requests # import ToolBox # html = requests.get(url, headers=ToolBox.tool_get_random_headers()) # print(html.text)
test_socket_manager.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import time import uuid import os from unittest import mock from parlai.mturk.core.socket_manager import Packet, SocketManager from parlai.mturk.core.agents import AssignState import parlai.mturk.core.data_model as data_model import parlai.mturk.core.shared_utils as shared_utils import threading from websocket_server import WebsocketServer import json TEST_WORKER_ID_1 = 'TEST_WORKER_ID_1' TEST_ASSIGNMENT_ID_1 = 'TEST_ASSIGNMENT_ID_1' TEST_HIT_ID_1 = 'TEST_HIT_ID_1' TEST_WORKER_ID_2 = 'TEST_WORKER_ID_2' TEST_ASSIGNMENT_ID_2 = 'TEST_ASSIGNMENT_ID_2' TEST_HIT_ID_2 = 'TEST_HIT_ID_2' TEST_CONV_ID_1 = 'TEST_CONV_ID_1' FAKE_ID = 'BOGUS' MESSAGE_ID_1 = 'MESSAGE_ID_1' MESSAGE_ID_2 = 'MESSAGE_ID_2' MESSAGE_ID_3 = 'MESSAGE_ID_3' MESSAGE_ID_4 = 'MESSAGE_ID_4' COMMAND_ID_1 = 'COMMAND_ID_1' MESSAGE_TYPE = data_model.MESSAGE_TYPE_MESSAGE COMMAND_TYPE = data_model.MESSAGE_TYPE_COMMAND MESSAGE_1 = {'message_id': MESSAGE_ID_1, 'type': MESSAGE_TYPE} MESSAGE_2 = {'message_id': MESSAGE_ID_2, 'type': MESSAGE_TYPE} COMMAND_1 = {'message_id': COMMAND_ID_1, 'type': COMMAND_TYPE} AGENT_ID = 'AGENT_ID' ACT_1 = {'text': 'THIS IS A MESSAGE', 'id': AGENT_ID} ACT_2 = {'text': 'THIS IS A MESSAGE AGAIN', 'id': AGENT_ID} active_statuses = [ AssignState.STATUS_NONE, AssignState.STATUS_ONBOARDING, AssignState.STATUS_WAITING, AssignState.STATUS_IN_TASK, ] complete_statuses = [ AssignState.STATUS_DONE, AssignState.STATUS_DISCONNECT, AssignState.STATUS_PARTNER_DISCONNECT, AssignState.STATUS_PARTNER_DISCONNECT_EARLY, AssignState.STATUS_EXPIRED, AssignState.STATUS_RETURNED, ] statuses = active_statuses + complete_statuses TASK_GROUP_ID_1 = 'TASK_GROUP_ID_1' SocketManager.DEF_MISSED_PONGS = 3 SocketManager.HEARTBEAT_RATE = 0.6 SocketManager.DEF_DEAD_TIME = 0.6 SocketManager.ACK_TIME = {Packet.TYPE_ALIVE: 0.4, Packet.TYPE_MESSAGE: 0.2} shared_utils.THREAD_SHORT_SLEEP = 0.05 shared_utils.THREAD_MEDIUM_SLEEP = 0.15 class TestPacket(unittest.TestCase): """Various unit tests for the AssignState class""" ID = 'ID' SENDER_ID = 'SENDER_ID' RECEIVER_ID = 'RECEIVER_ID' ASSIGNMENT_ID = 'ASSIGNMENT_ID' DATA = 'DATA' CONVERSATION_ID = 'CONVERSATION_ID' REQUIRES_ACK = True BLOCKING = False ACK_FUNCTION = 'ACK_FUNCTION' def setUp(self): self.packet_1 = Packet(self.ID, Packet.TYPE_MESSAGE, self.SENDER_ID, self.RECEIVER_ID, self.ASSIGNMENT_ID, self.DATA, conversation_id=self.CONVERSATION_ID, requires_ack=self.REQUIRES_ACK, blocking=self.BLOCKING, ack_func=self.ACK_FUNCTION) self.packet_2 = Packet(self.ID, Packet.TYPE_HEARTBEAT, self.SENDER_ID, self.RECEIVER_ID, self.ASSIGNMENT_ID, self.DATA) self.packet_3 = Packet(self.ID, Packet.TYPE_ALIVE, self.SENDER_ID, self.RECEIVER_ID, self.ASSIGNMENT_ID, self.DATA) def tearDown(self): pass def test_packet_init(self): '''Test proper initialization of packet fields''' self.assertEqual(self.packet_1.id, self.ID) self.assertEqual(self.packet_1.type, Packet.TYPE_MESSAGE) self.assertEqual(self.packet_1.sender_id, self.SENDER_ID) self.assertEqual(self.packet_1.receiver_id, self.RECEIVER_ID) self.assertEqual(self.packet_1.assignment_id, self.ASSIGNMENT_ID) self.assertEqual(self.packet_1.data, self.DATA) self.assertEqual(self.packet_1.conversation_id, self.CONVERSATION_ID) self.assertEqual(self.packet_1.requires_ack, self.REQUIRES_ACK) self.assertEqual(self.packet_1.blocking, self.BLOCKING) self.assertEqual(self.packet_1.ack_func, self.ACK_FUNCTION) self.assertEqual(self.packet_1.status, Packet.STATUS_INIT) self.assertEqual(self.packet_2.id, self.ID) self.assertEqual(self.packet_2.type, Packet.TYPE_HEARTBEAT) self.assertEqual(self.packet_2.sender_id, self.SENDER_ID) self.assertEqual(self.packet_2.receiver_id, self.RECEIVER_ID) self.assertEqual(self.packet_2.assignment_id, self.ASSIGNMENT_ID) self.assertEqual(self.packet_2.data, self.DATA) self.assertIsNone(self.packet_2.conversation_id) self.assertFalse(self.packet_2.requires_ack) self.assertFalse(self.packet_2.blocking) self.assertIsNone(self.packet_2.ack_func) self.assertEqual(self.packet_2.status, Packet.STATUS_INIT) self.assertEqual(self.packet_3.id, self.ID) self.assertEqual(self.packet_3.type, Packet.TYPE_ALIVE) self.assertEqual(self.packet_3.sender_id, self.SENDER_ID) self.assertEqual(self.packet_3.receiver_id, self.RECEIVER_ID) self.assertEqual(self.packet_3.assignment_id, self.ASSIGNMENT_ID) self.assertEqual(self.packet_3.data, self.DATA) self.assertIsNone(self.packet_3.conversation_id) self.assertTrue(self.packet_3.requires_ack) self.assertTrue(self.packet_3.blocking) self.assertIsNone(self.packet_3.ack_func) self.assertEqual(self.packet_3.status, Packet.STATUS_INIT) def test_dict_conversion(self): '''Ensure packets can be converted to and from a representative dict''' converted_packet = Packet.from_dict(self.packet_1.as_dict()) self.assertEqual(self.packet_1.id, converted_packet.id) self.assertEqual(self.packet_1.type, converted_packet.type) self.assertEqual( self.packet_1.sender_id, converted_packet.sender_id) self.assertEqual( self.packet_1.receiver_id, converted_packet.receiver_id) self.assertEqual( self.packet_1.assignment_id, converted_packet.assignment_id) self.assertEqual(self.packet_1.data, converted_packet.data) self.assertEqual( self.packet_1.conversation_id, converted_packet.conversation_id) packet_dict = self.packet_1.as_dict() self.assertDictEqual( packet_dict, Packet.from_dict(packet_dict).as_dict()) def test_connection_ids(self): '''Ensure that connection ids are reported as we expect them''' sender_conn_id = '{}_{}'.format(self.SENDER_ID, self.ASSIGNMENT_ID) receiver_conn_id = '{}_{}'.format(self.RECEIVER_ID, self.ASSIGNMENT_ID) self.assertEqual( self.packet_1.get_sender_connection_id(), sender_conn_id) self.assertEqual( self.packet_1.get_receiver_connection_id(), receiver_conn_id) def test_packet_conversions(self): '''Ensure that packet copies and acts are produced properly''' # Copy important packet message_packet_copy = self.packet_1.new_copy() self.assertNotEqual(message_packet_copy.id, self.ID) self.assertNotEqual(message_packet_copy, self.packet_1) self.assertEqual(message_packet_copy.type, self.packet_1.type) self.assertEqual( message_packet_copy.sender_id, self.packet_1.sender_id) self.assertEqual( message_packet_copy.receiver_id, self.packet_1.receiver_id) self.assertEqual( message_packet_copy.assignment_id, self.packet_1.assignment_id) self.assertEqual(message_packet_copy.data, self.packet_1.data) self.assertEqual( message_packet_copy.conversation_id, self.packet_1.conversation_id) self.assertEqual( message_packet_copy.requires_ack, self.packet_1.requires_ack) self.assertEqual( message_packet_copy.blocking, self.packet_1.blocking) self.assertIsNone(message_packet_copy.ack_func) self.assertEqual(message_packet_copy.status, Packet.STATUS_INIT) # Copy non-important packet hb_packet_copy = self.packet_2.new_copy() self.assertNotEqual(hb_packet_copy.id, self.ID) self.assertNotEqual(hb_packet_copy, self.packet_2) self.assertEqual(hb_packet_copy.type, self.packet_2.type) self.assertEqual(hb_packet_copy.sender_id, self.packet_2.sender_id) self.assertEqual(hb_packet_copy.receiver_id, self.packet_2.receiver_id) self.assertEqual( hb_packet_copy.assignment_id, self.packet_2.assignment_id) self.assertEqual(hb_packet_copy.data, self.packet_2.data) self.assertEqual( hb_packet_copy.conversation_id, self.packet_2.conversation_id) self.assertEqual( hb_packet_copy.requires_ack, self.packet_2.requires_ack) self.assertEqual(hb_packet_copy.blocking, self.packet_2.blocking) self.assertIsNone(hb_packet_copy.ack_func) self.assertEqual(hb_packet_copy.status, Packet.STATUS_INIT) # ack important packet ack_packet = self.packet_1.get_ack() self.assertEqual(ack_packet.id, self.ID) self.assertEqual(ack_packet.type, Packet.TYPE_ACK) self.assertEqual(ack_packet.sender_id, self.RECEIVER_ID) self.assertEqual(ack_packet.receiver_id, self.SENDER_ID) self.assertEqual(ack_packet.assignment_id, self.ASSIGNMENT_ID) self.assertEqual(ack_packet.data, '') self.assertEqual(ack_packet.conversation_id, self.CONVERSATION_ID) self.assertFalse(ack_packet.requires_ack) self.assertFalse(ack_packet.blocking) self.assertIsNone(ack_packet.ack_func) self.assertEqual(ack_packet.status, Packet.STATUS_INIT) def test_packet_modifications(self): '''Ensure that packet copies and acts are produced properly''' # All operations return the packet self.assertEqual(self.packet_1.swap_sender(), self.packet_1) self.assertEqual( self.packet_1.set_type(Packet.TYPE_ACK), self.packet_1) self.assertEqual(self.packet_1.set_data(None), self.packet_1) # Ensure all of the operations worked self.assertEqual(self.packet_1.sender_id, self.RECEIVER_ID) self.assertEqual(self.packet_1.receiver_id, self.SENDER_ID) self.assertEqual(self.packet_1.type, Packet.TYPE_ACK) self.assertIsNone(self.packet_1.data) class MockSocket(): def __init__(self): self.last_messages = {} self.connected = False self.disconnected = False self.closed = False self.ws = None self.should_heartbeat = True self.fake_workers = [] self.port = None self.launch_socket() self.handlers = {} while self.ws is None: time.sleep(0.05) time.sleep(1) def send(self, packet): self.ws.send_message_to_all(packet) def close(self): if not self.closed: self.ws.server_close() self.ws.shutdown() self.closed = True def do_nothing(self, *args): pass def launch_socket(self): def on_message(client, server, message): if self.closed: raise Exception('Socket is already closed...') if message == '': return packet_dict = json.loads(message) if packet_dict['content']['id'] == 'WORLD_ALIVE': self.ws.send_message( client, json.dumps({'type': 'conn_success'})) self.connected = True elif packet_dict['content']['type'] == 'heartbeat': pong = packet_dict['content'].copy() pong['type'] = 'pong' self.ws.send_message(client, json.dumps({ 'type': data_model.SOCKET_ROUTE_PACKET_STRING, 'content': pong, })) if 'receiver_id' in packet_dict['content']: receiver_id = packet_dict['content']['receiver_id'] use_func = self.handlers.get(receiver_id, self.do_nothing) use_func(packet_dict['content']) def on_connect(client, server): pass def on_disconnect(client, server): self.disconnected = True def run_socket(*args): port = 3030 while self.port is None: try: self.ws = WebsocketServer(port, host='127.0.0.1') self.port = port except OSError: port += 1 self.ws.set_fn_client_left(on_disconnect) self.ws.set_fn_new_client(on_connect) self.ws.set_fn_message_received(on_message) self.ws.run_forever() self.listen_thread = threading.Thread( target=run_socket, name='Fake-Socket-Thread' ) self.listen_thread.daemon = True self.listen_thread.start() class MockAgent(object): """Class that pretends to be an MTurk agent interacting through the webpage by simulating the same commands that are sent from the core.html file. Exposes methods to use for testing and checking status """ def __init__(self, hit_id, assignment_id, worker_id, task_group_id): self.conversation_id = None self.id = None self.assignment_id = assignment_id self.hit_id = hit_id self.worker_id = worker_id self.some_agent_disconnected = False self.disconnected = False self.task_group_id = task_group_id self.ws = None self.always_beat = True self.send_acks = True self.ready = False self.wants_to_send = False def send_packet(self, packet): def callback(*args): pass event_name = data_model.SOCKET_ROUTE_PACKET_STRING self.ws.send(json.dumps({ 'type': event_name, 'content': packet.as_dict(), })) def register_to_socket(self, ws, on_ack, on_hb, on_msg): handler = self.make_packet_handler(on_ack, on_hb, on_msg) self.ws = ws self.ws.handlers[self.worker_id] = handler def make_packet_handler(self, on_ack, on_hb, on_msg): """A packet handler that properly sends heartbeats""" def handler_mock(pkt): if pkt['type'] == Packet.TYPE_ACK: self.ready = True packet = Packet.from_dict(pkt) on_ack(packet) elif pkt['type'] == Packet.TYPE_HEARTBEAT: packet = Packet.from_dict(pkt) on_hb(packet) if self.always_beat: self.send_heartbeat() elif pkt['type'] == Packet.TYPE_MESSAGE: packet = Packet.from_dict(pkt) if self.send_acks: self.send_packet(packet.get_ack()) on_msg(packet) elif pkt['type'] == Packet.TYPE_ALIVE: raise Exception('Invalid alive packet {}'.format(pkt)) else: raise Exception('Invalid Packet type {} received in {}'.format( pkt['type'], pkt )) return handler_mock def build_and_send_packet(self, packet_type, data): msg = { 'id': str(uuid.uuid4()), 'type': packet_type, 'sender_id': self.worker_id, 'assignment_id': self.assignment_id, 'conversation_id': self.conversation_id, 'receiver_id': '[World_' + self.task_group_id + ']', 'data': data } event_name = data_model.SOCKET_ROUTE_PACKET_STRING if (packet_type == Packet.TYPE_ALIVE): event_name = data_model.SOCKET_AGENT_ALIVE_STRING self.ws.send(json.dumps({ 'type': event_name, 'content': msg, })) return msg['id'] def send_message(self, text): data = { 'text': text, 'id': self.id, 'message_id': str(uuid.uuid4()), 'episode_done': False } self.wants_to_send = False return self.build_and_send_packet(Packet.TYPE_MESSAGE, data) def send_alive(self): data = { 'hit_id': self.hit_id, 'assignment_id': self.assignment_id, 'worker_id': self.worker_id, 'conversation_id': self.conversation_id } return self.build_and_send_packet(Packet.TYPE_ALIVE, data) def send_heartbeat(self): """Sends a heartbeat to the world""" hb = { 'id': str(uuid.uuid4()), 'receiver_id': '[World_' + self.task_group_id + ']', 'assignment_id': self.assignment_id, 'sender_id': self.worker_id, 'conversation_id': self.conversation_id, 'type': Packet.TYPE_HEARTBEAT, 'data': None } self.ws.send(json.dumps({ 'type': data_model.SOCKET_ROUTE_PACKET_STRING, 'content': hb, })) def wait_for_alive(self): last_time = time.time() while not self.ready: self.send_alive() time.sleep(0.5) assert time.time() - last_time < 10, \ 'Timed out wating for server to acknowledge {} alive'.format( self.worker_id ) class TestSocketManagerSetupAndFunctions(unittest.TestCase): """Unit/integration tests for starting up a socket""" def setUp(self): self.fake_socket = MockSocket() time.sleep(1) def tearDown(self): self.fake_socket.close() @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_init_and_reg_shutdown(self): '''Test initialization of a socket manager''' self.assertFalse(self.fake_socket.connected) # Callbacks should never trigger during proper setup and shutdown nop_called = False def nop(*args): nonlocal nop_called # noqa 999 we don't support py2 nop_called = True socket_manager = SocketManager('https://127.0.0.1', self.fake_socket.port, nop, nop, nop, TASK_GROUP_ID_1, 0.3, nop) self.assertTrue(self.fake_socket.connected) self.assertFalse(nop_called) # Test shutdown self.assertFalse(self.fake_socket.disconnected) self.assertFalse(socket_manager.is_shutdown) self.assertTrue(socket_manager.alive) socket_manager.shutdown() self.assertTrue(self.fake_socket.disconnected) self.assertTrue(socket_manager.is_shutdown) self.assertFalse(nop_called) def assertEqualBy(self, val_func, val, max_time): start_time = time.time() while val_func() != val: assert time.time() - start_time < max_time, \ "Value was not attained in specified time, was {} rather " \ "than {}".format(val_func(), val) time.sleep(0.1) @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_init_and_socket_shutdown(self): '''Test initialization of a socket manager with a failed shutdown''' self.assertFalse(self.fake_socket.connected) # Callbacks should never trigger during proper setup and shutdown nop_called = False def nop(*args): nonlocal nop_called # noqa 999 we don't support py2 nop_called = True server_death_called = False def server_death(*args): nonlocal server_death_called server_death_called = True socket_manager = SocketManager('https://127.0.0.1', self.fake_socket.port, nop, nop, nop, TASK_GROUP_ID_1, 0.4, server_death) self.assertTrue(self.fake_socket.connected) self.assertFalse(nop_called) self.assertFalse(server_death_called) # Test shutdown self.assertFalse(self.fake_socket.disconnected) self.assertFalse(socket_manager.is_shutdown) self.assertTrue(socket_manager.alive) self.fake_socket.close() self.assertEqualBy(lambda: socket_manager.alive, False, 8 * socket_manager.HEARTBEAT_RATE) self.assertEqualBy(lambda: server_death_called, True, 4 * socket_manager.HEARTBEAT_RATE) self.assertFalse(nop_called) socket_manager.shutdown() @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_init_and_socket_shutdown_then_restart(self): '''Test restoring connection to a socket''' self.assertFalse(self.fake_socket.connected) # Callbacks should never trigger during proper setup and shutdown nop_called = False def nop(*args): nonlocal nop_called # noqa 999 we don't support py2 nop_called = True server_death_called = False def server_death(*args): nonlocal server_death_called server_death_called = True socket_manager = SocketManager('https://127.0.0.1', self.fake_socket.port, nop, nop, nop, TASK_GROUP_ID_1, 0.4, server_death) self.assertTrue(self.fake_socket.connected) self.assertFalse(nop_called) self.assertFalse(server_death_called) # Test shutdown self.assertFalse(self.fake_socket.disconnected) self.assertFalse(socket_manager.is_shutdown) self.assertTrue(socket_manager.alive) self.fake_socket.close() self.assertEqualBy(lambda: socket_manager.alive, False, 8 * socket_manager.HEARTBEAT_RATE) self.assertFalse(socket_manager.alive) self.fake_socket = MockSocket() self.assertEqualBy(lambda: socket_manager.alive, True, 4 * socket_manager.HEARTBEAT_RATE) self.assertFalse(nop_called) self.assertFalse(server_death_called) socket_manager.shutdown() def test_init_world_dead(self): '''Test initialization of a socket manager with a failed startup''' self.assertFalse(self.fake_socket.connected) self.fake_socket.close() # Callbacks should never trigger during proper setup and shutdown nop_called = False def nop(*args): nonlocal nop_called # noqa 999 we don't support py2 nop_called = True server_death_called = False def server_death(*args): nonlocal server_death_called server_death_called = True with self.assertRaises(ConnectionRefusedError): socket_manager = SocketManager('https://127.0.0.1', self.fake_socket.port, nop, nop, nop, TASK_GROUP_ID_1, 0.4, server_death) self.assertIsNone(socket_manager) self.assertFalse(nop_called) self.assertTrue(server_death_called) class TestSocketManagerRoutingFunctionality(unittest.TestCase): ID = 'ID' SENDER_ID = 'SENDER_ID' ASSIGNMENT_ID = 'ASSIGNMENT_ID' DATA = 'DATA' CONVERSATION_ID = 'CONVERSATION_ID' REQUIRES_ACK = True BLOCKING = False ACK_FUNCTION = 'ACK_FUNCTION' WORLD_ID = '[World_{}]'.format(TASK_GROUP_ID_1) def on_alive(self, packet): self.alive_packet = packet def on_message(self, packet): self.message_packet = packet def on_worker_death(self, worker_id, assignment_id): self.dead_worker_id = worker_id self.dead_assignment_id = assignment_id def on_server_death(self): self.server_died = True def setUp(self): self.AGENT_HEARTBEAT_PACKET = Packet( self.ID, Packet.TYPE_HEARTBEAT, self.SENDER_ID, self.WORLD_ID, self.ASSIGNMENT_ID, self.DATA, self.CONVERSATION_ID) self.AGENT_ALIVE_PACKET = Packet( MESSAGE_ID_1, Packet.TYPE_ALIVE, self.SENDER_ID, self.WORLD_ID, self.ASSIGNMENT_ID, self.DATA, self.CONVERSATION_ID) self.MESSAGE_SEND_PACKET_1 = Packet( MESSAGE_ID_2, Packet.TYPE_MESSAGE, self.WORLD_ID, self.SENDER_ID, self.ASSIGNMENT_ID, self.DATA, self.CONVERSATION_ID) self.MESSAGE_SEND_PACKET_2 = Packet( MESSAGE_ID_3, Packet.TYPE_MESSAGE, self.WORLD_ID, self.SENDER_ID, self.ASSIGNMENT_ID, self.DATA, self.CONVERSATION_ID, requires_ack=False) self.MESSAGE_SEND_PACKET_3 = Packet( MESSAGE_ID_4, Packet.TYPE_MESSAGE, self.WORLD_ID, self.SENDER_ID, self.ASSIGNMENT_ID, self.DATA, self.CONVERSATION_ID, blocking=False) self.fake_socket = MockSocket() time.sleep(0.3) self.alive_packet = None self.message_packet = None self.dead_worker_id = None self.dead_assignment_id = None self.server_died = False self.socket_manager = SocketManager( 'https://127.0.0.1', self.fake_socket.port, self.on_alive, self.on_message, self.on_worker_death, TASK_GROUP_ID_1, 1, self.on_server_death) def tearDown(self): self.socket_manager.shutdown() self.fake_socket.close() @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_init_state(self): '''Ensure all of the initial state of the socket_manager is ready''' self.assertEqual(self.socket_manager.server_url, 'https://127.0.0.1') self.assertEqual(self.socket_manager.port, self.fake_socket.port) self.assertEqual(self.socket_manager.alive_callback, self.on_alive) self.assertEqual(self.socket_manager.message_callback, self.on_message) self.assertEqual(self.socket_manager.socket_dead_callback, self.on_worker_death) self.assertEqual(self.socket_manager.task_group_id, TASK_GROUP_ID_1) self.assertEqual(self.socket_manager.missed_pongs, 1 + (1 / SocketManager.HEARTBEAT_RATE)) self.assertIsNotNone(self.socket_manager.ws) self.assertTrue(self.socket_manager.keep_running) self.assertIsNotNone(self.socket_manager.listen_thread) self.assertDictEqual(self.socket_manager.queues, {}) self.assertDictEqual(self.socket_manager.threads, {}) self.assertDictEqual(self.socket_manager.run, {}) self.assertDictEqual(self.socket_manager.last_sent_heartbeat_time, {}) self.assertDictEqual(self.socket_manager.last_received_heartbeat, {}) self.assertDictEqual(self.socket_manager.pongs_without_heartbeat, {}) self.assertDictEqual(self.socket_manager.packet_map, {}) self.assertTrue(self.socket_manager.alive) self.assertFalse(self.socket_manager.is_shutdown) self.assertEqual(self.socket_manager.get_my_sender_id(), self.WORLD_ID) @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_needed_heartbeat(self): '''Ensure needed heartbeat sends heartbeats at the right time''' self.socket_manager._safe_send = mock.MagicMock() connection_id = self.AGENT_HEARTBEAT_PACKET.get_sender_connection_id() # Ensure no failure under uninitialized cases self.socket_manager._send_needed_heartbeat(connection_id) self.socket_manager.last_received_heartbeat[connection_id] = None self.socket_manager._send_needed_heartbeat(connection_id) self.socket_manager._safe_send.assert_not_called() # assert not called when called too recently self.socket_manager.last_received_heartbeat[connection_id] = \ self.AGENT_HEARTBEAT_PACKET self.socket_manager.last_sent_heartbeat_time[connection_id] = \ time.time() + 10 self.socket_manager._send_needed_heartbeat(connection_id) self.socket_manager._safe_send.assert_not_called() # Assert called when supposed to self.socket_manager.last_sent_heartbeat_time[connection_id] = \ time.time() - SocketManager.HEARTBEAT_RATE self.assertGreater( time.time() - self.socket_manager.last_sent_heartbeat_time[connection_id], SocketManager.HEARTBEAT_RATE) self.socket_manager._send_needed_heartbeat(connection_id) self.assertLess( time.time() - self.socket_manager.last_sent_heartbeat_time[connection_id], SocketManager.HEARTBEAT_RATE) used_packet_json = self.socket_manager._safe_send.call_args[0][0] used_packet_dict = json.loads(used_packet_json) self.assertEqual( used_packet_dict['type'], data_model.SOCKET_ROUTE_PACKET_STRING) used_packet = Packet.from_dict(used_packet_dict['content']) self.assertNotEqual(self.AGENT_HEARTBEAT_PACKET.id, used_packet.id) self.assertEqual(used_packet.type, Packet.TYPE_HEARTBEAT) self.assertEqual(used_packet.sender_id, self.WORLD_ID) self.assertEqual(used_packet.receiver_id, self.SENDER_ID) self.assertEqual(used_packet.assignment_id, self.ASSIGNMENT_ID) self.assertEqual(used_packet.data, '') self.assertEqual(used_packet.conversation_id, self.CONVERSATION_ID) self.assertEqual(used_packet.requires_ack, False) self.assertEqual(used_packet.blocking, False) @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_ack_send(self): '''Ensure acks are being properly created and sent''' self.socket_manager._safe_send = mock.MagicMock() self.socket_manager._send_ack(self.AGENT_ALIVE_PACKET) used_packet_json = self.socket_manager._safe_send.call_args[0][0] used_packet_dict = json.loads(used_packet_json) self.assertEqual( used_packet_dict['type'], data_model.SOCKET_ROUTE_PACKET_STRING) used_packet = Packet.from_dict(used_packet_dict['content']) self.assertEqual(self.AGENT_ALIVE_PACKET.id, used_packet.id) self.assertEqual(used_packet.type, Packet.TYPE_ACK) self.assertEqual(used_packet.sender_id, self.WORLD_ID) self.assertEqual(used_packet.receiver_id, self.SENDER_ID) self.assertEqual(used_packet.assignment_id, self.ASSIGNMENT_ID) self.assertEqual(used_packet.conversation_id, self.CONVERSATION_ID) self.assertEqual(used_packet.requires_ack, False) self.assertEqual(used_packet.blocking, False) self.assertEqual(self.AGENT_ALIVE_PACKET.status, Packet.STATUS_SENT) def _send_packet_in_background(self, packet, send_time): '''creates a thread to handle waiting for a packet send''' def do_send(): self.socket_manager._send_packet( packet, packet.get_receiver_connection_id(), send_time ) self.sent = True send_thread = threading.Thread(target=do_send, daemon=True) send_thread.start() time.sleep(0.02) @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_blocking_ack_packet_send(self): '''Checks to see if ack'ed blocking packets are working properly''' self.socket_manager._safe_send = mock.MagicMock() self.socket_manager._safe_put = mock.MagicMock() self.sent = False # Test a blocking acknowledged packet send_time = time.time() self.assertEqual(self.MESSAGE_SEND_PACKET_1.status, Packet.STATUS_INIT) self._send_packet_in_background(self.MESSAGE_SEND_PACKET_1, send_time) self.assertEqual(self.MESSAGE_SEND_PACKET_1.status, Packet.STATUS_SENT) self.socket_manager._safe_send.assert_called_once() connection_id = self.MESSAGE_SEND_PACKET_1.get_receiver_connection_id() self.socket_manager._safe_put.assert_called_once_with( connection_id, (send_time, self.MESSAGE_SEND_PACKET_1)) self.assertTrue(self.sent) self.socket_manager._safe_send.reset_mock() self.socket_manager._safe_put.reset_mock() # Send it again - end outcome should be a call to send only # with sent set self.MESSAGE_SEND_PACKET_1.status = Packet.STATUS_ACK self._send_packet_in_background(self.MESSAGE_SEND_PACKET_1, send_time) self.socket_manager._safe_send.assert_not_called() self.socket_manager._safe_put.assert_not_called() @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_non_blocking_ack_packet_send(self): '''Checks to see if ack'ed non-blocking packets are working''' self.socket_manager._safe_send = mock.MagicMock() self.socket_manager._safe_put = mock.MagicMock() self.sent = False # Test a blocking acknowledged packet send_time = time.time() self.assertEqual(self.MESSAGE_SEND_PACKET_3.status, Packet.STATUS_INIT) self._send_packet_in_background(self.MESSAGE_SEND_PACKET_3, send_time) self.assertEqual(self.MESSAGE_SEND_PACKET_3.status, Packet.STATUS_SENT) self.socket_manager._safe_send.assert_called_once() self.socket_manager._safe_put.assert_called_once() self.assertTrue(self.sent) call_args = self.socket_manager._safe_put.call_args[0] connection_id = call_args[0] queue_item = call_args[1] self.assertEqual( connection_id, self.MESSAGE_SEND_PACKET_3.get_receiver_connection_id()) expected_send_time = \ send_time + SocketManager.ACK_TIME[self.MESSAGE_SEND_PACKET_3.type] self.assertAlmostEqual(queue_item[0], expected_send_time, places=2) self.assertEqual(queue_item[1], self.MESSAGE_SEND_PACKET_3) used_packet_json = self.socket_manager._safe_send.call_args[0][0] used_packet_dict = json.loads(used_packet_json) self.assertEqual( used_packet_dict['type'], data_model.SOCKET_ROUTE_PACKET_STRING) self.assertDictEqual(used_packet_dict['content'], self.MESSAGE_SEND_PACKET_3.as_dict()) @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_non_ack_packet_send(self): '''Checks to see if non-ack'ed packets are working''' self.socket_manager._safe_send = mock.MagicMock() self.socket_manager._safe_put = mock.MagicMock() self.sent = False # Test a blocking acknowledged packet send_time = time.time() self.assertEqual(self.MESSAGE_SEND_PACKET_2.status, Packet.STATUS_INIT) self._send_packet_in_background(self.MESSAGE_SEND_PACKET_2, send_time) self.assertEqual(self.MESSAGE_SEND_PACKET_2.status, Packet.STATUS_SENT) self.socket_manager._safe_send.assert_called_once() self.socket_manager._safe_put.assert_not_called() self.assertTrue(self.sent) used_packet_json = self.socket_manager._safe_send.call_args[0][0] used_packet_dict = json.loads(used_packet_json) self.assertEqual( used_packet_dict['type'], data_model.SOCKET_ROUTE_PACKET_STRING) self.assertDictEqual(used_packet_dict['content'], self.MESSAGE_SEND_PACKET_2.as_dict()) @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_simple_packet_channel_management(self): '''Ensure that channels are created, managed, and then removed as expected ''' self.socket_manager._safe_put = mock.MagicMock() use_packet = self.MESSAGE_SEND_PACKET_1 worker_id = use_packet.receiver_id assignment_id = use_packet.assignment_id # Open a channel and assert it is there self.socket_manager.open_channel(worker_id, assignment_id) time.sleep(0.1) connection_id = use_packet.get_receiver_connection_id() self.assertTrue(self.socket_manager.run[connection_id]) self.assertIsNotNone(self.socket_manager.queues[connection_id]) self.assertEqual( self.socket_manager.last_sent_heartbeat_time[connection_id], 0) self.assertEqual( self.socket_manager.pongs_without_heartbeat[connection_id], 0) self.assertIsNone( self.socket_manager.last_received_heartbeat[connection_id]) self.assertTrue(self.socket_manager.socket_is_open(connection_id)) self.assertFalse(self.socket_manager.socket_is_open(FAKE_ID)) # Send a bad packet, ensure it is ignored resp = self.socket_manager.queue_packet(self.AGENT_ALIVE_PACKET) self.socket_manager._safe_put.assert_not_called() self.assertFalse(resp) self.assertNotIn(self.AGENT_ALIVE_PACKET.id, self.socket_manager.packet_map) # Send a packet to an open socket, ensure it got queued resp = self.socket_manager.queue_packet(use_packet) self.socket_manager._safe_put.assert_called_once() self.assertIn(use_packet.id, self.socket_manager.packet_map) self.assertTrue(resp) # Assert we can get the status of a packet in the map, but not # existing doesn't throw an error self.assertEqual(self.socket_manager.get_status(use_packet.id), use_packet.status) self.assertEqual(self.socket_manager.get_status(FAKE_ID), Packet.STATUS_NONE) # Assert that closing a thread does the correct cleanup work self.socket_manager.close_channel(connection_id) time.sleep(0.2) self.assertFalse(self.socket_manager.run[connection_id]) self.assertNotIn(connection_id, self.socket_manager.queues) self.assertNotIn(connection_id, self.socket_manager.threads) self.assertNotIn(use_packet.id, self.socket_manager.packet_map) # Assert that opening multiple threads and closing them is possible self.socket_manager.open_channel(worker_id, assignment_id) self.socket_manager.open_channel(worker_id + '2', assignment_id) time.sleep(0.1) self.assertEqual(len(self.socket_manager.queues), 2) self.socket_manager.close_all_channels() time.sleep(0.1) self.assertEqual(len(self.socket_manager.queues), 0) @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_safe_put(self): '''Test safe put and queue retrieval mechanisms''' self.socket_manager._send_packet = mock.MagicMock() use_packet = self.MESSAGE_SEND_PACKET_1 worker_id = use_packet.receiver_id assignment_id = use_packet.assignment_id connection_id = use_packet.get_receiver_connection_id() # Open a channel and assert it is there self.socket_manager.open_channel(worker_id, assignment_id) send_time = time.time() self.socket_manager._safe_put(connection_id, (send_time, use_packet)) # Wait for the sending thread to try to pull the packet from the queue time.sleep(0.3) # Ensure the right packet was popped and sent. self.socket_manager._send_packet.assert_called_once() call_args = self.socket_manager._send_packet.call_args[0] self.assertEqual(use_packet, call_args[0]) self.assertEqual(connection_id, call_args[1]) self.assertEqual(send_time, call_args[2]) self.socket_manager.close_all_channels() time.sleep(0.1) self.socket_manager._safe_put(connection_id, (send_time, use_packet)) self.assertEqual(use_packet.status, Packet.STATUS_FAIL) class TestSocketManagerMessageHandling(unittest.TestCase): '''Test sending messages to the world and then to each of two agents, along with failure cases for each ''' def on_alive(self, packet): self.alive_packet = packet self.socket_manager.open_channel( packet.sender_id, packet.assignment_id) def on_message(self, packet): self.message_packet = packet def on_worker_death(self, worker_id, assignment_id): self.dead_worker_id = worker_id self.dead_assignment_id = assignment_id def on_server_death(self): self.server_died = True def assertEqualBy(self, val_func, val, max_time): start_time = time.time() while val_func() != val: assert time.time() - start_time < max_time, \ "Value was not attained in specified time" time.sleep(0.1) def setUp(self): self.fake_socket = MockSocket() time.sleep(0.3) self.agent1 = MockAgent(TEST_HIT_ID_1, TEST_ASSIGNMENT_ID_1, TEST_WORKER_ID_1, TASK_GROUP_ID_1) self.agent2 = MockAgent(TEST_HIT_ID_2, TEST_ASSIGNMENT_ID_2, TEST_WORKER_ID_2, TASK_GROUP_ID_1) self.alive_packet = None self.message_packet = None self.dead_worker_id = None self.dead_assignment_id = None self.server_died = False self.socket_manager = SocketManager( 'https://127.0.0.1', 3030, self.on_alive, self.on_message, self.on_worker_death, TASK_GROUP_ID_1, 1, self.on_server_death) def tearDown(self): self.socket_manager.shutdown() self.fake_socket.close() @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_alive_send_and_disconnect(self): acked_packet = None incoming_hb = None message_packet = None hb_count = 0 def on_ack(*args): nonlocal acked_packet acked_packet = args[0] def on_hb(*args): nonlocal incoming_hb, hb_count incoming_hb = args[0] hb_count += 1 def on_msg(*args): nonlocal message_packet message_packet = args[0] self.agent1.register_to_socket(self.fake_socket, on_ack, on_hb, on_msg) self.assertIsNone(acked_packet) self.assertIsNone(incoming_hb) self.assertIsNone(message_packet) self.assertEqual(hb_count, 0) # Assert alive is registered alive_id = self.agent1.send_alive() self.assertEqualBy(lambda: acked_packet is None, False, 8) self.assertIsNone(incoming_hb) self.assertIsNone(message_packet) self.assertIsNone(self.message_packet) self.assertEqualBy(lambda: self.alive_packet is None, False, 8) self.assertEqual(self.alive_packet.id, alive_id) self.assertEqual(acked_packet.id, alive_id, 'Alive was not acked') acked_packet = None # assert sending heartbeats actually works, and that heartbeats don't # get acked self.agent1.send_heartbeat() self.assertEqualBy(lambda: incoming_hb is None, False, 8) self.assertIsNone(acked_packet) self.assertGreater(hb_count, 0) # Test message send from agent test_message_text_1 = 'test_message_text_1' msg_id = self.agent1.send_message(test_message_text_1) self.assertEqualBy(lambda: self.message_packet is None, False, 8) self.assertEqualBy(lambda: acked_packet is None, False, 8) self.assertEqual(self.message_packet.id, acked_packet.id) self.assertEqual(self.message_packet.id, msg_id) self.assertEqual(self.message_packet.data['text'], test_message_text_1) # Test message send to agent manager_message_id = 'message_id_from_manager' test_message_text_2 = 'test_message_text_2' message_send_packet = Packet( manager_message_id, Packet.TYPE_MESSAGE, self.socket_manager.get_my_sender_id(), TEST_WORKER_ID_1, TEST_ASSIGNMENT_ID_1, test_message_text_2, 't2') self.socket_manager.queue_packet(message_send_packet) self.assertEqualBy(lambda: message_packet is None, False, 8) self.assertEqual(message_packet.id, manager_message_id) self.assertEqual(message_packet.data, test_message_text_2) self.assertIn(manager_message_id, self.socket_manager.packet_map) self.assertEqualBy( lambda: self.socket_manager.packet_map[manager_message_id].status, Packet.STATUS_ACK, 6, ) # Test agent disconnect self.agent1.always_beat = False self.assertEqualBy(lambda: self.dead_worker_id, TEST_WORKER_ID_1, 8) self.assertEqual(self.dead_assignment_id, TEST_ASSIGNMENT_ID_1) self.assertGreater(hb_count, 1) @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_failed_ack_resend(self): '''Ensures when a message from the manager is dropped, it gets retried until it works as long as there hasn't been a disconnect ''' acked_packet = None incoming_hb = None message_packet = None hb_count = 0 def on_ack(*args): nonlocal acked_packet acked_packet = args[0] def on_hb(*args): nonlocal incoming_hb, hb_count incoming_hb = args[0] hb_count += 1 def on_msg(*args): nonlocal message_packet message_packet = args[0] self.agent1.register_to_socket(self.fake_socket, on_ack, on_hb, on_msg) self.assertIsNone(acked_packet) self.assertIsNone(incoming_hb) self.assertIsNone(message_packet) self.assertEqual(hb_count, 0) # Assert alive is registered alive_id = self.agent1.send_alive() self.assertEqualBy(lambda: acked_packet is None, False, 8) self.assertIsNone(incoming_hb) self.assertIsNone(message_packet) self.assertIsNone(self.message_packet) self.assertEqualBy(lambda: self.alive_packet is None, False, 8) self.assertEqual(self.alive_packet.id, alive_id) self.assertEqual(acked_packet.id, alive_id, 'Alive was not acked') acked_packet = None # assert sending heartbeats actually works, and that heartbeats don't # get acked self.agent1.send_heartbeat() self.assertEqualBy(lambda: incoming_hb is None, False, 8) self.assertIsNone(acked_packet) self.assertGreater(hb_count, 0) # Test message send to agent manager_message_id = 'message_id_from_manager' test_message_text_2 = 'test_message_text_2' self.agent1.send_acks = False message_send_packet = Packet( manager_message_id, Packet.TYPE_MESSAGE, self.socket_manager.get_my_sender_id(), TEST_WORKER_ID_1, TEST_ASSIGNMENT_ID_1, test_message_text_2, 't2') self.socket_manager.queue_packet(message_send_packet) self.assertEqualBy(lambda: message_packet is None, False, 8) self.assertEqual(message_packet.id, manager_message_id) self.assertEqual(message_packet.data, test_message_text_2) self.assertIn(manager_message_id, self.socket_manager.packet_map) self.assertNotEqual( self.socket_manager.packet_map[manager_message_id].status, Packet.STATUS_ACK, ) message_packet = None self.agent1.send_acks = True self.assertEqualBy(lambda: message_packet is None, False, 8) self.assertEqual(message_packet.id, manager_message_id) self.assertEqual(message_packet.data, test_message_text_2) self.assertIn(manager_message_id, self.socket_manager.packet_map) self.assertEqualBy( lambda: self.socket_manager.packet_map[manager_message_id].status, Packet.STATUS_ACK, 6, ) @unittest.skipIf(os.environ.get('TRAVIS'), 'Travis fails socket setup') def test_one_agent_disconnect_other_alive(self): acked_packet = None incoming_hb = None message_packet = None hb_count = 0 def on_ack(*args): nonlocal acked_packet acked_packet = args[0] def on_hb(*args): nonlocal incoming_hb, hb_count incoming_hb = args[0] hb_count += 1 def on_msg(*args): nonlocal message_packet message_packet = args[0] self.agent1.register_to_socket(self.fake_socket, on_ack, on_hb, on_msg) self.agent2.register_to_socket(self.fake_socket, on_ack, on_hb, on_msg) self.assertIsNone(acked_packet) self.assertIsNone(incoming_hb) self.assertIsNone(message_packet) self.assertEqual(hb_count, 0) # Assert alive is registered self.agent1.send_alive() self.agent2.send_alive() self.assertEqualBy(lambda: acked_packet is None, False, 8) self.assertIsNone(incoming_hb) self.assertIsNone(message_packet) # Start sending heartbeats self.agent1.send_heartbeat() self.agent2.send_heartbeat() # Kill second agent self.agent2.always_beat = False self.assertEqualBy(lambda: self.dead_worker_id, TEST_WORKER_ID_2, 8) self.assertEqual(self.dead_assignment_id, TEST_ASSIGNMENT_ID_2) # Run rest of tests # Test message send from agent test_message_text_1 = 'test_message_text_1' msg_id = self.agent1.send_message(test_message_text_1) self.assertEqualBy(lambda: self.message_packet is None, False, 8) self.assertEqualBy(lambda: acked_packet is None, False, 8) self.assertEqual(self.message_packet.id, acked_packet.id) self.assertEqual(self.message_packet.id, msg_id) self.assertEqual(self.message_packet.data['text'], test_message_text_1) # Test message send to agent manager_message_id = 'message_id_from_manager' test_message_text_2 = 'test_message_text_2' message_send_packet = Packet( manager_message_id, Packet.TYPE_MESSAGE, self.socket_manager.get_my_sender_id(), TEST_WORKER_ID_1, TEST_ASSIGNMENT_ID_1, test_message_text_2, 't2') self.socket_manager.queue_packet(message_send_packet) self.assertEqualBy(lambda: message_packet is None, False, 8) self.assertEqual(message_packet.id, manager_message_id) self.assertEqual(message_packet.data, test_message_text_2) self.assertIn(manager_message_id, self.socket_manager.packet_map) self.assertEqualBy( lambda: self.socket_manager.packet_map[manager_message_id].status, Packet.STATUS_ACK, 6, ) # Test agent disconnect self.agent1.always_beat = False self.assertEqualBy(lambda: self.dead_worker_id, TEST_WORKER_ID_1, 8) self.assertEqual(self.dead_assignment_id, TEST_ASSIGNMENT_ID_1) if __name__ == '__main__': unittest.main(buffer=True)
sync_blocking.py
#!usr/bin/env python3 # -*- coding: utf-8 -*- """ Test module to implement synchronous blocking to address race condition among threads, using threading.Lock and threading.Semaphore/threading.BoundedSemaphore. """ __author__ = 'Ziang Lu' import time from threading import BoundedSemaphore, Lock, Semaphore, Thread, current_thread balance = 0 # Lock lock = Lock() def thread_func(n: int) -> None: """ Dummy function to be run within a thread. :param n: int :return: None """ for _ in range(10000000): # Note that Lock objects can be used in a traditional way, i.e., via # acquire() and release() methods, but it can also simply be used as a # context manager, as a syntax sugar with lock: change_balance(n) def change_balance(n: int) -> None: """ Changes the balance. :param n: int :return: None """ global balance balance += n balance -= n # 先存后取, 效果应该为无变化 th1 = Thread(target=thread_func, args=(5,)) th2 = Thread(target=thread_func, args=(8,)) th1.start() th2.start() th1.join() th2.join() print(balance) # Output: # 0 # Semaphore # 管理一个内置的计数器, 每当调用acquire()时-1, 调用release()时+1 # 计数器不能小于0; 当计数器为0时, acquire()将阻塞线程至同步锁定状态, 直到其他线程调用 # release() # 注意: 同时acquire semaphore的线程仍然可能会有race condition # BoundedSemaphore # 在Semaphore的基础上, 不允许计数器超过initial value (设置上限) # A bounded semaphore with initial value 2 bounded_sema = BoundedSemaphore(value=2) def func() -> None: """ Dummy function. :return: None """ th_name = current_thread().name # 请求Semaphore, 成功后计数器-1 print(f'{th_name} acquiring semaphore...') # Note that BoundedSemaphore objects can be used in a traditional way, i.e., # via acquire() and release() methods, but it can also simply be used as a # context manager, as a syntax sugar with bounded_sema: # 释放Semaphore的时候, 计数器+1 print(f'{th_name} gets semaphore') time.sleep(4) threads = [Thread(target=func) for _ in range(4)] for th in threads: th.start() for th in threads: th.join() # Output: # Thread-3 acquiring semaphore... # Thread-3 gets semaphore # Thread-4 acquiring semaphore... # Thread-4 gets semaphore # Thread-5 acquiring semaphore... # Thread-6 acquiring semaphore... # Will block here for 4 seconds, waiting for the semaphore # Thread-5 gets semaphore # Thread-6 gets semaphore
exchange_rate.py
from datetime import datetime import inspect import requests import sys import os import json import pkgutil from threading import Thread import time import csv import decimal from decimal import Decimal as PyDecimal # Qt 5.12 also exports Decimal from collections import defaultdict from .bitcoin import COIN from .i18n import _ from .util import PrintError, ThreadJob, print_error, inv_base_units DEFAULT_ENABLED = False DEFAULT_CURRENCY = "USD" DEFAULT_EXCHANGE = "CoinGecko" # Note the exchange here should ideally also support history rates # See https://en.wikipedia.org/wiki/ISO_4217 CCY_PRECISIONS = {'BHD': 3, 'BIF': 0, 'BYR': 0, 'CLF': 4, 'CLP': 0, 'CVE': 0, 'DJF': 0, 'GNF': 0, 'IQD': 3, 'ISK': 0, 'JOD': 3, 'JPY': 0, 'KMF': 0, 'KRW': 0, 'KWD': 3, 'LYD': 3, 'MGA': 1, 'MRO': 1, 'OMR': 3, 'PYG': 0, 'RWF': 0, 'TND': 3, 'UGX': 0, 'UYI': 0, 'VND': 0, 'VUV': 0, 'XAF': 0, 'XAU': 4, 'XOF': 0, 'XPF': 0} class ExchangeBase(PrintError): def __init__(self, on_quotes, on_history): self.history = {} self.history_timestamps = defaultdict(float) self.quotes = {} self.on_quotes = on_quotes self.on_history = on_history def get_json(self, site, get_string): # APIs must have https url = ''.join(['https://', site, get_string]) response = requests.request('GET', url, headers={'User-Agent' : 'Electron Cash'}, timeout=10) if response.status_code != 200: raise RuntimeWarning("Response status: " + str(response.status_code)) return response.json() def get_csv(self, site, get_string): url = ''.join(['https://', site, get_string]) response = requests.request('GET', url, headers={'User-Agent' : 'Electron-Cash'}) if response.status_code != 200: raise RuntimeWarning("Response status: " + str(response.status_code)) reader = csv.DictReader(response.content.decode().split('\n')) return list(reader) def name(self): return self.__class__.__name__ def update_safe(self, ccy): try: self.print_error("getting fx quotes for", ccy) self.quotes = self.get_rates(ccy) self.print_error("received fx quotes") except Exception as e: self.print_error("failed fx quotes:", e) self.on_quotes() def update(self, ccy): t = Thread(target=self.update_safe, args=(ccy,), daemon=True) t.start() def read_historical_rates(self, ccy, cache_dir): filename = self._get_cache_filename(ccy, cache_dir) h, timestamp = None, 0.0 if os.path.exists(filename): timestamp = os.stat(filename).st_mtime try: with open(filename, 'r', encoding='utf-8') as f: h = json.loads(f.read()) if h: self.print_error("read_historical_rates: returning cached history from", filename) except Exception as e: self.print_error("read_historical_rates: error", repr(e)) h = h or None return h, timestamp def _get_cache_filename(self, ccy, cache_dir): return os.path.join(cache_dir, self.name() + '_' + ccy) @staticmethod def _is_timestamp_old(timestamp): HOUR = 60.0*60.0 # number of seconds in an hour return time.time() - timestamp >= 24.0 * HOUR # check history rates every 24 hours, as the granularity is per-day anyway def is_historical_rate_old(self, ccy): return self._is_timestamp_old(self.history_timestamps.get(ccy, 0.0)) def _cache_historical_rates(self, h, ccy, cache_dir): ''' Writes the history, h, to the cache file. Catches its own exceptions and always returns successfully, even if the write process failed. ''' wroteBytes, filename = 0, '(none)' try: filename = self._get_cache_filename(ccy, cache_dir) with open(filename, 'w', encoding='utf-8') as f: f.write(json.dumps(h)) wroteBytes = os.stat(filename).st_size except Exception as e: self.print_error("cache_historical_rates error:", repr(e)) return False self.print_error(f"cache_historical_rates: wrote {wroteBytes} bytes to file {filename}") return True def get_historical_rates_safe(self, ccy, cache_dir): h, timestamp = self.read_historical_rates(ccy, cache_dir) if not h or self._is_timestamp_old(timestamp): try: self.print_error("requesting fx history for", ccy) h = self.request_history(ccy) self.print_error("received fx history for", ccy) if not h: # Paranoia: No data; abort early rather than write out an # empty file raise RuntimeWarning(f"received empty history for {ccy}") self._cache_historical_rates(h, ccy, cache_dir) except Exception as e: self.print_error("failed fx history:", repr(e)) return self.print_error("received history rates of length", len(h)) self.history[ccy] = h self.history_timestamps[ccy] = timestamp self.on_history() def get_historical_rates(self, ccy, cache_dir): result, timestamp = self.history.get(ccy), self.history_timestamps.get(ccy, 0.0) if (not result or self._is_timestamp_old(timestamp)) and ccy in self.history_ccys(): t = Thread(target=self.get_historical_rates_safe, args=(ccy, cache_dir), daemon=True) t.start() return result def history_ccys(self): return [] def historical_rate(self, ccy, d_t): return self.history.get(ccy, {}).get(d_t.strftime('%Y-%m-%d')) def get_currencies(self): rates = self.get_rates('') return sorted([str(a) for (a, b) in rates.items() if b is not None and len(a)==3]) class CoinGecko(ExchangeBase): def get_rates(self, ccy): json = self.get_json('api.coingecko.com', '/api/v3/coins/devault?localization=False&sparkline=false') prices = json["market_data"]["current_price"] return dict([(a[0].upper(),PyDecimal(a[1])) for a in prices.items()]) def history_ccys(self): return ['AED', 'ARS', 'AUD', 'BTD', 'BHD', 'BMD', 'BRL', 'BTC', 'CAD', 'CHF', 'CLP', 'CNY', 'CZK', 'DKK', 'ETH', 'EUR', 'GBP', 'HKD', 'HUF', 'IDR', 'ILS', 'INR', 'JPY', 'KRW', 'KWD', 'LKR', 'LTC', 'MMK', 'MXH', 'MXN', 'MYR', 'NOK', 'NZD', 'PHP', 'PKR', 'PLN', 'RUB', 'SAR', 'SEK', 'SGD', 'THB', 'TRY', 'TWD', 'USD', 'VEF', 'XAG', 'XAU', 'XDR', 'ZAR'] def request_history(self, ccy): history = self.get_json('api.coingecko.com', '/api/v3/coins/devault/market_chart?vs_currency=%s&days=max' % ccy) from datetime import datetime as dt return dict([(dt.utcfromtimestamp(h[0]/1000).strftime('%Y-%m-%d'), h[1]) for h in history['prices']]) def dictinvert(d): inv = {} for k, vlist in d.items(): for v in vlist: keys = inv.setdefault(v, []) keys.append(k) return inv def get_exchanges_and_currencies(): try: data = pkgutil.get_data(__name__, 'currencies.json') return json.loads(data.decode('utf-8')) except: pass path = os.path.join(os.path.dirname(__file__), 'currencies.json') d = {} is_exchange = lambda obj: (inspect.isclass(obj) and issubclass(obj, ExchangeBase) and obj != ExchangeBase) exchanges = dict(inspect.getmembers(sys.modules[__name__], is_exchange)) for name, klass in exchanges.items(): exchange = klass(None, None) try: d[name] = exchange.get_currencies() print_error(name, "ok") except: print_error(name, "error") continue with open(path, 'w', encoding='utf-8') as f: f.write(json.dumps(d, indent=4, sort_keys=True)) return d CURRENCIES = get_exchanges_and_currencies() def get_exchanges_by_ccy(history=True): if not history: return dictinvert(CURRENCIES) d = {} exchanges = CURRENCIES.keys() for name in exchanges: klass = globals()[name] exchange = klass(None, None) d[name] = exchange.history_ccys() return dictinvert(d) class FxThread(ThreadJob): default_currency = DEFAULT_CURRENCY default_exchange = DEFAULT_EXCHANGE def __init__(self, config, network): self.config = config self.network = network self.ccy = self.get_currency() self.history_used_spot = False self.ccy_combo = None self.hist_checkbox = None self.timeout = 0.0 self.cache_dir = os.path.join(config.path, 'cache') self.set_exchange(self.config_exchange()) if not os.path.exists(self.cache_dir): os.mkdir(self.cache_dir) def get_currencies(self, h): d = get_exchanges_by_ccy(h) return sorted(d.keys()) def get_exchanges_by_ccy(self, ccy, h): d = get_exchanges_by_ccy(h) return d.get(ccy, []) def ccy_amount_str(self, amount, commas, default_prec=2, is_diff=False): prec = CCY_PRECISIONS.get(self.ccy, default_prec) diff_str = '' if is_diff: diff_str = '+' if amount >= 0 else '-' fmt_str = "%s{:%s.%df}" % (diff_str, "," if commas else "", max(0, prec)) try: rounded_amount = round(amount, prec) except decimal.InvalidOperation: rounded_amount = amount return fmt_str.format(rounded_amount) def run(self): ''' This runs from the Network thread. It is invoked roughly every 100ms (see network.py), with actual work being done every 2.5 minutes. ''' if self.is_enabled(): if self.timeout <= time.time(): self.exchange.update(self.ccy) if (self.show_history() and (self.timeout == 0 # forced update # OR > 24 hours have expired or self.exchange.is_historical_rate_old(self.ccy))): # Update historical rates. Note this doesn't actually # go out to the network unless cache file is missing # and/or >= 24 hours have passed since last fetch. self.exchange.get_historical_rates(self.ccy, self.cache_dir) # And, finally, update self.timeout so we execute this branch # every ~2.5 minutes self.timeout = time.time() + 150 def is_enabled(self): return self.config.get('use_exchange_rate', DEFAULT_ENABLED) def set_enabled(self, b): return self.config.set_key('use_exchange_rate', bool(b)) def get_history_config(self): return bool(self.config.get('history_rates')) def set_history_config(self, b): self.config.set_key('history_rates', bool(b)) def get_fiat_address_config(self): return bool(self.config.get('fiat_address')) def set_fiat_address_config(self, b): self.config.set_key('fiat_address', bool(b)) def get_currency(self): '''Use when dynamic fetching is needed''' return self.config.get("currency", self.default_currency) def config_exchange(self): return self.config.get('use_exchange', self.default_exchange) def show_history(self): return self.is_enabled() and self.get_history_config() and self.ccy in self.exchange.history_ccys() def set_currency(self, ccy): self.ccy = ccy if self.get_currency() != ccy: self.config.set_key('currency', ccy, True) self.timeout = 0 # Force update because self.ccy changes self.on_quotes() def set_exchange(self, name): default_class = globals().get(self.default_exchange) class_ = globals().get(name, default_class) if self.config_exchange() != name: self.config.set_key('use_exchange', name, True) self.exchange = class_(self.on_quotes, self.on_history) if self.get_history_config() and self.ccy not in self.exchange.history_ccys() and class_ != default_class: # this exchange has no history for this ccy. Try the default exchange. # If that also fails the user will be stuck in a strange UI # situation where the checkbox is checked but they see no history # Note this code is here to migrate users from previous history # API exchanges in config that are no longer serving histories. self.set_exchange(self.default_exchange) return self.print_error("using exchange", name) # A new exchange means new fx quotes, initially empty. # This forces a quote refresh, which will happen in the Network thread. self.timeout = 0 def on_quotes(self): if self.network: self.network.trigger_callback('on_quotes') def on_history(self): if self.network: self.network.trigger_callback('on_history') def exchange_rate(self): '''Returns None, or the exchange rate as a PyDecimal''' rate = self.exchange.quotes.get(self.ccy) if rate: return PyDecimal(rate) def format_amount_and_units(self, btc_balance, is_diff=False): amount_str = self.format_amount(btc_balance, is_diff=is_diff) return '' if not amount_str else "%s %s" % (amount_str, self.ccy) def format_amount(self, btc_balance, is_diff=False): rate = self.exchange_rate() return '' if rate is None else self.value_str(btc_balance, rate, is_diff=is_diff) def get_fiat_status_text(self, btc_balance, base_unit, decimal_point): rate = self.exchange_rate() default_prec = 5 if base_unit == inv_base_units.get(2): # if base_unit == 'bits', increase precision on fiat as bits is pretty tiny as of 2019 default_prec = 4 return _(" (No FX rate available)") if rate is None else " 1 %s~%s %s" % (base_unit, self.value_str(COIN / (10**(8 - decimal_point)), rate, default_prec ), self.ccy ) def value_str(self, satoshis, rate, default_prec=2, is_diff=False): if satoshis is None: # Can happen with incomplete history return _("Unknown") if rate: value = PyDecimal(satoshis) / COIN * PyDecimal(rate) return "%s" % (self.ccy_amount_str(value, True, default_prec, is_diff=is_diff)) return _("No data") def history_rate(self, d_t): rate = self.exchange.historical_rate(self.ccy, d_t) # Frequently there is no rate for today, until tomorrow :) # Use spot quotes in that case if rate is None and (datetime.today().date() - d_t.date()).days <= 2: rate = self.exchange.quotes.get(self.ccy) self.history_used_spot = True return PyDecimal(rate) if rate is not None else None def historical_value_str(self, satoshis, d_t): rate = self.history_rate(d_t) return self.value_str(satoshis, rate) def historical_value(self, satoshis, d_t): rate = self.history_rate(d_t) if rate: return PyDecimal(satoshis) / COIN * PyDecimal(rate) def timestamp_rate(self, timestamp): from .util import timestamp_to_datetime date = timestamp_to_datetime(timestamp) return self.history_rate(date)
ballisticacore_server.py
#!/usr/bin/env python3.9 # Released under the MIT License. See LICENSE for details. # """BallisticaCore server manager.""" from __future__ import annotations import json import os import signal import subprocess import sys import time from pathlib import Path from threading import Lock, Thread, current_thread from typing import TYPE_CHECKING # We make use of the bacommon and efro packages as well as site-packages # included with our bundled Ballistica dist, so we need to add those paths # before we import them. sys.path += [ str(Path(Path(__file__).parent, 'dist', 'ba_data', 'python')), str(Path(Path(__file__).parent, 'dist', 'ba_data', 'python-site-packages')) ] from bacommon.servermanager import ServerConfig, StartServerModeCommand from efro.dataclassio import dataclass_from_dict, dataclass_validate from efro.error import CleanError from efro.terminal import Clr if TYPE_CHECKING: from typing import Optional, Union from types import FrameType from bacommon.servermanager import ServerCommand VERSION_STR = '1.3' # Version history: # 1.3.1 # Windows binary is now named BallisticaCoreHeadless.exe # 1.3: # Added show_tutorial config option # Added team_names config option # Added team_colors config option # Added playlist_inline config option # 1.2: # Added optional --help arg # Added --config arg for specifying config file and --root for ba_root path # Added noninteractive mode and --interactive/--noninteractive args to # explicitly enable/disable it (it is autodetected by default) # Added explicit control for auto-restart: --no-auto-restart # Config file is now reloaded each time server binary is restarted; no more # need to bring down server wrapper to pick up changes # Now automatically restarts server binary when config file is modified # (use --no-config-auto-restart to disable that behavior) # 1.1.1: # Switched config reading to use efro.dataclasses.dataclass_from_dict() # 1.1.0: # Added shutdown command # Changed restart to default to immediate=True # Added clean_exit_minutes, unclean_exit_minutes, and idle_exit_minutes # 1.0.0: # Initial release class ServerManagerApp: """An app which manages BallisticaCore server execution. Handles configuring, launching, re-launching, and otherwise managing BallisticaCore operating in server mode. """ # How many seconds we wait after asking our subprocess to do an immediate # shutdown before bringing down the hammer. IMMEDIATE_SHUTDOWN_TIME_LIMIT = 5.0 def __init__(self) -> None: self._config_path = 'config.yaml' self._user_provided_config_path = False self._config = ServerConfig() self._ba_root_path = os.path.abspath('dist/ba_root') self._interactive = sys.stdin.isatty() self._wrapper_shutdown_desired = False self._done = False self._subprocess_commands: list[Union[str, ServerCommand]] = [] self._subprocess_commands_lock = Lock() self._subprocess_force_kill_time: Optional[float] = None self._auto_restart = True self._config_auto_restart = True self._config_mtime: Optional[float] = None self._last_config_mtime_check_time: Optional[float] = None self._should_report_subprocess_error = False self._running = False self._interpreter_start_time: Optional[float] = None self._subprocess: Optional[subprocess.Popen[bytes]] = None self._subprocess_launch_time: Optional[float] = None self._subprocess_sent_config_auto_restart = False self._subprocess_sent_clean_exit = False self._subprocess_sent_unclean_exit = False self._subprocess_thread: Optional[Thread] = None self._subprocess_exited_cleanly: Optional[bool] = None # This may override the above defaults. self._parse_command_line_args() # Do an initial config-load. If the config is invalid at this point # we can cleanly die (we're more lenient later on reloads). self.load_config(strict=True, print_confirmation=False) @property def config(self) -> ServerConfig: """The current config for the app.""" return self._config @config.setter def config(self, value: ServerConfig) -> None: dataclass_validate(value) self._config = value def _prerun(self) -> None: """Common code at the start of any run.""" # Make sure we don't call run multiple times. if self._running: raise RuntimeError('Already running.') self._running = True dbgstr = 'debug' if __debug__ else 'opt' print( f'{Clr.CYN}{Clr.BLD}BallisticaCore server manager {VERSION_STR}' f' starting up ({dbgstr} mode)...{Clr.RST}', flush=True) # Python will handle SIGINT for us (as KeyboardInterrupt) but we # need to register a SIGTERM handler so we have a chance to clean # up our subprocess when someone tells us to die. (and avoid # zombie processes) signal.signal(signal.SIGTERM, self._handle_term_signal) # During a run, we make the assumption that cwd is the dir # containing this script, so make that so. Up until now that may # not be the case (we support being called from any location). os.chdir(os.path.abspath(os.path.dirname(__file__))) # Fire off a background thread to wrangle our server binaries. self._subprocess_thread = Thread(target=self._bg_thread_main) self._subprocess_thread.start() def _postrun(self) -> None: """Common code at the end of any run.""" print(f'{Clr.CYN}Server manager shutting down...{Clr.RST}', flush=True) assert self._subprocess_thread is not None if self._subprocess_thread.is_alive(): print(f'{Clr.CYN}Waiting for subprocess exit...{Clr.RST}', flush=True) # Mark ourselves as shutting down and wait for the process to wrap up. self._done = True self._subprocess_thread.join() # If there's a server error we should care about, exit the # entire wrapper uncleanly. if self._should_report_subprocess_error: raise CleanError('Server subprocess exited uncleanly.') def run(self) -> None: """Do the thing.""" if self._interactive: self._run_interactive() else: self._run_noninteractive() def _run_noninteractive(self) -> None: """Run the app loop to completion noninteractively.""" self._prerun() try: while True: time.sleep(1.234) except KeyboardInterrupt: # Gracefully bow out if we kill ourself via keyboard. pass except SystemExit: # We get this from the builtin quit(), our signal handler, etc. # Need to catch this so we can clean up, otherwise we'll be # left in limbo with our process thread still running. pass self._postrun() def _run_interactive(self) -> None: """Run the app loop to completion interactively.""" import code self._prerun() # Print basic usage info for interactive mode. print( f"{Clr.CYN}Interactive mode enabled; use the 'mgr' object" f' to interact with the server.\n' f"Type 'help(mgr)' for more information.{Clr.RST}", flush=True) context = {'__name__': '__console__', '__doc__': None, 'mgr': self} # Enable tab-completion if possible. self._enable_tab_completion(context) # Now just sit in an interpreter. # TODO: make it possible to use IPython if the user has it available. try: self._interpreter_start_time = time.time() code.interact(local=context, banner='', exitmsg='') except SystemExit: # We get this from the builtin quit(), our signal handler, etc. # Need to catch this so we can clean up, otherwise we'll be # left in limbo with our process thread still running. pass except BaseException as exc: print( f'{Clr.SRED}Unexpected interpreter exception:' f' {exc} ({type(exc)}){Clr.RST}', flush=True) self._postrun() def cmd(self, statement: str) -> None: """Exec a Python command on the current running server subprocess. Note that commands are executed asynchronously and no status or return value is accessible from this manager app. """ if not isinstance(statement, str): raise TypeError(f'Expected a string arg; got {type(statement)}') with self._subprocess_commands_lock: self._subprocess_commands.append(statement) self._block_for_command_completion() def _block_for_command_completion(self) -> None: # Ideally we'd block here until the command was run so our prompt would # print after it's results. We currently don't get any response from # the app so the best we can do is block until our bg thread has sent # it. In the future we can perhaps add a proper 'command port' # interface for proper blocking two way communication. while True: with self._subprocess_commands_lock: if not self._subprocess_commands: break time.sleep(0.1) # One last short delay so if we come out *just* as the command is sent # we'll hopefully still give it enough time to process/print. time.sleep(0.1) def screenmessage(self, message: str, color: Optional[tuple[float, float, float]] = None, clients: Optional[list[int]] = None) -> None: """Display a screen-message. This will have no name attached and not show up in chat history. They will show up in replays, however (unless clients is passed). """ from bacommon.servermanager import ScreenMessageCommand self._enqueue_server_command( ScreenMessageCommand(message=message, color=color, clients=clients)) def chatmessage(self, message: str, clients: Optional[list[int]] = None) -> None: """Send a chat message from the server. This will have the server's name attached and will be logged in client chat windows, just like other chat messages. """ from bacommon.servermanager import ChatMessageCommand self._enqueue_server_command( ChatMessageCommand(message=message, clients=clients)) def clientlist(self) -> None: """Print a list of connected clients.""" from bacommon.servermanager import ClientListCommand self._enqueue_server_command(ClientListCommand()) self._block_for_command_completion() def kick(self, client_id: int, ban_time: Optional[int] = None) -> None: """Kick the client with the provided id. If ban_time is provided, the client will be banned for that length of time in seconds. If it is None, ban duration will be determined automatically. Pass 0 or a negative number for no ban time. """ from bacommon.servermanager import KickCommand self._enqueue_server_command( KickCommand(client_id=client_id, ban_time=ban_time)) def restart(self, immediate: bool = True) -> None: """Restart the server subprocess. By default, the current server process will exit immediately. If 'immediate' is passed as False, however, it will instead exit at the next clean transition point (the end of a series, etc). """ from bacommon.servermanager import ShutdownCommand, ShutdownReason self._enqueue_server_command( ShutdownCommand(reason=ShutdownReason.RESTARTING, immediate=immediate)) # If we're asking for an immediate restart but don't get one within # the grace period, bring down the hammer. if immediate: self._subprocess_force_kill_time = ( time.time() + self.IMMEDIATE_SHUTDOWN_TIME_LIMIT) def shutdown(self, immediate: bool = True) -> None: """Shut down the server subprocess and exit the wrapper. By default, the current server process will exit immediately. If 'immediate' is passed as False, however, it will instead exit at the next clean transition point (the end of a series, etc). """ from bacommon.servermanager import ShutdownCommand, ShutdownReason self._enqueue_server_command( ShutdownCommand(reason=ShutdownReason.NONE, immediate=immediate)) # An explicit shutdown means we know to bail completely once this # subprocess completes. self._wrapper_shutdown_desired = True # If we're asking for an immediate shutdown but don't get one within # the grace period, bring down the hammer. if immediate: self._subprocess_force_kill_time = ( time.time() + self.IMMEDIATE_SHUTDOWN_TIME_LIMIT) def _parse_command_line_args(self) -> None: """Parse command line args.""" # pylint: disable=too-many-branches i = 1 argc = len(sys.argv) did_set_interactive = False while i < argc: arg = sys.argv[i] if arg == '--help': self.print_help() sys.exit(0) elif arg == '--config': if i + 1 >= argc: raise CleanError('Expected a config path as next arg.') path = sys.argv[i + 1] if not os.path.exists(path): raise CleanError( f"Supplied path does not exist: '{path}'.") # We need an abs path because we may be in a different # cwd currently than we will be during the run. self._config_path = os.path.abspath(path) self._user_provided_config_path = True i += 2 elif arg == '--root': if i + 1 >= argc: raise CleanError('Expected a path as next arg.') path = sys.argv[i + 1] # Unlike config_path, this one doesn't have to exist now. # We do however need an abs path because we may be in a # different cwd currently than we will be during the run. self._ba_root_path = os.path.abspath(path) i += 2 elif arg == '--interactive': if did_set_interactive: raise CleanError('interactive/noninteractive can only' ' be specified once.') self._interactive = True did_set_interactive = True i += 1 elif arg == '--noninteractive': if did_set_interactive: raise CleanError('interactive/noninteractive can only' ' be specified once.') self._interactive = False did_set_interactive = True i += 1 elif arg == '--no-auto-restart': self._auto_restart = False i += 1 elif arg == '--no-config-auto-restart': self._config_auto_restart = False i += 1 else: raise CleanError(f"Invalid arg: '{arg}'.") @classmethod def _par(cls, txt: str) -> str: """Spit out a pretty paragraph for our help text.""" import textwrap ind = ' ' * 2 out = textwrap.fill(txt, 80, initial_indent=ind, subsequent_indent=ind) return f'{out}\n' @classmethod def print_help(cls) -> None: """Print app help.""" filename = os.path.basename(__file__) out = ( f'{Clr.BLD}{filename} usage:{Clr.RST}\n' + cls._par( 'This script handles configuring, launching, re-launching,' ' and otherwise managing BallisticaCore operating' ' in server mode. It can be run with no arguments, but' ' accepts the following optional ones:') + f'\n' f'{Clr.BLD}--help:{Clr.RST}\n' f' Show this help.\n' f'\n' f'{Clr.BLD}--config [path]{Clr.RST}\n' + cls._par( 'Set the config file read by the server script. The config' ' file contains most options for what kind of game to host.' ' It should be in yaml format. Note that yaml is backwards' ' compatible with json so you can just write json if you' ' want to. If not specified, the script will look for a' ' file named \'config.yaml\' in the same directory as the' ' script.') + '\n' f'{Clr.BLD}--root [path]{Clr.RST}\n' + cls._par( 'Set the ballistica root directory. This is where the server' ' binary will read and write its caches, state files,' ' downloaded assets to, etc. It needs to be a writable' ' directory. If not specified, the script will use the' ' \'dist/ba_root\' directory relative to itself.') + '\n' f'{Clr.BLD}--interactive{Clr.RST}\n' f'{Clr.BLD}--noninteractive{Clr.RST}\n' + cls._par( 'Specify whether the script should run interactively.' ' In interactive mode, the script creates a Python interpreter' ' and reads commands from stdin, allowing for live interaction' ' with the server. The server script will then exit when ' 'end-of-file is reached in stdin. Noninteractive mode creates' ' no interpreter and is more suited to being run in automated' ' scenarios. By default, interactive mode will be used if' ' a terminal is detected and noninteractive mode otherwise.') + '\n' f'{Clr.BLD}--no-auto-restart{Clr.RST}\n' + cls._par('Auto-restart is enabled by default, which means the' ' server manager will restart the server binary whenever' ' it exits (even when uncleanly). Disabling auto-restart' ' will cause the server manager to instead exit after a' ' single run and also to return error codes if the' ' server binary did so.') + '\n' f'{Clr.BLD}--no-config-auto-restart{Clr.RST}\n' + cls._par( 'By default, when auto-restart is enabled, the server binary' ' will be automatically restarted if changes to the server' ' config file are detected. This disables that behavior.')) print(out) def load_config(self, strict: bool, print_confirmation: bool) -> None: """Load the config. If strict is True, errors will propagate upward. Otherwise, warnings will be printed and repeated attempts will be made to load the config. Eventually the function will give up and leave the existing config as-is. """ retry_seconds = 3 maxtries = 11 for trynum in range(maxtries): try: self._config = self._load_config_from_file( print_confirmation=print_confirmation) return except Exception as exc: if strict: raise CleanError( f'Error loading config file:\n{exc}') from exc print(f'{Clr.RED}Error loading config file:\n{exc}.{Clr.RST}', flush=True) if trynum == maxtries - 1: print( f'{Clr.RED}Max-tries reached; giving up.' f' Existing config values will be used.{Clr.RST}', flush=True) break print( f'{Clr.CYN}Please correct the error.' f' Will re-attempt load in {retry_seconds}' f' seconds. (attempt {trynum+1} of' f' {maxtries-1}).{Clr.RST}', flush=True) for _j in range(retry_seconds): # If the app is trying to die, drop what we're doing. if self._done: return time.sleep(1) def _load_config_from_file(self, print_confirmation: bool) -> ServerConfig: out: Optional[ServerConfig] = None if not os.path.exists(self._config_path): # Special case: # If the user didn't specify a particular config file, allow # gracefully falling back to defaults if the default one is # missing. if not self._user_provided_config_path: if print_confirmation: print( f'{Clr.YLW}Default config file not found' f' (\'{self._config_path}\'); using default' f' settings.{Clr.RST}', flush=True) self._config_mtime = None self._last_config_mtime_check_time = time.time() return ServerConfig() # Don't be so lenient if the user pointed us at one though. raise RuntimeError( f"Config file not found: '{self._config_path}'.") import yaml with open(self._config_path, encoding='utf-8') as infile: user_config_raw = yaml.safe_load(infile.read()) # An empty config file will yield None, and that's ok. if user_config_raw is not None: out = dataclass_from_dict(ServerConfig, user_config_raw) # Update our known mod-time since we know it exists. self._config_mtime = Path(self._config_path).stat().st_mtime self._last_config_mtime_check_time = time.time() # Go with defaults if we weren't able to load anything. if out is None: out = ServerConfig() if print_confirmation: print(f'{Clr.CYN}Valid server config file loaded.{Clr.RST}', flush=True) return out def _enable_tab_completion(self, locs: dict) -> None: """Enable tab-completion on platforms where available (linux/mac).""" try: import readline import rlcompleter readline.set_completer(rlcompleter.Completer(locs).complete) readline.parse_and_bind('tab:complete') except ImportError: # This is expected (readline doesn't exist under windows). pass def _bg_thread_main(self) -> None: """Top level method run by our bg thread.""" while not self._done: self._run_server_cycle() def _handle_term_signal(self, sig: int, frame: Optional[FrameType]) -> None: """Handle signals (will always run in the main thread).""" del sig, frame # Unused. sys.exit(1 if self._should_report_subprocess_error else 0) def _run_server_cycle(self) -> None: """Spin up the server subprocess and run it until exit.""" # pylint: disable=consider-using-with # Reload our config, and update our overall behavior based on it. # We do non-strict this time to give the user repeated attempts if # if they mess up while modifying the config on the fly. self.load_config(strict=False, print_confirmation=True) self._prep_subprocess_environment() # Launch the binary and grab its stdin; # we'll use this to feed it commands. self._subprocess_launch_time = time.time() # Set an environment var so the server process knows its being # run under us. This causes it to ignore ctrl-c presses and other # slight behavior tweaks. Hmm; should this be an argument instead? os.environ['BA_SERVER_WRAPPER_MANAGED'] = '1' print(f'{Clr.CYN}Launching server subprocess...{Clr.RST}', flush=True) binary_name = ('BallisticaCoreHeadless.exe' if os.name == 'nt' else './ballisticacore_headless') assert self._ba_root_path is not None self._subprocess = None # Launch! try: self._subprocess = subprocess.Popen( [binary_name, '-cfgdir', self._ba_root_path], stdin=subprocess.PIPE, cwd='dist') except Exception as exc: self._subprocess_exited_cleanly = False print( f'{Clr.RED}Error launching server subprocess: {exc}{Clr.RST}', flush=True) # Do the thing. try: self._run_subprocess_until_exit() except Exception as exc: print(f'{Clr.RED}Error running server subprocess: {exc}{Clr.RST}', flush=True) self._kill_subprocess() assert self._subprocess_exited_cleanly is not None # EW: it seems that if we die before the main thread has fully started # up the interpreter, its possible that it will not break out of its # loop via the usual SystemExit that gets sent when we die. if self._interactive: while (self._interpreter_start_time is None or time.time() - self._interpreter_start_time < 0.5): time.sleep(0.1) # Avoid super fast death loops. if (not self._subprocess_exited_cleanly and self._auto_restart and not self._done): time.sleep(5.0) # If they don't want auto-restart, we'll exit the whole wrapper. # (and with an error code if things ended badly). if not self._auto_restart: self._wrapper_shutdown_desired = True if not self._subprocess_exited_cleanly: self._should_report_subprocess_error = True self._reset_subprocess_vars() # If we want to die completely after this subprocess has ended, # tell the main thread to die. if self._wrapper_shutdown_desired: # Only do this if the main thread is not already waiting for # us to die; otherwise it can lead to deadlock. # (we hang in os.kill while main thread is blocked in Thread.join) if not self._done: self._done = True # This should break the main thread out of its blocking # interpreter call. os.kill(os.getpid(), signal.SIGTERM) def _prep_subprocess_environment(self) -> None: """Write files that must exist at process launch.""" assert self._ba_root_path is not None os.makedirs(self._ba_root_path, exist_ok=True) cfgpath = os.path.join(self._ba_root_path, 'config.json') if os.path.exists(cfgpath): with open(cfgpath, encoding='utf-8') as infile: bincfg = json.loads(infile.read()) else: bincfg = {} # Some of our config values translate directly into the # ballisticacore config file; the rest we pass at runtime. bincfg['Port'] = self._config.port bincfg['Auto Balance Teams'] = self._config.auto_balance_teams bincfg['Show Tutorial'] = self._config.show_tutorial if self._config.team_names is not None: bincfg['Custom Team Names'] = self._config.team_names elif 'Custom Team Names' in bincfg: del bincfg['Custom Team Names'] if self._config.team_colors is not None: bincfg['Custom Team Colors'] = self._config.team_colors elif 'Custom Team Colors' in bincfg: del bincfg['Custom Team Colors'] bincfg['Idle Exit Minutes'] = self._config.idle_exit_minutes with open(cfgpath, 'w', encoding='utf-8') as outfile: outfile.write(json.dumps(bincfg)) def _enqueue_server_command(self, command: ServerCommand) -> None: """Enqueue a command to be sent to the server. Can be called from any thread. """ with self._subprocess_commands_lock: self._subprocess_commands.append(command) def _send_server_command(self, command: ServerCommand) -> None: """Send a command to the server. Must be called from the server process thread. """ import pickle assert current_thread() is self._subprocess_thread assert self._subprocess is not None assert self._subprocess.stdin is not None val = repr(pickle.dumps(command)) assert '\n' not in val execcode = (f'import ba._servermode;' f' ba._servermode._cmd({val})\n').encode() self._subprocess.stdin.write(execcode) self._subprocess.stdin.flush() def _run_subprocess_until_exit(self) -> None: if self._subprocess is None: return assert current_thread() is self._subprocess_thread assert self._subprocess.stdin is not None # Send the initial server config which should kick things off. # (but make sure its values are still valid first) dataclass_validate(self._config) self._send_server_command(StartServerModeCommand(self._config)) while True: # If the app is trying to shut down, nope out immediately. if self._done: break # Pass along any commands to our process. with self._subprocess_commands_lock: for incmd in self._subprocess_commands: # If we're passing a raw string to exec, no need to wrap it # in any proper structure. if isinstance(incmd, str): self._subprocess.stdin.write((incmd + '\n').encode()) self._subprocess.stdin.flush() else: self._send_server_command(incmd) self._subprocess_commands = [] # Request restarts/shut-downs for various reasons. self._request_shutdowns_or_restarts() # If they want to force-kill our subprocess, simply exit this # loop; the cleanup code will kill the process if its still # alive. if (self._subprocess_force_kill_time is not None and time.time() > self._subprocess_force_kill_time): print( f'{Clr.CYN}Immediate shutdown time limit' f' ({self.IMMEDIATE_SHUTDOWN_TIME_LIMIT:.1f} seconds)' f' expired; force-killing subprocess...{Clr.RST}', flush=True) break # Watch for the server process exiting.. code: Optional[int] = self._subprocess.poll() if code is not None: clr = Clr.CYN if code == 0 else Clr.RED print( f'{clr}Server subprocess exited' f' with code {code}.{Clr.RST}', flush=True) self._subprocess_exited_cleanly = (code == 0) break time.sleep(0.25) def _request_shutdowns_or_restarts(self) -> None: # pylint: disable=too-many-branches assert current_thread() is self._subprocess_thread assert self._subprocess_launch_time is not None now = time.time() minutes_since_launch = (now - self._subprocess_launch_time) / 60.0 # If we're doing auto-restart with config changes, handle that. if (self._auto_restart and self._config_auto_restart and not self._subprocess_sent_config_auto_restart): if (self._last_config_mtime_check_time is None or (now - self._last_config_mtime_check_time) > 3.123): self._last_config_mtime_check_time = now mtime: Optional[float] if os.path.isfile(self._config_path): mtime = Path(self._config_path).stat().st_mtime else: mtime = None if mtime != self._config_mtime: print( f'{Clr.CYN}Config-file change detected;' f' requesting immediate restart.{Clr.RST}', flush=True) self.restart(immediate=True) self._subprocess_sent_config_auto_restart = True # Attempt clean exit if our clean-exit-time passes. # (and enforce a 6 hour max if not provided) clean_exit_minutes = 360.0 if self._config.clean_exit_minutes is not None: clean_exit_minutes = min(clean_exit_minutes, self._config.clean_exit_minutes) if clean_exit_minutes is not None: if (minutes_since_launch > clean_exit_minutes and not self._subprocess_sent_clean_exit): opname = 'restart' if self._auto_restart else 'shutdown' print( f'{Clr.CYN}clean_exit_minutes' f' ({clean_exit_minutes})' f' elapsed; requesting soft' f' {opname}.{Clr.RST}', flush=True) if self._auto_restart: self.restart(immediate=False) else: self.shutdown(immediate=False) self._subprocess_sent_clean_exit = True # Attempt unclean exit if our unclean-exit-time passes. # (and enforce a 7 hour max if not provided) unclean_exit_minutes = 420.0 if self._config.unclean_exit_minutes is not None: unclean_exit_minutes = min(unclean_exit_minutes, self._config.unclean_exit_minutes) if unclean_exit_minutes is not None: if (minutes_since_launch > unclean_exit_minutes and not self._subprocess_sent_unclean_exit): opname = 'restart' if self._auto_restart else 'shutdown' print( f'{Clr.CYN}unclean_exit_minutes' f' ({unclean_exit_minutes})' f' elapsed; requesting immediate' f' {opname}.{Clr.RST}', flush=True) if self._auto_restart: self.restart(immediate=True) else: self.shutdown(immediate=True) self._subprocess_sent_unclean_exit = True def _reset_subprocess_vars(self) -> None: self._subprocess = None self._subprocess_launch_time = None self._subprocess_sent_config_auto_restart = False self._subprocess_sent_clean_exit = False self._subprocess_sent_unclean_exit = False self._subprocess_force_kill_time = None self._subprocess_exited_cleanly = None def _kill_subprocess(self) -> None: """End the server subprocess if it still exists.""" assert current_thread() is self._subprocess_thread if self._subprocess is None: return print(f'{Clr.CYN}Stopping subprocess...{Clr.RST}', flush=True) # First, ask it nicely to die and give it a moment. # If that doesn't work, bring down the hammer. self._subprocess.terminate() try: self._subprocess.wait(timeout=10) self._subprocess_exited_cleanly = ( self._subprocess.returncode == 0) except subprocess.TimeoutExpired: self._subprocess_exited_cleanly = False self._subprocess.kill() print(f'{Clr.CYN}Subprocess stopped.{Clr.RST}', flush=True) def main() -> None: """Run the BallisticaCore server manager.""" try: ServerManagerApp().run() except CleanError as exc: # For clean errors, do a simple print and fail; no tracebacks/etc. # Any others will bubble up and give us the usual mess. exc.pretty_print() sys.exit(1) if __name__ == '__main__': main()
thread.py
#!/usr/bin/python3 # Name: chrome.py # Version: R2 # Date: July 2019 # Function: Parses original chrome Bookmarks file # Tries to reach each URL and removes it on error # Accepts return codes as parameters. chrome.py must be called as executable: # $ ./chrome.py --help # $ ./chrome.py 404 501 403 # Threaded # # Input: bookmark file in ./.config/BraveSoftware/Brave-Browser/Default/Bookmarks # Bookmarks file structure: # { # "checksum": "79c9312bbeee61a5710117f00bc16ff8", # "roots": { # "bookmark_bar": { # "children": [ { # "date_added": "13187860084000000", # ... # }, { # ... # }], # "children": [ { # "date_added": "13134043672000000", # ... # }, { # ... # }], # "children": [ { # ... # }, { # "date_added": "13154093672000000", # "id": "4092", # "name": "Servicio LG Electronics en Linea :: Drivers", # "type": "url", # "url": "http://es.lgservice.com/" # }, { # ... # } ], # 'date_added': '13199527258944339', # 'date_modified': '0', # 'id': '6540', # 'name': 'Tuxedo', # 'type': 'folder'} # } ], # "date_added": "13199527258977344", # "date_modified": "13200493908840013", # "id": "7107", # "name": "unfiled", # "type": "folder" # } ], # "date_added": "13198974830896033", # "date_modified": "13200494087851454", # "id": "1", # "name": "Bookmark bar", # "type": "folder" # } # "other": { # } # "synced": { # } # } # "version": 1 # } # # Output: import requests import json from pprint import pprint import sys from threading import Thread import http.client, sys import queue concurrent = 2 DELETEFOLDER = 0 DIRNAME = "output/" JSONIN = DIRNAME + "Bookmarks" JSONOUT = DIRNAME + "Bookmarks.out" URLXXX = DIRNAME + "XXX.url" URLOK = DIRNAME + "OK.url" # Read input parameters and create corresponding files params = sys.argv[1:] nparams = len(sys.argv) errorWatch = [] errorName = [] errorFile = [] if nparams > 1: if params[0] == '--help': print(""" Usage: ./thread.py <code1> <code2> <code3> Parameters: http return <code> that will trigger not adding its URL to filtered file and writing its address to '<code>.url'. Code range [100..999]. Files: Input 'Bookmark' file Output will be written to 'output/'. These file will be created: - Bookmarks.out (purged file) - XXX.url (network errors) - OK.url (all passed) - One <code>.url file for each parameter """) sys.exit() elif nparams == 1: print(""" Usage: ./chrome.py <code1> <code2> <code3> """) sys.exit() # Parameter parsing for param in params: if param.isdigit(): iparam = int(param) if iparam > 99 and iparam < 1000: errorWatch.append(param) errorName.append("URL" + param) errorFile.append(DIRNAME + param + '.url') else: print("Error: return code", param, "is out of bounds [100..999]\n") sys.exit() else: print("Error: return code", param, "is not and integer\n") sys.exit() # Create output/ directory if not exists try: os.mkdir(DIRNAME) print("Directory" , DIRNAME , "created ") except: print("Directory" , DIRNAME , "preserved") RED = '\033[31m' GREEN = '\033[32m' BLUE = '\033[34m' NONE = '\033[0m' # No Color # Read source bookmark file with open(JSONIN, "r") as f: Bookmarks = json.load(f) # Create output files urlXXX = open(URLXXX,"w") urlOK = open(URLOK,"w") for i in range(0, nparams-1): errorName[i] = open(errorFile[i], "w") print("Created", errorName[i]) # Threading functions def doWork(): while True: url = q.get() status, url = getStatus(url) #doSomethingWithResult(status, url) q.task_done() def getStatus(ourl): try: req = requests.head(ourl, timeout=10, proxies={'http':'','https':''}) status = str(req.status_code) return status, ourl except: return "XXX", ourl # Start the paralel queue q = queue.Queue(concurrent * 2) for i in range(concurrent): t = Thread(target=doWork) t.daemon = True t.start() # Recurrent function def preorder(tree, depth): depth += 1 if tree: width = len(tree) i = d = 0 for item in tree: name = item["name"] try: branches = len(item["children"]) subtree = item["children"] print("[" + str(depth) + "] " + name + " (" + str(branches) + ")") except: branches = 0 if branches > 0: preorder(subtree, depth) else: type = item["type"] id = item["id"] if type == "url": # list element being checked is i date_added = item["date_added"] url = item["url"] print(">>> " + url) #print(" N ", name) try: # To paralelize # Send request to queue q.put(url.strip()) q.join() # Read request from queue status, url = getStatus(url) # Old sequential #req = requests.head(url, timeout=10) #status = str(req.status_code) except: print(RED + " XXX " + id + " #" + str(i)) urlXXX.write(url + "\n") ret = tree.pop(d); d -= 1 print(NONE, end="") else: found = 0 for j, code in enumerate(errorWatch): if status == code: found = 1 print(RED + " " + status + " " + id + " #" + str(i)) errorName[j].write(url + "\n") ret = tree.pop(d); d -= 1 print(NONE, end="") if not found: # looked for code not in list print(" ", status, '+' + " #" + str(i)) urlOK.write(url + "\n") elif type == "folder": print(GREEN + " Empty folder" + NONE) if DELETEFOLDER: ret = tree.pop(d); d -= 1 else: print(BLUE + " ???" + id + NONE) i += 1 d += 1 return tree original = Bookmarks['roots']['bookmark_bar']['children'] nodes = preorder(original, 0) # JSON structure other = { "children": [ ], "date_added": "13198974830951405", "date_modified": "13200950919336220", "id": "2", "name": "Other bookmarks", "type": "folder" } synced = { "children": [ ], "date_added": "13198974830951420", "date_modified": "0", "id": "3", "name": "Mobile bookmarks", "type": "folder" } bookmarks_bar = {"children": nodes, "date_added": "13198974830896033", "date_modified": "13200494087851454", "id": "1", "name": "Bookmarks bar", "type": "folder" } roots = {'bookmark_bar': bookmarks_bar, 'other': other, 'synced': synced} # checksum entry is updated by Brave upon loading filtered = { "checksum": "00000000000000000000000000000000", "roots": roots, "version": 1 } # Write json list *filtered* to disk with open(JSONOUT, 'w') as fout: json.dump(filtered , fout, sort_keys=True, indent=4, separators=(',', ': '))
main.py
import threading from queue import Queue from spider import Spider from domain import * from general import * PROJECT_NAME = 'viper-seo' HOMEPAGE = 'http://viper-seo.com/' DOMAIN_NAME = get_domain_name(HOMEPAGE) QUEUE_FILE = PROJECT_NAME + '/queue.txt' CRAWLED_FILE = PROJECT_NAME + '/crawled.txt' NUMBER_OF_THREADS = 8 queue = Queue() Spider(PROJECT_NAME, HOMEPAGE, DOMAIN_NAME) # Create worker threads (will die when main exits) def create_workers(): for _ in range(NUMBER_OF_THREADS): t = threading.Thread(target=work) t.daemon = True t.start() # Do the next job in the queue def work(): while True: url = queue.get() Spider.crawl_page(threading.current_thread().name, url) queue.task_done() # Each queued link is a new job def create_jobs(): for link in file_to_set(QUEUE_FILE): queue.put(link) queue.join() crawl() # Check if there are items in the queue, if so crawl them def crawl(): queued_links = file_to_set(QUEUE_FILE) if len(queued_links) > 0: print(str(len(queued_links)) + ' links in the queue') create_jobs() create_workers() crawl()
test_ssl.py
# -*- coding: utf-8 -*- # Test the support for SSL and sockets import sys import unittest from test import test_support as support from test.script_helper import assert_python_ok import asyncore import socket import select import time import datetime import gc import os import errno import pprint import shutil import urllib2 import traceback import weakref import platform import functools from contextlib import closing ssl = support.import_module("ssl") PROTOCOLS = sorted(ssl._PROTOCOL_NAMES) HOST = support.HOST IS_LIBRESSL = ssl.OPENSSL_VERSION.startswith('LibreSSL') IS_OPENSSL_1_1 = not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0) 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 = CERTFILE.encode(sys.getfilesystemencoding()) ONLYCERT = data_file("ssl_cert.pem") ONLYKEY = data_file("ssl_key.pem") BYTES_ONLYCERT = ONLYCERT.encode(sys.getfilesystemencoding()) BYTES_ONLYKEY = ONLYKEY.encode(sys.getfilesystemencoding()) CERTFILE_PROTECTED = data_file("keycert.passwd.pem") ONLYKEY_PROTECTED = data_file("ssl_key.passwd.pem") KEY_PASSWORD = "somepass" CAPATH = data_file("capath") BYTES_CAPATH = CAPATH.encode(sys.getfilesystemencoding()) CAFILE_NEURONIO = data_file("capath", "4e1295a3.0") CAFILE_CACERT = data_file("capath", "5ed36f99.0") # 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_CERTFILE2 = data_file("keycert4.pem") SIGNING_CA = data_file("pycacert.pem") # cert with all kinds of subject alt names ALLSANFILE = data_file("allsans.pem") REMOTE_HOST = "self-signed.pythontest.net" REMOTE_ROOT_CERT = data_file("selfsigned_pythontestdotnet.pem") 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") TALOS_INVALID_CRLDP = data_file("talos-2019-0758.pem") DHFILE = data_file("ffdh3072.pem") BYTES_DHFILE = DHFILE.encode(sys.getfilesystemencoding()) # 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) class BasicTests(unittest.TestCase): def test_sslwrap_simple(self): # A crude test for the legacy API try: ssl.sslwrap_simple(socket.socket(socket.AF_INET)) except IOError, e: if e.errno == 32: # broken pipe when ssl_sock.do_handshake(), this test doesn't care about that pass else: raise try: ssl.sslwrap_simple(socket.socket(socket.AF_INET)._sock) except IOError, e: if e.errno == 32: # broken pipe when ssl_sock.do_handshake(), this test doesn't care about that pass else: raise 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 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") 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 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")) 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) 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 p = ssl._ssl._test_decode_cert(CERTFILE) if support.verbose: sys.stdout.write("\n" + pprint.pformat(p) + "\n") self.assertEqual(p['issuer'], ((('countryName', 'XY'),), (('localityName', 'Castle Anthrax'),), (('organizationName', 'Python Software Foundation'),), (('commonName', 'localhost'),)) ) # Note the next three asserts will fail if the keys are regenerated self.assertEqual(p['notAfter'], asn1time('Aug 26 14:23:15 2028 GMT')) self.assertEqual(p['notBefore'], asn1time('Aug 29 14:23:15 2018 GMT')) self.assertEqual(p['serialNumber'], '98A7CF88C74A32ED') self.assertEqual(p['subject'], ((('countryName', 'XY'),), (('localityName', 'Castle Anthrax'),), (('organizationName', 'Python Software Foundation'),), (('commonName', 'localhost'),)) ) self.assertEqual(p['subjectAltName'], (('DNS', 'localhost'),)) # 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_2019_5010(self): p = ssl._ssl._test_decode_cert(TALOS_INVALID_CRLDP) if support.verbose: sys.stdout.write("\n" + pprint.pformat(p) + "\n") self.assertEqual( p, { 'issuer': ( (('countryName', 'UK'),), (('commonName', 'cody-ca'),)), 'notAfter': 'Jun 14 18:00:58 2028 GMT', 'notBefore': 'Jun 18 18:00:58 2018 GMT', 'serialNumber': '02', 'subject': ((('countryName', 'UK'),), (('commonName', 'codenomicon-vm-2.test.lal.cisco.com'),)), 'subjectAltName': ( ('DNS', 'codenomicon-vm-2.test.lal.cisco.com'),), 'version': 3 } ) 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, long)) 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)) @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 = ssl.wrap_socket(s) wr = weakref.ref(ss) del ss self.assertEqual(wr(), None) def test_wrapped_unconnected(self): # Methods on an unconnected SSLSocket propagate the original # socket.error raise by the underlying socket object. s = socket.socket(socket.AF_INET) with closing(ssl.wrap_socket(s)) as ss: self.assertRaises(socket.error, ss.recv, 1) self.assertRaises(socket.error, ss.recv_into, bytearray(b'x')) self.assertRaises(socket.error, ss.recvfrom, 1) self.assertRaises(socket.error, ss.recvfrom_into, bytearray(b'x'), 1) self.assertRaises(socket.error, ss.send, b'x') self.assertRaises(socket.error, ss.sendto, b'x', ('0.0.0.0', 0)) self.assertRaises(NotImplementedError, ss.dup) 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 closing(ssl.wrap_socket(s)) as ss: self.assertEqual(timeout, ss.gettimeout()) def test_errors(self): sock = socket.socket() self.assertRaisesRegexp(ValueError, "certfile must be specified", ssl.wrap_socket, sock, keyfile=CERTFILE) self.assertRaisesRegexp(ValueError, "certfile must be specified for server-side operations", ssl.wrap_socket, sock, server_side=True) self.assertRaisesRegexp(ValueError, "certfile must be specified for server-side operations", ssl.wrap_socket, sock, server_side=True, certfile="") with closing(ssl.wrap_socket(sock, server_side=True, certfile=CERTFILE)) as s: self.assertRaisesRegexp(ValueError, "can't connect in server-side mode", s.connect, (HOST, 8080)) with self.assertRaises(IOError) as cm: with closing(socket.socket()) as sock: ssl.wrap_socket(sock, certfile=NONEXISTINGCERT) self.assertEqual(cm.exception.errno, errno.ENOENT) with self.assertRaises(IOError) as cm: with closing(socket.socket()) as sock: ssl.wrap_socket(sock, certfile=CERTFILE, keyfile=NONEXISTINGCERT) self.assertEqual(cm.exception.errno, errno.ENOENT) with self.assertRaises(IOError) as cm: with closing(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): ssl.wrap_socket(sock, certfile=certfile, ssl_version=ssl.PROTOCOL_TLSv1) 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) 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 one left-most wildcard cert = {'subject': ((('commonName', 'f*.com'),),)} ok(cert, 'foo.com') ok(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 = u'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 = u'www*.pythön.org'.encode("idna").decode("ascii") cert = {'subject': ((('commonName', idna),),)} ok(cert, u'www.pythön.org'.encode("idna").decode("ascii")) ok(cert, u'www1.pythön.org'.encode("idna").decode("ascii")) fail(cert, u'ftp.pythön.org'.encode("idna").decode("ascii")) fail(cert, u'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') # 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.com'),),)} ok(cert, 'axxb.com') cert = {'subject': ((('commonName', 'a*b.co*'),),)} fail(cert, 'axxb.com') cert = {'subject': ((('commonName', 'a*b*.com'),),)} with self.assertRaises(ssl.CertificateError) as cm: ssl.match_hostname(cert, 'axxbxxc.com') self.assertIn("too many wildcards", str(cm.exception)) def test_server_side(self): # server_hostname doesn't work for server sockets ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) with closing(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) with closing(ssl.wrap_socket(s)) as ss: with self.assertRaises(ValueError): ss.get_channel_binding("unknown-type") @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 closing(ssl.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 closing(ssl.wrap_socket(s, server_side=True, certfile=CERTFILE)) as ss: self.assertIsNone(ss.get_channel_binding("tls-unique")) 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.assertRaisesRegexp(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.assertRaisesRegexp(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: ssl.wrap_socket(s, cert_reqs=ssl.CERT_NONE) self.assertEqual(str(cx.exception), "only stream sockets are supported") ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) 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 treatement 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") class ContextTests(unittest.TestCase): @skip_if_broken_ubuntu_ssl def test_constructor(self): for protocol in PROTOCOLS: ssl.SSLContext(protocol) self.assertRaises(TypeError, ssl.SSLContext) 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_TLSv1) ctx.set_ciphers("ALL") ctx.set_ciphers("DEFAULT") with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): ctx.set_ciphers("^$:,;?*'dorothyx") @skip_if_broken_ubuntu_ssl def test_options(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # 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(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # 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 @unittest.skipUnless(have_verify_flags(), "verify_flags need OpenSSL > 0.9.8") def test_verify_flags(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # 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_TLSv1) # 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(IOError) as cm: ctx.load_cert_chain(NONEXISTINGCERT) self.assertEqual(cm.exception.errno, errno.ENOENT) with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): ctx.load_cert_chain(BADCERT) with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): ctx.load_cert_chain(EMPTYCERT) # Separate key and cert ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) 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.assertRaisesRegexp(ssl.SSLError, "PEM lib"): ctx.load_cert_chain(ONLYCERT) with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): ctx.load_cert_chain(ONLYKEY) with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT) # Mismatching key and cert ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) with self.assertRaisesRegexp(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.assertRaisesRegexp(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.assertRaisesRegexp(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.assertRaisesRegexp(ValueError, "cannot be longer"): ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_huge) with self.assertRaisesRegexp(TypeError, "must return a string"): ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bad_type) with self.assertRaisesRegexp(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_TLSv1) 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) ctx.load_verify_locations(cafile=BYTES_CERTFILE.decode('utf-8')) self.assertRaises(TypeError, ctx.load_verify_locations) self.assertRaises(TypeError, ctx.load_verify_locations, None, None, None) with self.assertRaises(IOError) as cm: ctx.load_verify_locations(NONEXISTINGCERT) self.assertEqual(cm.exception.errno, errno.ENOENT) with self.assertRaises(IOError): ctx.load_verify_locations(u'') with self.assertRaisesRegexp(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().decode("ascii") cacert_der = ssl.PEM_cert_to_DER_cert(cacert_pem) with open(CAFILE_NEURONIO) as f: neuronio_pem = f.read().decode("ascii") neuronio_der = ssl.PEM_cert_to_DER_cert(neuronio_pem) # test PEM ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) 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_TLSv1) 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_TLSv1) 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_TLSv1) 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_TLSv1) 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_TLSv1) self.assertRaises(TypeError, ctx.load_verify_locations, cadata=object) with self.assertRaisesRegexp(ssl.SSLError, "no start line"): ctx.load_verify_locations(cadata=u"broken") with self.assertRaisesRegexp(ssl.SSLError, "not enough data"): ctx.load_verify_locations(cadata=b"broken") def test_load_dh_params(self): filename = u'dhpäräm.pem' fs_encoding = sys.getfilesystemencoding() try: filename.encode(fs_encoding) except UnicodeEncodeError: self.skipTest("filename %r cannot be encoded to the filesystem encoding %r" % (filename, fs_encoding)) ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) 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(IOError) 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) with support.temp_dir() as d: fname = os.path.join(d, filename) shutil.copy(DHFILE, fname) ctx.load_dh_params(fname) @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_TLSv1) 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_TLSv1) 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_TLSv1) # 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_TLSv1) 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_TLSv1) 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_TLSv1) 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_TLSv1) ctx.load_default_certs() ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) ctx.load_default_certs(ssl.Purpose.SERVER_AUTH) ctx.load_default_certs() ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) ctx.load_default_certs(ssl.Purpose.CLIENT_AUTH) ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) 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_TLSv1) 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") def test_load_default_certs_env_windows(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) ctx.load_default_certs() stats = ctx.cert_store_stats() ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) 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_SSLv23) 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().decode("ascii") ctx = ssl.create_default_context(cafile=SIGNING_CA, capath=CAPATH, cadata=cadata) self.assertEqual(ctx.protocol, ssl.PROTOCOL_SSLv23) 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_SSLv23) 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_SSLv23) 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_SSLv23) self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) self._assert_context_options(ctx) def test__https_verify_certificates(self): # Unit test to check the contect factory mapping # The factories themselves are tested above # This test will fail by design if run under PYTHONHTTPSVERIFY=0 # (as will various test_httplib tests) # Uses a fresh SSL module to avoid affecting the real one local_ssl = support.import_fresh_module("ssl") # Certificate verification is enabled by default self.assertIs(local_ssl._create_default_https_context, local_ssl.create_default_context) # Turn default verification off local_ssl._https_verify_certificates(enable=False) self.assertIs(local_ssl._create_default_https_context, local_ssl._create_unverified_context) # And back on local_ssl._https_verify_certificates(enable=True) self.assertIs(local_ssl._create_default_https_context, local_ssl.create_default_context) # The default behaviour is to enable local_ssl._https_verify_certificates(enable=False) local_ssl._https_verify_certificates() self.assertIs(local_ssl._create_default_https_context, local_ssl.create_default_context) def test__https_verify_envvar(self): # Unit test to check the PYTHONHTTPSVERIFY handling # Need to use a subprocess so it can still be run under -E https_is_verified = """import ssl, sys; \ status = "Error: _create_default_https_context does not verify certs" \ if ssl._create_default_https_context is \ ssl._create_unverified_context \ else None; \ sys.exit(status)""" https_is_not_verified = """import ssl, sys; \ status = "Error: _create_default_https_context verifies certs" \ if ssl._create_default_https_context is \ ssl.create_default_context \ else None; \ sys.exit(status)""" extra_env = {} # Omitting it leaves verification on assert_python_ok("-c", https_is_verified, **extra_env) # Setting it to zero turns verification off extra_env[ssl._https_verify_envvar] = "0" assert_python_ok("-c", https_is_not_verified, **extra_env) # Any other value should also leave it on for setting in ("", "1", "enabled", "foo"): extra_env[ssl._https_verify_envvar] = setting assert_python_ok("-c", https_is_verified, **extra_env) def test_check_hostname(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) self.assertFalse(ctx.check_hostname) # Requires CERT_REQUIRED or CERT_OPTIONAL with self.assertRaises(ValueError): ctx.check_hostname = True ctx.verify_mode = ssl.CERT_REQUIRED self.assertFalse(ctx.check_hostname) ctx.check_hostname = True self.assertTrue(ctx.check_hostname) ctx.verify_mode = ssl.CERT_OPTIONAL ctx.check_hostname = True self.assertTrue(ctx.check_hostname) # 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) 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_TLSv1) 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_TLSv1) with closing(socket.socket()) as s: s.bind(("127.0.0.1", 0)) s.listen(5) c = socket.socket() c.connect(s.getsockname()) c.setblocking(False) with closing(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) class NetworkedTests(unittest.TestCase): def test_connect(self): with support.transient_internet(REMOTE_HOST): s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE) try: s.connect((REMOTE_HOST, 443)) self.assertEqual({}, s.getpeercert()) finally: s.close() # this should fail because we have no verification certs s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED) self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed", s.connect, (REMOTE_HOST, 443)) s.close() # this should succeed because we specify the root cert s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=REMOTE_ROOT_CERT) try: s.connect((REMOTE_HOST, 443)) self.assertTrue(s.getpeercert()) finally: s.close() def test_connect_ex(self): # Issue #11326: check connect_ex() implementation with support.transient_internet(REMOTE_HOST): s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=REMOTE_ROOT_CERT) try: self.assertEqual(0, s.connect_ex((REMOTE_HOST, 443))) self.assertTrue(s.getpeercert()) finally: s.close() def test_non_blocking_connect_ex(self): # Issue #11326: non-blocking connect_ex() should allow handshake # to proceed after the socket gets ready. with support.transient_internet(REMOTE_HOST): s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=REMOTE_ROOT_CERT, do_handshake_on_connect=False) try: s.setblocking(False) rc = s.connect_ex((REMOTE_HOST, 443)) # 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()) finally: s.close() 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 = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=REMOTE_ROOT_CERT, do_handshake_on_connect=False) try: 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)) finally: s.close() def test_connect_ex_error(self): with support.transient_internet(REMOTE_HOST): s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=REMOTE_ROOT_CERT) try: rc = s.connect_ex((REMOTE_HOST, 444)) # 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) finally: s.close() def test_connect_with_context(self): with support.transient_internet(REMOTE_HOST): # Same as test_connect, but with a separately created context ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) s = ctx.wrap_socket(socket.socket(socket.AF_INET)) s.connect((REMOTE_HOST, 443)) try: self.assertEqual({}, s.getpeercert()) finally: s.close() # Same with a server hostname s = ctx.wrap_socket(socket.socket(socket.AF_INET), server_hostname=REMOTE_HOST) s.connect((REMOTE_HOST, 443)) s.close() # This should fail because we have no verification certs ctx.verify_mode = ssl.CERT_REQUIRED s = ctx.wrap_socket(socket.socket(socket.AF_INET)) self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed", s.connect, (REMOTE_HOST, 443)) s.close() # This should succeed because we specify the root cert ctx.load_verify_locations(REMOTE_ROOT_CERT) s = ctx.wrap_socket(socket.socket(socket.AF_INET)) s.connect((REMOTE_HOST, 443)) try: cert = s.getpeercert() self.assertTrue(cert) finally: s.close() 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. with support.transient_internet(REMOTE_HOST): ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ctx.verify_mode = ssl.CERT_REQUIRED ctx.load_verify_locations(capath=CAPATH) s = ctx.wrap_socket(socket.socket(socket.AF_INET)) s.connect((REMOTE_HOST, 443)) try: cert = s.getpeercert() self.assertTrue(cert) finally: s.close() # Same with a bytes `capath` argument ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ctx.verify_mode = ssl.CERT_REQUIRED ctx.load_verify_locations(capath=BYTES_CAPATH) s = ctx.wrap_socket(socket.socket(socket.AF_INET)) s.connect((REMOTE_HOST, 443)) try: cert = s.getpeercert() self.assertTrue(cert) finally: s.close() def test_connect_cadata(self): with open(REMOTE_ROOT_CERT) as f: pem = f.read().decode('ascii') der = ssl.PEM_cert_to_DER_cert(pem) with support.transient_internet(REMOTE_HOST): ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ctx.verify_mode = ssl.CERT_REQUIRED ctx.load_verify_locations(cadata=pem) with closing(ctx.wrap_socket(socket.socket(socket.AF_INET))) as s: s.connect((REMOTE_HOST, 443)) cert = s.getpeercert() self.assertTrue(cert) # same with DER ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ctx.verify_mode = ssl.CERT_REQUIRED ctx.load_verify_locations(cadata=der) with closing(ctx.wrap_socket(socket.socket(socket.AF_INET))) as s: s.connect((REMOTE_HOST, 443)) 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). with support.transient_internet(REMOTE_HOST): ss = ssl.wrap_socket(socket.socket(socket.AF_INET)) ss.connect((REMOTE_HOST, 443)) 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): with support.transient_internet(REMOTE_HOST): s = socket.socket(socket.AF_INET) s.connect((REMOTE_HOST, 443)) s.setblocking(False) s = ssl.wrap_socket(s, cert_reqs=ssl.CERT_NONE, do_handshake_on_connect=False) count = 0 while True: try: count += 1 s.do_handshake() break except ssl.SSLWantReadError: select.select([s], [], []) except ssl.SSLWantWriteError: select.select([], [s], []) s.close() if support.verbose: sys.stdout.write("\nNeeded %d calls to do_handshake() to establish session.\n" % count) def test_get_server_certificate(self): def _test_get_server_certificate(host, port, cert=None): with support.transient_internet(host): pem = ssl.get_server_certificate((host, port)) if not pem: self.fail("No server certificate on %s:%s!" % (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: self.fail("Got server certificate %s for %s:%s!" % (pem, host, port)) pem = ssl.get_server_certificate((host, port), ca_certs=cert) if not pem: self.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)) _test_get_server_certificate(REMOTE_HOST, 443, REMOTE_ROOT_CERT) if support.IPV6_ENABLED: _test_get_server_certificate('ipv6.google.com', 443) def test_ciphers(self): remote = (REMOTE_HOST, 443) with support.transient_internet(remote[0]): with closing(ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE, ciphers="ALL")) as s: s.connect(remote) with closing(ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT")) as s: s.connect(remote) # Error checking can happen at instantiation or when connecting with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): with closing(socket.socket(socket.AF_INET)) as sock: s = ssl.wrap_socket(sock, cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") s.connect(remote) def test_get_ca_certs_capath(self): # capath certs are loaded on request with support.transient_internet(REMOTE_HOST): ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ctx.verify_mode = ssl.CERT_REQUIRED ctx.load_verify_locations(capath=CAPATH) self.assertEqual(ctx.get_ca_certs(), []) s = ctx.wrap_socket(socket.socket(socket.AF_INET)) s.connect((REMOTE_HOST, 443)) try: cert = s.getpeercert() self.assertTrue(cert) finally: s.close() 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. with support.transient_internet(REMOTE_HOST): ctx1 = ssl.SSLContext(ssl.PROTOCOL_TLSv1) ctx2 = ssl.SSLContext(ssl.PROTOCOL_SSLv23) s = socket.socket(socket.AF_INET) with closing(ctx1.wrap_socket(s)) as ss: ss.connect((REMOTE_HOST, 443)) 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) try: import threading except ImportError: _have_threads = False else: _have_threads = True 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 (ssl.SSLError, socket.error, OSError) as e: if e.errno in (errno.ECONNRESET, errno.EPIPE, errno.ESHUTDOWN): # Mimick Python 3: # # except (ConnectionResetError, BrokenPipeError): # # 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 else: # 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. if not isinstance(e, ssl.SSLError) and e.errno != errno.ECONNRESET: raise self.server.conn_errors.append(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: 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 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") 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 ssl.SSLError: 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) 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.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(5) 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() self.sock.close() def stop(self): self.active = False class AsyncoreEchoServer(threading.Thread): class EchoServer(asyncore.dispatcher): class ConnectionHandler(asyncore.dispatcher_with_send): def __init__(self, conn, certfile): self.socket = ssl.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 socket.error, 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_accept(self): sock_obj, addr = self.accept() 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): """ 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 closing(client_context.wrap_socket(socket.socket(), server_hostname=sni_name)) 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(), }) s.close() stats['server_alpn_protocols'] = server.selected_alpn_protocols stats['server_npn_protocols'] = server.selected_npn_protocols 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_SSLv23: client_context.set_ciphers("ALL") for ctx in (client_context, server_context): ctx.verify_mode = certsreqs ctx.load_cert_chain(CERTFILE) ctx.load_verify_locations(CERTFILE) 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 socket.error 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: context = ssl.SSLContext(protocol) context.load_cert_chain(CERTFILE) server_params_test(context, context, chatty=True, connectionchatty=True) def test_getpeercert(self): if support.verbose: sys.stdout.write("\n") context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(CERTFILE) context.load_cert_chain(CERTFILE) server = ThreadedEchoServer(context=context, chatty=False) with server: s = context.wrap_socket(socket.socket(), do_handshake_on_connect=False) 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) s.close() @unittest.skipUnless(have_verify_flags(), "verify_flags need OpenSSL > 0.9.8") def test_crl_check(self): if support.verbose: sys.stdout.write("\n") server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) server_context.load_cert_chain(SIGNED_CERTFILE) context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(SIGNING_CA) tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0) self.assertEqual(context.verify_flags, ssl.VERIFY_DEFAULT | tf) # VERIFY_DEFAULT should pass server = ThreadedEchoServer(context=server_context, chatty=True) with server: with closing(context.wrap_socket(socket.socket())) 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 context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF server = ThreadedEchoServer(context=server_context, chatty=True) with server: with closing(context.wrap_socket(socket.socket())) as s: with self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed"): s.connect((HOST, server.port)) # now load a CRL file. The CRL file is signed by the CA. context.load_verify_locations(CRLFILE) server = ThreadedEchoServer(context=server_context, chatty=True) with server: with closing(context.wrap_socket(socket.socket())) 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") server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) server_context.load_cert_chain(SIGNED_CERTFILE) context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_REQUIRED context.check_hostname = True context.load_verify_locations(SIGNING_CA) # correct hostname should verify server = ThreadedEchoServer(context=server_context, chatty=True) with server: with closing(context.wrap_socket(socket.socket(), server_hostname="localhost")) 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 closing(context.wrap_socket(socket.socket(), server_hostname="invalid")) as s: with self.assertRaisesRegexp(ssl.CertificateError, "hostname 'invalid' doesn't match u?'localhost'"): s.connect((HOST, server.port)) # missing server_hostname arg should cause an exception, too server = ThreadedEchoServer(context=server_context, chatty=True) with server: with closing(socket.socket()) as s: with self.assertRaisesRegexp(ValueError, "check_hostname requires server_hostname"): context.wrap_socket(s) def test_wrong_cert(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. """ certfile = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") server = ThreadedEchoServer(SIGNED_CERTFILE, certreqs=ssl.CERT_REQUIRED, cacerts=SIGNING_CA, chatty=False, connectionchatty=False) with server, \ closing(socket.socket()) as sock, \ closing(ssl.wrap_socket(sock, certfile=certfile, ssl_version=ssl.PROTOCOL_TLSv1)) 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 socket.error 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(5) listener_ready.set() newsock, addr = s.accept() newsock.close() s.close() listener_gone.set() def connector(): listener_ready.wait() with closing(socket.socket()) as c: c.connect((HOST, port)) listener_gone.wait() try: ssl_sock = ssl.wrap_socket(c) except socket.error: pass else: self.fail('connecting to closed SSL socket should have failed') t = threading.Thread(target=listener) t.start() try: connector() finally: t.join() @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_SSLv23, False) 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_SSLv23, False, client_options=ssl.OP_NO_SSLv2) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, client_options=ssl.OP_NO_SSLv3) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, client_options=ssl.OP_NO_TLSv1) @skip_if_broken_ubuntu_ssl def test_protocol_sslv23(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_SSLv23, ssl.PROTOCOL_SSLv2, True) except socket.error 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_SSLv23, ssl.PROTOCOL_SSLv3, False) try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True) try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1') if hasattr(ssl, 'PROTOCOL_SSLv3'): try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL) if hasattr(ssl, 'PROTOCOL_SSLv3'): try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, ssl.CERT_REQUIRED) try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED) try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED) # Server with specific SSL options if hasattr(ssl, 'PROTOCOL_SSLv3'): try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, server_options=ssl.OP_NO_SSLv3) # Will choose TLSv1 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) try_protocol_combo(ssl.PROTOCOL_SSLv23, 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_SSLv23, 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_SSLv23, 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_SSLv23, 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_SSLv23, False, client_options=ssl.OP_NO_TLSv1_1) try_protocol_combo(ssl.PROTOCOL_SSLv23, 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_SSLv23, False, client_options=ssl.OP_NO_TLSv1_2) try_protocol_combo(ssl.PROTOCOL_SSLv23, 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, ssl_version=ssl.PROTOCOL_TLSv1, 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 = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1) 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 a SocketServer to create and manage SSL connections.""" server = make_https_server(self, certfile=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=CERTFILE) f = urllib2.urlopen(url, context=context) try: dlen = f.info().getheader("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 = ssl.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_TLSv1, cacerts=CERTFILE, chatty=True, connectionchatty=False) with server: s = ssl.wrap_socket(socket.socket(), server_side=False, certfile=CERTFILE, ca_certs=CERTFILE, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLSv1) 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, whether to expect success, *args) send_methods = [ ('send', s.send, True, []), ('sendto', s.sendto, False, ["some.address"]), ('sendall', s.sendall, True, []), ] recv_methods = [ ('recv', s.recv, True, []), ('recvfrom', s.recvfrom, False, ["some.address"]), ('recv_into', _recv_into, True, []), ('recvfrom_into', _recvfrom_into, False, []), ] data_prefix = u"PREFIX_" for meth_name, send_meth, expect_success, args in send_methods: indata = (data_prefix + meth_name).encode('ascii') try: send_meth(indata, *args) 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) self.assertRaises(NotImplementedError, s.dup) 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 = ssl.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_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(5) 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.assertRaisesRegexp(ssl.SSLError, "timed out", ssl.wrap_socket, c) finally: c.close() try: c = socket.socket(socket.AF_INET) c = ssl.wrap_socket(c) c.settimeout(0.2) # Will attempt handshake and time out self.assertRaisesRegexp(ssl.SSLError, "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_SSLv23) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(CERTFILE) context.load_cert_chain(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) evt = threading.Event() remote = [None] peer = [None] def serve(): server.listen(5) # Block on the accept and wait on the connection to close. evt.set() remote[0], peer[0] = server.accept() remote[0].send(remote[0].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[0].close() server.close() # Sanity checks. self.assertIsInstance(remote[0], ssl.SSLSocket) self.assertEqual(peer[0], client_addr) def test_getpeercert_enotconn(self): context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) with closing(context.wrap_socket(socket.socket())) as sock: with self.assertRaises(socket.error) as cm: sock.getpeercert() self.assertEqual(cm.exception.errno, errno.ENOTCONN) def test_do_handshake_enotconn(self): context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) with closing(context.wrap_socket(socket.socket())) as sock: with self.assertRaises(socket.error) as cm: sock.do_handshake() self.assertEqual(cm.exception.errno, errno.ENOTCONN) def test_no_shared_ciphers(self): server_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) server_context.load_cert_chain(SIGNED_CERTFILE) client_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) client_context.verify_mode = ssl.CERT_REQUIRED client_context.check_hostname = True # 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: s = client_context.wrap_socket( socket.socket(), server_hostname="localhost") with self.assertRaises(ssl.SSLError): s.connect((HOST, server.port)) self.assertIn("no shared cipher", str(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_TLSv1) with ThreadedEchoServer(CERTFILE, ssl_version=ssl.PROTOCOL_TLSv1, chatty=False) as server: with closing(context.wrap_socket(socket.socket())) as s: self.assertIs(s.version(), None) s.connect((HOST, server.port)) self.assertEqual(s.version(), 'TLSv1') 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) # disable all but TLS 1.3 context.options |= ( ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_TLSv1_2 ) with ThreadedEchoServer(context=context) as server: s = context.wrap_socket(socket.socket()) with closing(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', ]) @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_SSLv23) 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 closing(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") server = ThreadedEchoServer(CERTFILE, certreqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLSv1, cacerts=CERTFILE, chatty=True, connectionchatty=False) with server: s = ssl.wrap_socket(socket.socket(), server_side=False, certfile=CERTFILE, ca_certs=CERTFILE, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLSv1) 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) 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")) s.close() # now, again s = ssl.wrap_socket(socket.socket(), server_side=False, certfile=CERTFILE, ca_certs=CERTFILE, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLSv1) 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) 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")) s.close() def test_compression(self): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.load_cert_chain(CERTFILE) stats = server_params_test(context, context, chatty=True, connectionchatty=True) 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): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.load_cert_chain(CERTFILE) context.options |= ssl.OP_NO_COMPRESSION stats = server_params_test(context, context, chatty=True, connectionchatty=True) self.assertIs(stats['compression'], None) def test_dh_params(self): # Check we can get a connection with ephemeral Diffie-Hellman context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.load_cert_chain(CERTFILE) context.load_dh_params(DHFILE) context.set_ciphers("kEDH") stats = server_params_test(context, context, chatty=True, connectionchatty=True) 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]) def test_selected_alpn_protocol(self): # selected_alpn_protocol() is None unless ALPN is used. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.load_cert_chain(CERTFILE) stats = server_params_test(context, context, chatty=True, connectionchatty=True) 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 = ssl.SSLContext(ssl.PROTOCOL_TLSv1) client_context.load_verify_locations(CERTFILE) server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) server_context.load_cert_chain(CERTFILE) server_context.set_alpn_protocols(['foo', 'bar']) stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True) 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: server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) server_context.load_cert_chain(CERTFILE) server_context.set_alpn_protocols(server_protocols) client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) client_context.load_cert_chain(CERTFILE) client_context.set_alpn_protocols(client_protocols) try: stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True) except ssl.SSLError as e: stats = e if (expected is None and IS_OPENSSL_1_1 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 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.load_cert_chain(CERTFILE) stats = server_params_test(context, context, chatty=True, connectionchatty=True) 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: server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) server_context.load_cert_chain(CERTFILE) server_context.set_npn_protocols(server_protocols) client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) client_context.load_cert_chain(CERTFILE) client_context.set_npn_protocols(client_protocols) stats = server_params_test(client_context, server_context, chatty=True, connectionchatty=True) 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_TLSv1) server_context.load_cert_chain(SIGNED_CERTFILE) other_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) other_context.load_cert_chain(SIGNED_CERTFILE2) client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) client_context.verify_mode = ssl.CERT_REQUIRED 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() 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, 'localhost') # 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, 'localhost') 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/0.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_read_write_after_close_raises_valuerror(self): context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(CERTFILE) context.load_cert_chain(CERTFILE) server = ThreadedEchoServer(context=context, chatty=False) with server: s = context.wrap_socket(socket.socket()) s.connect((HOST, server.port)) s.close() self.assertRaises(ValueError, s.read, 1024) self.assertRaises(ValueError, s.write, b'hello') def test_main(verbose=False): if support.verbose: plats = { 'Linux': platform.linux_distribution, 'Mac': platform.mac_ver, 'Windows': platform.win32_ver, } 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, REMOTE_ROOT_CERT, 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, BasicTests, BasicSocketTests, SSLErrorTests] if support.is_resource_enabled('network'): tests.append(NetworkedTests) if _have_threads: thread_info = support.threading_setup() if thread_info: tests.append(ThreadedTests) try: support.run_unittest(*tests) finally: if _have_threads: support.threading_cleanup(*thread_info) if __name__ == "__main__": test_main()
WorkerService.py
from __future__ import absolute_import from functools import wraps __author__ = 'patrizio' import celery.bin.worker from multiprocessing import Process from celery import Celery from celery.signals import task_success, task_failure, task_revoked from kombu import Queue, Exchange from ssl import CERT_REQUIRED from testagent.utils.Singleton import Singleton from testagent.exceptions.WorkerServiceException import WorkerServiceException from testagent.options import default_options, CELERY_LOGFILE import testagent.subscription_options @task_success.connect def task_success_handler(sender=None, result=None, args=None, kwargs=None, **kwds): ws = WorkerService() result_to_send = sender.request.id + "#" + str(result[0]) print("Sending back: " + result_to_send) #queue = Queue('collector_agents', # Exchange("collector_agents", type="direct"), # 'key-test') exchange = Exchange(ws.CeleryConfiguration.RESULT_EXCHANGE_NAME, type=ws.CeleryConfiguration.RESULT_EXCHANGE_TYPE) queue = Queue(ws.CeleryConfiguration.RESULT_QUEUE_NAME, exchange=exchange, routing_key=ws.CeleryConfiguration.RESULT_ROUTING_KEY ) with ws.app.producer_or_acquire(None) as prod: prod.publish(result_to_send, serializer='raw', routing_key=ws.CeleryConfiguration.RESULT_ROUTING_KEY, declare=[queue], exchange=exchange, retry=True) print("Sent back: " + result_to_send) class WorkerService(Singleton): status = None worker_process = None class CeleryConfiguration(object): """ default settings """ CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_EVENT_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_IMPORTS = ('testagent.tasks',) CELERYD_POOL_RESTARTS = True CELERYD_HIJACK_ROOT_LOGGER = False def __custom_banner(self): RED = "\033[1;49;31m" WHITE = "\033[1;49;37m" RESET_SEQ = "\033[1;49;37m" from celery.apps import worker as celery_worker celery_worker.ARTLINES = [] celery_worker.BANNER = """\n \t\t\tCelery Version {version} Welcome\t\t\t\t\t""" + RED + """{hostname}"""+RESET_SEQ+""" => Test Agent ID:\t\t\t"""+RED+"""{app}"""+RESET_SEQ+""" => Broker:\t\t\t\t"""+RED+"""{conninfo}"""+RESET_SEQ+""" => Results backend broker:\t\t"""+RED+"""{results}"""+RESET_SEQ+""" => Concurrency\t\t\t\t"""+RED+"""{concurrency}"""+RESET_SEQ+""" => Active queues {queues} """ ARTLINES = [ RED+''' .lkKWMWNKx:. ''' + RESET_SEQ, RED+''' ;xXMMMMMMMMMMMMKd' ''' + RESET_SEQ, RED+''' .dWMMW0 KMMMXl. ''' + RESET_SEQ, RED+''' xMMM0: cXMMWl ''' + RESET_SEQ, RED+''' ..,,;,'. .XMMK, ;NMM0. ''' + RESET_SEQ, RED+''' ,o0WMMMMMMMMMXkNMMd OMMK ''' + RESET_SEQ, RED+''' .;okKXNNX0kl' .oNMMMXOdc::clx0WMMMk 0MMd ''' + RESET_SEQ, RED+''' c0MMMMWXKKXWMMMWkdWMMKc. ,dK. \'MMW ''' + RESET_SEQ, RED+''' :NMMWx;. .:OMMMMX; WMMk. ''' + RESET_SEQ, RED+''' kMMNc .dWO ;OMMMO. ''' + RESET_SEQ, RED+''' xMMX. . .kMMWc ''' + RESET_SEQ, RED+''' 'MMW. :WMMl ''' + RESET_SEQ, RED+''' dMMk ;MMM ''' + RESET_SEQ, RED+''' .cdkOONMMk xMMO ''' + RESET_SEQ, RED+''' .oXMMMMMMMMMN '''+WHITE+''' '''+RED+''' ,MMW ''' + RESET_SEQ, RED+''' ;WMMXl. .,o0: '''+WHITE+''' '''+RED+''' 'MMW ''' + RESET_SEQ, RED+''';MMMl '''+WHITE+''' TEST BASED CERTIFICATION ENVIRONMENT '''+RED+''' lMM0 ''' + RESET_SEQ, RED+'''XMMl '''+WHITE+''' TEST AGENT version 1.1 - April 2015 '''+RED+''' .WMM; ''' + RESET_SEQ, RED+'''WMM' '''+WHITE+''' Patrizio Tufarolo <patrizio.tufarolo@studenti.unimi.it> '''+RED+''' .XMMx ''' + RESET_SEQ, RED+'''0MMd '''+WHITE+''' '''+RED+''' cWMMd ''' + RESET_SEQ, RED+''''WMMd .cXMMK, ''' + RESET_SEQ, RED+''' ;NMMNd;....................................................................,cdKMMM0: ''' + RESET_SEQ, RED+''' .oNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWOl. ''' + RESET_SEQ, RED+''' c0WMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWN0o, ''' + RESET_SEQ, ] celery_worker.BANNER = '\n'.join(ARTLINES) + "\n" + celery_worker.BANNER + "\n" def configure(self, app=None, options=None): options = options if options else default_options self.app = app or Celery("testagent") if (options and options.broker_url and options.results_exchange_name and options.results_exchange_type and options.results_queue_name and options.results_routing_key and options.tasks_exchange_name and options.tasks_exchange_name and options.tasks_exchange_type and options.tasks_queue_name): super(WorkerService, self).configure() self.__custom_banner() self.status = "stopped" self.worker_process = Process() print self.CeleryConfiguration self.CeleryConfiguration.BROKER_URL = options.broker_url self.CeleryConfiguration.CELERY_TIMEZONE = options.timezone self.CeleryConfiguration.CELERY_RESULT_BACKEND = options.backend_broker_url self.CeleryConfiguration.CELERY_DEFAULT_QUEUE = options.tasks_queue_name self.CeleryConfiguration.CELERY_QUEUES = [ Queue(options.tasks_queue_name, exchange=Exchange(options.tasks_exchange_name, type=options.tasks_exchange_type), routing_key=options.tasks_routing_key ) ] self.CeleryConfiguration.BROKER_USE_SSL = False if options.broker_ssl_enable and options.broker_ssl_ca: self.CeleryConfiguration.BROKER_USE_SSL = { "ca_certs": options.broker_ssl_cacerts } if options.broker_ssl_verifycert and options.broker_ssl_keyfile and options.broker_ssl_certfile: self.CeleryConfiguration.BROKER_USE_SSL["keyfile"] = options.broker_ssl_keyfile self.CeleryConfiguration.BROKER_USE_SSL["certfile"] = options.broker_ssl_certfile self.CeleryConfiguration.BROKER_USE_SSL["cert_reqs"] = CERT_REQUIRED self.CeleryConfiguration.RESULT_EXCHANGE_NAME = options.results_exchange_name self.CeleryConfiguration.RESULT_EXCHANGE_TYPE = options.results_exchange_type self.CeleryConfiguration.RESULT_QUEUE_NAME = options.results_queue_name self.CeleryConfiguration.RESULT_ROUTING_KEY = options.results_routing_key self.app.config_from_object(self.CeleryConfiguration) self.app.connection = self.app.broker_connection self.app.loader.import_default_modules() self.options = options @Singleton._if_configured(WorkerServiceException) def deconfigure(self): self._configured = False def get_app(self): if self.app: return self.app @Singleton._if_configured(WorkerServiceException) def _worker_thread(self): wrk = celery.bin.worker.worker(app=self.app) wrk.run(logfile=CELERY_LOGFILE) def get_options(self): try: return self.options if self.options else default_options except: return default_options @Singleton._if_configured(WorkerServiceException) def start_worker(self): if self.status != "started": self.worker_process = Process(target=self._worker_thread) self.worker_process.start() self.status = "started" @Singleton._if_configured(WorkerServiceException) def stop_worker(self): if self.worker_process.is_alive(): self.worker_process.terminate() if self.status == "started": self.status = "stopped"
__init__.py
""" Copyright (c) 2015 SONATA-NFV and Paderborn University 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. Neither the name of the SONATA-NFV, Paderborn University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. This work has been performed in the framework of the SONATA project, funded by the European Commission under Grant number 671517 through the Horizon 2020 and 5G-PPP programmes. The authors would like to acknowledge the contributions of their colleagues of the SONATA partner consortium (www.sonata-nfv.eu). """ """ This module implements a simple REST API that behaves like SONATA's gatekeeper. It is only used to support the development of SONATA's SDK tools and to demonstrate the year 1 version of the emulator until the integration with WP4's orchestrator is done. """ import logging import threading import dummygatekeeper as dgk class SonataDummyGatekeeperEndpoint(object): """ Creates and starts a REST API based on Flask in an additional thread. Can connect this API to data centers defined in an emulator topology. """ def __init__(self, listenip, port, deploy_sap=False, docker_management=False, auto_deploy=False, auto_delete=False, sap_vnfd_path=None): self.dcs = {} self.ip = listenip self.port = port dgk.DEPLOY_SAP = deploy_sap dgk.USE_DOCKER_MGMT = docker_management dgk.AUTO_DEPLOY = auto_deploy dgk.AUTO_DELETE = auto_delete dgk.SAP_VNFD = sap_vnfd_path logging.debug("Created API endpoint %s" % self) def __repr__(self): return "%s(%s:%d)" % (self.__class__.__name__, self.ip, self.port) def connectDatacenter(self, dc): self.dcs[dc.label] = dc logging.info("Connected DC(%s) to API endpoint %s" % ( dc, self)) def start(self): thread = threading.Thread(target=self._api_server_thread, args=()) thread.daemon = True thread.start() logging.debug("Started API endpoint %s" % self) def _api_server_thread(self): dgk.start_rest_api(self.ip, self.port, self.dcs)
examplecricketstream.py
import logging import queue import threading import betfairlightweight # setup logging logging.basicConfig(level=logging.INFO) # change to DEBUG to see log all updates # create trading instance (app key must be activated for cricket stream) trading = betfairlightweight.APIClient("username", "password", app_key="appKey") # login trading.login() # create queue output_queue = queue.Queue() # create stream listener listener = betfairlightweight.StreamListener(output_queue=output_queue) # create stream stream = trading.streaming.create_stream(listener=listener, host="sports_data") # subscribe streaming_unique_id = stream.subscribe_to_cricket_matches() # start stream in a new thread (in production would need err handling) t = threading.Thread(target=stream.start, daemon=True) t.start() # check for updates in output queue while True: updates = output_queue.get() for update in updates: print(update.json())
alpaca_discovery.py
#!/usr/bin/env python3 """Provides the ability to find IPv4 ASCOM Alpaca servers on the local networks. Uses the netifaces library to find the broadcast IPs that can be used for sending the UDP discovery message. Some functions accept **kwargs (i.e. unspecified keyword arguments) so that they can be passed arguments that originated from argparse, which may well include arguments not of interested to the methods here. Note that I've chosen to omit support for IPv6 because I don't need it for testing Tiny Alpaca Server. TODO(jamessynge): Figure out if I can NOT use netifaces to get the network interface information. """ import argparse import dataclasses import json import queue import socket import sys import threading import time from typing import Callable, Dict, Generator, List, Optional import install_advice try: import netifaces # pylint: disable=g-import-not-at-top except ImportError: install_advice.install_advice('netifaces') # build_cleaner doesn't find imports that aren't at the top level, so we repeat # the import here. import netifaces # pylint: disable=g-import-not-at-top,g-bad-import-order # Daniel VanNoord selected UDP port 32227 for the Alpaca Discovery protocol, but # that port is not officially assigned to the protocol, so it may change some # day. An Alpaca Server can confirm that the packet is intended for it by # looking for the string 'alpacadiscovery1' as the entire body of the UDP packet # it receives at that port, and an Alpaca Discovery client can confirm that a # response is from an Alpaca Server by checking that the response body can be # parsed as JSON and has a property 'alpacaport' whose value is an integer that # can be a TCP port number (e.g. 1 to 65535). ALPACA_DISCOVERY_PORT = 32227 DISCOVERY_REQUEST_BODY = 'alpacadiscovery1' ALPACA_SERVER_PORT_PROPERTY = 'alpacaport' DEFAULT_DISCOVERY_SECS = 2.0 @dataclasses.dataclass class DiscoverySource: """Addresses from and to which to send ASCOM Alpaca discovery packets.""" interface_name: str src_address: str dst_address: str dst_is_broadcast: bool def get_name(self) -> str: return f'{self.dst_address} via {self.interface_name}' def create_bound_udp_socket(self) -> socket.socket: """Create UDP port for sending to dst_address.""" # -------------------------------- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if self.dst_is_broadcast: sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) try: sock.bind((self.src_address, 0)) # listen to any on a temporary port except: print(f'failure to bind {self}', file=sys.stderr, flush=True) sock.close() raise # sock.setblocking(0) return sock def send_discovery_packet(self, sock: socket.socket, verbose=False): """Writes an Alpaca Discovery UDP Packet to sock.""" if verbose: action = 'Broadcasting' if self.dst_is_broadcast else 'Sending' # Appending a \n explicitly because multiple threads will output strings, # and I've found that the default end value is output as a separate # operation that can come after the "Collected..." string from another # thread. print( f'{action} from {self.src_address} to {self.dst_address}\n', flush=True, end='') sock.sendto( DISCOVERY_REQUEST_BODY.encode(encoding='ascii'), (self.dst_address, ALPACA_DISCOVERY_PORT)) @dataclasses.dataclass class DiscoveryResponse: """Represents an Alpaca Discovery Protocol Response from an Alpaca Server.""" source: DiscoverySource data_bytes: bytes recvfrom_addr: str recvfrom_port: int # The discovery port. def get_alpaca_server_addr(self) -> str: return f'{self.recvfrom_addr}:{self.get_port()}' def get_port(self) -> int: data_str = str(self.data_bytes, 'ascii') jsondata = json.loads(data_str) return int(jsondata[ALPACA_SERVER_PORT_PROPERTY]) def generate_addresses(address_family) -> Generator[Dict[str, str], None, None]: """docstring.""" # netifaces.interfaces returns a list of interface names. for name in netifaces.interfaces(): # netifaces.ifaddresses(interface_name) returns a dictionary mapping an # address family (e.g. netifaces.AF_INET for IPv4) to a list of address # groups (dictionaries) provided by that interface. Note that a single # interface may have multiple addresses, even for a single address family. for addr_family, addr_groups in netifaces.ifaddresses(name).items(): if address_family == addr_family: for address_group in addr_groups: if 'addr' not in address_group: # Note that I'm assuming continue result = dict(interface_name=name) result.update(address_group) yield result def generate_discovery_sources() -> Generator[DiscoverySource, None, None]: """docstring.""" for address_group in generate_addresses(netifaces.AF_INET): if 'broadcast' in address_group: yield DiscoverySource( interface_name=address_group['interface_name'], src_address=address_group['addr'], dst_address=address_group['broadcast'], dst_is_broadcast=True) elif 'peer' in address_group: yield DiscoverySource( interface_name=address_group['interface_name'], src_address=address_group['addr'], dst_address=address_group['peer'], dst_is_broadcast=False) def receiver(sock: socket.socket, max_discovery_secs: float, response_queue: queue.Queue) -> None: sock.settimeout(max_discovery_secs) while True: try: data_bytes, addr = sock.recvfrom(1024) except socket.timeout: return # For AF_INET sockets, addr is a pair, (host, port). response_queue.put((data_bytes, addr[0], addr[1])) class Discoverer(object): """Performs Alpaca Discovery for a single DiscoverySource.""" def __init__(self, source: DiscoverySource): self.source = source def perform_discovery(self, response_queue: queue.Queue, max_discovery_secs: float = DEFAULT_DISCOVERY_SECS, verbose=False) -> threading.Thread: """Returns a thread which writes DiscoveryResponses to response_queue.""" def worker(): for r in self.generate_responses( max_discovery_secs=max_discovery_secs, verbose=verbose): response_queue.put(r) t = threading.Thread(target=worker, name=self.source.get_name()) t.start() return t def generate_responses( self, max_discovery_secs: float = DEFAULT_DISCOVERY_SECS, verbose=False) -> Generator[DiscoveryResponse, None, None]: """Yields DiscoveryResponses after sending from the source address.""" sock = self.source.create_bound_udp_socket() q = queue.Queue(maxsize=1000) t = threading.Thread(target=receiver, args=(sock, max_discovery_secs, q)) t.start() iota = max(0.001, min(0.05, max_discovery_secs / 100.0)) time.sleep(iota) self.source.send_discovery_packet(sock, verbose=verbose) count = 0 while t.is_alive(): try: data_bytes, addr, port = q.get(block=True, timeout=iota) except queue.Empty: continue yield DiscoveryResponse( source=self.source, data_bytes=data_bytes, recvfrom_addr=addr, recvfrom_port=port) count += 1 t.join() while not q.empty(): data_bytes, addr, port = q.get(block=False) yield DiscoveryResponse( source=self.source, data_bytes=data_bytes, recvfrom_addr=addr, recvfrom_port=port) if verbose: # Appending a \n explicitly because multiple threads will output strings, # and I've found that the default end value is output as a separate # operation that can come after the "Collected..." string from another # thread. print( f'Collected {count} responses for source {self.source.get_name()}\n', flush=True, end='') def perform_discovery(discovery_response_handler: Callable[[DiscoveryResponse], None], sources: Optional[List[DiscoverySource]] = None, max_discovery_secs: float = DEFAULT_DISCOVERY_SECS, verbose=False, **kwargs) -> None: """Sends a discovery packet from all sources, passes results to handler.""" del kwargs # Unused. if sources is None: if verbose: print('Finding network interfaces to use for discovery.') sources = list(generate_discovery_sources()) discoverers = [Discoverer(source) for source in sources] q = queue.Queue(maxsize=1000) threads = [] for d in discoverers: threads.append( d.perform_discovery( response_queue=q, max_discovery_secs=max_discovery_secs, verbose=verbose)) start_secs = time.time() while threads: if not threads[0].is_alive(): t = threads.pop(0) if verbose: print('Thread %r is done' % t.name, flush=True) t.join() while not q.empty(): dr = q.get(block=False) discovery_response_handler(dr) time.sleep(0.01) end_secs = time.time() if verbose: elapsed_secs = end_secs - start_secs print(f'perform_discovery: elapsed_secs={elapsed_secs}') if elapsed_secs < max_discovery_secs: print( f'perform_discovery: ended {max_discovery_secs - elapsed_secs}s early' ) def find_first_server(**kwargs) -> Optional[DiscoveryResponse]: """Return the first server to respond, else None.""" result = None def discovery_response_handler(dr: DiscoveryResponse) -> None: nonlocal result if result is not None: return result = dr perform_discovery(discovery_response_handler, **kwargs) return result def make_discovery_parser() -> argparse.ArgumentParser: """Returns a parser for discovery operations.""" parser = argparse.ArgumentParser(add_help=False) parser.add_argument( '--max_discovery_secs', metavar='SECONDS', type=float, default=DEFAULT_DISCOVERY_SECS, help='Time to wait (seconds) for Alpaca Discovery responses.') parser.add_argument( '--verbose', '-v', action='store_true', help='Print more messages about what the program is doing.') return parser def main(): parser = argparse.ArgumentParser( description='Find Alpaca servers.', parents=[make_discovery_parser()]) cli_args = parser.parse_args() cli_kwargs = vars(cli_args) def discovery_response_handler(dr: DiscoveryResponse) -> None: print('Found a server at', dr.get_alpaca_server_addr()) perform_discovery(discovery_response_handler, **cli_kwargs) if __name__ == '__main__': main()
main.py
from lib.appController import Controller, device_name_queue from appCase.test_qq import QQDemo from lib.logger import logger from lib.result import Result from lib import HTMLTestAppRunner from lib.path import APPREPORT import threading import unittest local = threading.local() class App(object): def __init__(self): self.c = Controller() def case(self): # 通过导入测试类来实现生成测试集 suite = unittest.TestLoader().loadTestsFromTestCase(QQDemo) # 生成一个空的结果集 local.result = Result() # 运行case,并更新结果集,记录正确的case 失败的case res = suite.run(local.result) # 将结果通过测试手机名称进行区分 logger.debug('当前线程的的名字:%s' % threading.current_thread().getName()) # 当前线程的名字 就是当前运行手机的名字 result = {threading.current_thread().getName(): res} for deviceName, result in result.items(): html = HTMLTestAppRunner.HTMLTestRunner(stream=open(APPREPORT.format('{}.html'.format(deviceName)), "wb"), verbosity=2, title='测试') # 这个方法就是生成报告的主要函数 html.generateReport('', result) def run(self): threads = [] self.c.server() if self.c.test_server(): drivers = self.c.driver() logger.info('开始执行CASE!当前启动[%s]个DRIVER!' % drivers.qsize()) # 根据由多少个driver执行多少次case for case in range(drivers.qsize()): # 根据driver启动多线程跑case,对每个线程通过手机名 命名 t = threading.Thread(target=self.case, name=device_name_queue.get()) threads.append(t) t.start() for t in threads: t.join() if __name__ == '__main__': App().run()
benchmark_runner.py
import csv import multiprocessing import pathlib import time from typing import Callable, List import benchmark import start_webserver from helpers import constants OUTPUT_DIR = "./output" RESULT_PREFIX = "results_" WEBSERVERS = [ ("Flask", start_webserver.start_flask), ("FastAPI_sync", start_webserver.start_fast), ("FastAPI_async", start_webserver.start_fast_async) ] def start_webserver_background(start_fn: Callable, kwargs=None, initialization_time=5) -> multiprocessing.Process: p = multiprocessing.Process(target=start_fn, kwargs=kwargs if kwargs else {}) p.start() time.sleep(initialization_time) return p def start_wait_server() -> multiprocessing.Process: return start_webserver_background(start_webserver.start_fast_async, kwargs={"port": constants.WAIT_PORT}) def run_benchmark(benchmark_instance: benchmark.Benchmark) -> List[List[str]]: results: List[List[str]] = [] for name, start_fn in WEBSERVERS: def setup(): start_wait_server() start_webserver_background(start_fn) def teardown(): start_webserver.kill_webservers() result = benchmark.run_benchmark(benchmark_instance, setup, teardown) results.append([name] + result) return results if __name__ == "__main__": for benchmark_instance in benchmark.BENCHMARKS: print("Running benchmarks for", benchmark_instance.name()) results = run_benchmark(benchmark_instance) file_path = pathlib.Path(OUTPUT_DIR) / "".join((benchmark_instance.name(), ".csv")) with open(file_path, "w") as csvfile: writer = csv.writer(csvfile) writer.writerow(["name"] + benchmark.HEADERS) for result in results: writer.writerow(result)
display.py
import time import cv2 from multiprocessing import Process, Queue def _display_loop(camera_number: int, request_queue: Queue): my_cam = cv2.VideoCapture(camera_number) current_text = None while True: ret_val, img = my_cam.read() new_text = None if not request_queue.empty(): req = request_queue.get_nowait() if req: type = req.get("type") if type == "clear": current_text = None elif type == "set": current_text = req img = cv2.flip(img, 1) if current_text: _draw_main_text(img, current_text.get("text")) _draw_sub_text(img, current_text.get("subtext")) cv2.imshow("my webcam", img) # for some reason this line needs to be here or this doesn't work. I don't know why, # but I do know it won't work otherwise! if cv2.waitKey(1) == 27: break # esc to quit time.sleep(0.01) def _draw_main_text(img, text="Die!"): height, width, _ = img.shape font_scale = 7 thickness = 4 (text_width, text_height), _ = cv2.getTextSize( text, fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=font_scale, thickness=thickness, ) while text_width >= width: font_scale -= 1 (text_width, text_height), _ = cv2.getTextSize( text, fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=font_scale, thickness=thickness, ) text_location = ( int(width / 2 - text_width / 2), int(height / 2 + text_height / 2), ) _draw_text(img, text, text_location, font_scale, thickness) def _draw_sub_text(img, text="Kill them!"): _draw_text(img, text, text_location=(50, 50), font_scale=1, thickness=4) def _draw_text(img, text, text_location, font_scale, thickness): cv2.putText( img, text=text, org=text_location, fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=font_scale, color=[0, 0, 0], lineType=cv2.LINE_AA, thickness=thickness, ) cv2.putText( img, text=text, org=text_location, fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=font_scale, color=[255, 255, 255], lineType=cv2.LINE_AA, thickness=(thickness - 2), ) class PhotoboothDisplay: def __init__(self, camera_to_use) -> "PhotoboothDisplay": self.request_queue = Queue() Process( target=_display_loop, args=(camera_to_use, self.request_queue), daemon=True ).start() def put_text(self, text, subtext="") -> None: self.request_queue.put({"type": "set", "text": text, "subtext": subtext}) def clear_text(self) -> None: self.request_queue.put({"type": "clear"})
__init__.py
# coding: utf-8 """ 画面操作の制御を行う __init__.pyファイルはこのディレクトリ以下をインポートされると必ず呼び出されるのでここに書く。 もちろん、コードが増えてきた場合は別途ファイルに書いてここでインポートする構成でも構いません。 ここでは画面に何を表示するかの管理を行う。 このライブラリはMQTTと画面表示での並列動作が必要なので、 threadingライブラリを使用してそれを実現しています。 https://docs.python.jp/3/library/threading.html """ from logging import getLogger logger = getLogger(__name__) import unicornhathd import time # 表示動作を行う関数のインポート from .clock import loop as clock_loop from .weather import loop as weather_loop from threading import Thread, Event # eventオブジェクトを作成する # https://docs.python.jp/3/library/threading.html#event-objects event = Event() driver = None def change(mode): """ 画面の変更要求を受け付ける関数。 使用時はこれをインポートして、随時関数を始動してこれを操作する。 """ # 渡されたモードの確認。 # 知らないモードが渡された場合はここで受付を棄却する if mode not in ('clock', 'weather'): logger.warn('invalid mode (%s)', mode) return False logger.debug('get change call to "%s"', mode) # モードに対応した関数を用意する func = None if mode == 'clock': func = clock_loop elif mode == 'weather': func = weather_loop else: logger.error('cant get function.') return False # イベントオブジェクトをセットして現在動作している表示処理を終了させる。 # これがセットされると表示関数中ループを抜け出すことにより関数が終了し、デーモンも消滅する。 # 各表示関数はwhileループ毎でこれを確認しているので終了には時間がかかる。 # なのである程度待つ必要がある。 # 動作モードによって終了に必要な時間にばらつきがある場合は、Lockオブジェクトを使用するのもアリ event.set() time.sleep(1) # イベントオブジェクトをリセットして再利用可能にする event.clear() # Threadオブジェクトに動作関数を渡し、並列動作を開始させる(デーモンの作成) # ここでeventオブジェクトを渡して終了イベントを渡せるようにする # https://docs.python.jp/3/library/threading.html#thread-objects driver = Thread(target=func, args=(event,)) driver.daemon = True driver.start() logger.debug('change sequence is end.') return True def start(): ''' スタート用の関数 呼び出されるととりあず時計を表示する ''' logger.debug('display initial function start.') change('clock') def end(): ''' 処理終了用の関数 デーモンを終了させ、unicornHatHDの表示をOFFにする。 ''' event.set() time.sleep(1) unicornhathd.off()
plugin.py
#! /usr/bin/env python # -*- coding: utf-8 -*- #################### # Copyright (c) 2013, Richard Perlman All rights reserved. # with much credit to Rob Smith (kormoc) -- https://github.com/BrightcoveOS/Diamond/blob/master/src/collectors/apcupsd/apcupsd.py # # Starting with 0.5.0, revised by Marty Skinner (https://github.com/MartySkinner/Indigo-apcupsd) # ################################################################################ # Imports ################################################################################ from berkinet import logger from ghpu import GitHubPluginUpdater import inspect import os import socket import string import sys import threading import time import subprocess ################################################################################ # Globals ################################################################################ k_utilityBinaryName = u"apcaccess" k_utilityBinaryPath = u"/usr/local/sbin:/sbin" k_utilityCommand = u"{binary} status {address} {port}".format k_utilityOutputSeparator = u": " k_utilityOutputSpaceReplacement = u"_" k_utilityOutputUnitWords = [u'Seconds', u'Minutes', u'Hours', u'Watts', u'Volts', u'Percent'] k_eventServerBindHost = u"0.0.0.0" k_eventServerListenBacklog = 5 k_eventServerMsgMaxLength = 128 + 16 + 1 # device name + event name + separator k_eventServerSeparator = u":" k_eventServerEvents = ['annoyme', 'battattach', 'battdetach', 'changeme', 'commfailure', 'commok', 'doreboot', 'doshutdown', 'emergency', 'endselftest', 'failing', 'killpower', 'loadlimit', 'mainsback', 'offbattery', 'onbattery', 'powerout', 'readApcupsd', 'remotedown', 'runlimit', 'startselftest', 'timeout'] k_eventServerClientSeparator = u"," k_localhostName = u"localhost" k_localhostAddress = u"127.0.0.1" # default preference values used if the plugin hasn't been configured k_apcupsdTimeoutDefault = 8 k_apcupsdFrequencyDefault = 5 k_useIpConnDefault = False k_useIpConnAccessDefault = k_localhostAddress k_daysBetweenUpdateChecksDefault = 1 k_overridePathDefault = False k_utilityPathDefault = u"" k_removeUnitsDefault = True k_showDebugInfo1Default = 1 # Increment this each time Device.xml changes / adds / deletes ANY device properties / state NAMES k_deviceUpdateVersion = 1 def startEventServer(self, port): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.serverRun = True socket.setdefaulttimeout(self.apcupsdTimeout) self.s = threading.Thread(target=eventServer, args=[self, k_eventServerBindHost, port]) self.s.daemon = True self.s.start() self.sleep(5) if self.s.isAlive(): self.log.log(2, dbFlg, u"Event notification server started", self.logName) self.log.log(2, dbFlg, u"%s: completed" % (funcName), self.logName) return True else: self.log.logError(u"Event notification server failed to start", self.logName) self.log.log(2, dbFlg, u"%s: completed" % (funcName), self.logName) return False def stopEventServer(self): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.serverRun = False if hasattr(self, "s"): self.log.log(2, dbFlg, u"Event notifications server asked to stop", self.logName) self.s.join(10) cnt = 0 while cnt < (self.apcupsdTimeout + 10) and self.s.isAlive(): self.sleep(1) cnt = cnt + 1 self.log.log(3, dbFlg, u"%s: Event notifications server needed %s delays to stop" % (funcName, cnt), self.logName) self.log.log(2, dbFlg, u"%s: completed" % (funcName), self.logName) return def eventServer(self, host, port): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(3, dbFlg, u"%s: received address: %s and port: %s" % (funcName, host, port), self.logName) try: server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind((host, port)) server.listen(k_eventServerListenBacklog) except Exception as e: e1 = sys.exc_info()[0] self.log.logError(u"%s: problem with socket: %s & %s" % (funcName, e, e1), self.logName) return self.log.log(2, dbFlg, u"%s: started listening on %s" % (funcName, server.getsockname()), self.logName) while self.serverRun: try: self.log.log(4, dbFlg, u"%s: waiting for a connection" % (funcName), self.logName) client, client_address = server.accept() self.log.log(3, dbFlg, u"%s: client connected from address: %s port: %s" % (funcName, client_address[0], client_address[1]), self.logName) if client_address[0] in self.useIpConnAccess: data = client.recv(k_eventServerMsgMaxLength) if data: self.log.log(3, dbFlg, u"%s: received %s" % (funcName, data), self.logName) self.buildAction(data) else: self.log.logError(u"%s: unauthorized client attempted access from: address: %s port: %s" % (funcName, client_address[0], client_address[1]), self.logName) client.close() except socket.timeout: pass except Exception as e: e1 = sys.exc_info()[0] self.log.logError(u"%s: read loop: Errors %s & %s" % (funcName, e, e1), self.logName) pass self.log.log(2, dbFlg, u"%s: Event notification server closed" % (funcName), self.logName) ######################################## def findInPath(self, file_name, def_path=os.defpath): funcName = inspect.stack()[0][3] dbFlg = False path = os.getenv('PATH', def_path) self.log.log(2, dbFlg, u"%s: PATH to search: %s" % (funcName, path), self.logName) for d in path.split(os.pathsep): file_path = os.path.abspath(os.path.join(d, file_name)) if os.path.exists(file_path): self.log.log(2, dbFlg, u"%s: found %s" % (funcName, file_path), self.logName) return file_path self.log.log(2, dbFlg, u"%s: %s not found in PATH" % (funcName, file_name), self.logName) return file_name ######################################## def doShell(self, cmd): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s: Called" % (funcName), self.logName) self.log.log(3, dbFlg, u"%s: command: %s" % (funcName, cmd), self.logName) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = p.communicate() self.log.log(3, dbFlg, u"%s: returned output\n%s" % (funcName, out), self.logName) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return (p.returncode, out) ################################################################################ # delayAmount : 900 # description : plugin action # * deviceId : 145579207 # pluginId : <ourPluginId> # * pluginTypeId : apcupsdServerEvent # * props : <ourPluginId> : (dict) # actionType : commok (string) # replaceExisting : True # textToSpeak : class Action(object): def __init__(self): self.description = u'plugin generated action' self.deviceId = 0 self.pluginTypeId = None self.props = {'actionType': None} def __str__(self): desc_str = u"description: %s\ndeviceId: %s \npluginId: %s \npluginTypeId: %s \n props: %s \n" %(self.description, self.deviceId, self.pluginId, self.pluginTypeId, self.props) return desc_str ################################################################################ ################################################################################ class Plugin(indigo.PluginBase): ######################################## # Class properties ######################################## def __init__(self, pluginid, pluginDisplayName, pluginVersion, pluginPrefs): indigo.PluginBase.__init__(self, pluginid, pluginDisplayName, pluginVersion, pluginPrefs) self.log = logger(self) self.logName = pluginDisplayName funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) try: self.apcupsdTimeout = string.atof(self.pluginPrefs["apcupsdTimeout"]) except KeyError: self.apcupsdTimeout = k_apcupsdTimeoutDefault self.log.logError(u"The apcupsd plugin appears to have not been configured. Default values will be used until the configuration is changed.", self.logName) self.apcupsdFrequency = string.atof(self.pluginPrefs.get("apcupsdFrequency", k_apcupsdFrequencyDefault)) self.useIpConn = self.pluginPrefs.get("useIpConn", k_useIpConnDefault) if self.useIpConn: self.useIpConnAccess = self.pluginPrefs.get("useIpConnAccess", k_useIpConnAccessDefault).split(k_eventServerClientSeparator) self.log.log(2, dbFlg, u"%s: read access list: %s" % (funcName, self.useIpConnAccess), self.logName) self.pluginid = pluginid self.pluginDisplayName = pluginDisplayName self.apcupsdCommError = False self.triggerList = [] self.triggerDict = {} self.defaultStatesDict = eval(open("../Resources/defaultStates.dict").read()) self.commLostStatesList = eval(open("../Resources/commLostStates.List").read()) self.serverRun = True self.readLoop = True self.startingUp = True # setup the plugin update checker... it will be disabled if the URL is empty self.updater = GitHubPluginUpdater(self) daysBetweenUpdateChecks = string.atof(self.pluginPrefs.get("daysBetweenUpdateChecks", k_daysBetweenUpdateChecksDefault)) self.secondsBetweenUpdateChecks = daysBetweenUpdateChecks * 86400 self.nextUpdateCheck = 0 # this will force an update check as soon as the plugin is running self.utilityBinaryName = k_utilityBinaryName utilityBinaryPath = k_utilityBinaryPath if self.pluginPrefs.get("overridePath", k_overridePathDefault) and self.pluginPrefs.get("utilityPath", k_utilityPathDefault) != "": utilityBinaryPath = self.pluginPrefs["utilityPath"] self.utilityBinary = findInPath(self, self.utilityBinaryName, utilityBinaryPath) if self.utilityBinaryName != self.utilityBinary: self.utilityBinaryFound = True else: self.utilityBinaryFound = False self.log.logError(u"Could not find the '%s' binary. Is the APCUPSD package installed?" % (self.utilityBinaryName), self.logName) self.removeUnits = self.pluginPrefs.get("removeUnits", k_removeUnitsDefault) self.logLevel = self.pluginPrefs.get("showDebugInfo1", k_showDebugInfo1Default) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) ######################################## def __del__(self): indigo.PluginBase.__del__(self) ######################################## def startup(self): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(1, dbFlg, u"%s: Plugin Starting" % (funcName), self.logName) self.log.log(2, dbFlg, u"%s: completed" % (funcName), self.logName) ######################################## def closedPrefsConfigUi (self, valuesDict, UserCancelled): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(4, dbFlg, u"%s:\nvaluesDict:\n%s\nUserCancelled: %s" % (funcName, valuesDict, UserCancelled), self.logName) if UserCancelled is False: self.log = logger(self) self.apcupsdFrequency = string.atof(valuesDict["apcupsdFrequency"]) lastUseIpConn = self.useIpConn self.useIpConn = valuesDict["useIpConn"] if self.useIpConn: self.apcupsdTimeout = string.atof(valuesDict["apcupsdTimeout"]) self.useIpConnAccess = valuesDict["useIpConnAccess"].split(k_eventServerClientSeparator) self.log.log(2, dbFlg, u"%s: read access list: %s" % (funcName, self.useIpConnAccess), self.logName) if lastUseIpConn: self.log.log(2, dbFlg, u"Event notifications server asked to stop", self.logName) # because we may have new preferences to put into play, ask any currently running server to stop what its doing stopEventServer(self) port = int(valuesDict["useIpConnPort"]) startEventServer(self, port) else: # since we don't need a server now, ask any currently running server to stop what its doing stopEventServer(self) daysBetweenUpdateChecks = string.atoi(valuesDict["daysBetweenUpdateChecks"]) self.secondsBetweenUpdateChecks = daysBetweenUpdateChecks * 86400 self.nextUpdateCheck = 0 # this will force an update check starting now self.logLevel = string.atoi(valuesDict["showDebugInfo1"]) if valuesDict["overridePath"] and valuesDict["utilityPath"] != "": utilityBinaryPath = valuesDict["utilityPath"] utilityBinary = findInPath(self, self.utilityBinaryName, utilityBinaryPath) if self.utilityBinaryName != utilityBinary: self.utilityBinaryPath = utilityBinary self.log.log(1, dbFlg, u"Plugin options reset. Polling apcupsd servers every %s minutes and a debug level of %i" % (self.apcupsdFrequency, int(valuesDict["showDebugInfo1"])), self.logName) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) ######################################## # this is also called by the custom menu item ######################################## def checkForUpdates(self): update = self.updater.getLatestRelease() if update == None: self.log.logError(u"Error encountered checking for a new plugin version", self.logName) else: update = self.updater.checkForUpdate() ######################################## def runConcurrentThread(self): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.startingUp = False if self.utilityBinaryFound is False: self.log.log(2, dbFlg, u"%s: A missing '%s' binary will NOT clear itself without changing the plugin preferences and/or installing the APCUPSD package, then reloading the plugin." % (funcName, self.utilityBinaryName), self.logName) self.sleep(60*10) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return if self.useIpConn: port = int(self.pluginPrefs["useIpConnPort"]) startEventServer(self, port) try: self.log.log(1, dbFlg, u"Plugin started. Polling apcupsd server(s) every %s minutes" % (self.apcupsdFrequency), self.logName) except AttributeError: self.log.logError(u"Plugin start delayed pending completion of initial plugin configuration", self.logName) return try: while True: self.readLoop = True if self.secondsBetweenUpdateChecks > 0: # obtain the current date/time and determine if it is after the previously-calculated # next check run timeNow = time.time() if timeNow > self.nextUpdateCheck: self.pluginPrefs['updaterLastCheck'] = timeNow self.log.log(3, dbFlg, u"# of seconds between update checks: %s" % (int(self.secondsBetweenUpdateChecks)), self.logName) self.nextUpdateCheck = timeNow + self.secondsBetweenUpdateChecks # use the updater to check for an update now self.checkForUpdates() devCount = 0 for dev in indigo.devices.iter(self.pluginId): if dev.enabled: devCount += 1 self.log.log(2, dbFlg, u"%s: Got device %s from Indigo" % (funcName, dev.name), self.logName) self.readApcupsd(dev) self.log.log(3, dbFlg, u"%s: Read device %s" % (funcName, dev.name), self.logName) if devCount == 0 and self.logLevel > 0: self.log.log(2, dbFlg, u"%s: Completed device poll. No enabled devices found" % (funcName), self.logName) else: if devCount == 1: devWord = u"device" else: devWord = u"devices" self.log.log(2, dbFlg, u"%s: Completed device poll. %s %s found" % (funcName, devCount, devWord), self.logName) # we sleep (apcupsdFrequency minutes) between reads - in 1 sec increments so we can be interupted by self.readLoop changing count = 0 while count < self.apcupsdFrequency * 60 and self.readLoop: self.sleep(1) count +=1 except self.StopThread: self.log.log(2, dbFlg, u"%s: StopThread is now True" % (funcName), self.logName) stopEventServer(self) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) ######################################## def readApcupsd(self, dev, parseOnly=False, tmpProps=False): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(4, dbFlg, u"%s: Received device:\n%s\n" % (funcName, unicode(dev)), self.logName) if tmpProps is False: try: sAddress = dev.pluginProps["apcupsdAddress"] except KeyError: self.log.logError(u"%s: Trying to get status for a device that is not configured" % (funcName), self.logName) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return False sPort = dev.pluginProps["apcupsdPort"] else: sAddress = tmpProps["apcupsdAddress"] sPort = tmpProps["apcupsdPort"] self.log.log(4, dbFlg, u"%s: doing '%s status' for address %s on port %s" % (funcName, self.utilityBinary, sAddress, sPort), self.logName) apcupsdSuccess = False apcupsdRetries = 0 while not apcupsdSuccess and apcupsdRetries < 5: if apcupsdRetries == 0: self.log.log(3, dbFlg, u"%s: starting read. Retries=%s" % (funcName, apcupsdRetries), self.logName) else: self.log.log(2, dbFlg, u"%s: starting read. Retries=%s" % (funcName, apcupsdRetries), self.logName) apcupsdRetries = apcupsdRetries + 1 result, report = doShell(self, k_utilityCommand(binary=self.utilityBinary, address=sAddress, port=sPort)) if result: self.log.logError(u"%s: Connection to %s failed with error code %s. Attempt %s of 5" % (funcName, self.utilityBinary, result, apcupsdRetries), self.logName) self.log.logError(u"%s: Returned output: %s" % (funcName, report), self.logName) apcupsdSuccess = False self.sleep(1) else: self.log.log(4, dbFlg, u"%s: report\n%s" % (funcName, report), self.logName) metrics = {} for line in report.split('\n'): (key,spl,val) = line.partition(k_utilityOutputSeparator) # if the key contains any spaces, they would be unable to be specified in Devices.XML as field Ids so replace now key = key.rstrip().lower().replace(' ', k_utilityOutputSpaceReplacement) val = val.strip() if self.removeUnits is True: test = val.split() if len(test) >= 2: unit = test[1] # is there a "units" keyword here? if unit in k_utilityOutputUnitWords: val = test[0] # ignore anything after 1st space if key != '': metrics[key] = val self.log.log(4, dbFlg, u"%s: parsed key=%s and val=%s" % (funcName, key, val), self.logName) if 'status' in metrics: apcupsdSuccess = True if parseOnly: self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return (True, metrics) if metrics['status'] == 'COMMLOST' and not self.apcupsdCommError: dev.setErrorStateOnServer(u'lost comm') self.apcupsdCommError = True for state in dev.states: try: dev.updateStateOnServer(key=state, value='n/a', clearErrorState=False) except: dev.updateStateOnServer(key=state, value='n/a') self.log.log(2, dbFlg, u"%s: changing state for: %s to n/a" % (funcName, state), self.logName) self.log.log(3, dbFlg, u"%s: COMMLOST" % (funcName), self.logName) elif metrics['status'] != 'COMMLOST' and self.apcupsdCommError: dev.setErrorStateOnServer(None) self.apcupsdCommError = False self.log.log(3, dbFlg, u"%s: ONLINE" % (funcName), self.logName) else: self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return (False, metrics) if apcupsdSuccess: for metric in metrics: value = metrics[metric] try: if metric in dev.states: self.log.log(4, dbFlg, u"%s: found metric: %s " % (funcName, metric), self.logName) if self.apcupsdCommError: if metric in self.commLostStatesList: self.log.log(3, dbFlg, u"%s: found commLostStates: %s in list:%s" % (funcName, metric, self.commLostStatesList), self.logName) try: dev.updateStateOnServer(key=metric, value=value + ' *', clearErrorState=False) except: dev.updateStateOnServer(key=metric, value=value + ' *') else: pass else: try: dev.updateStateOnServer(key=metric, value=value, clearErrorState=False) except: dev.updateStateOnServer(key=metric, value=value) self.log.log(4, dbFlg, u"%s: metric:%s, val:%s, is Error:%s" % (funcName, metric, value, self.apcupsdCommError), self.logName) except Exception as e: self.log.logError(u"%s: error writing device state" % (funcName), self.logName) e1 = sys.exc_info()[0] self.log.logError(u"%s: Errors %s and %s" % (funcName, e, e1), self.logName) self.log.log(2, dbFlg, u"%s: Completed readings update from device: %s" % (funcName, dev.name), self.logName) else: self.log.logError(u"%s: Failed to get status for UPS %s after %s tries. Will retry in %s minutes" % (funcName, dev.name, apcupsdRetries, self.apcupsdFrequency), self.logName) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) ######################################## # Device start, stop, modify and delete ######################################## def deviceStartComm(self, dev): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called for device %s" % (funcName, dev.name), self.logName) madeChanges = False tmpProps = dev.pluginProps deviceVersion = int(tmpProps.get('version', 0)) if deviceVersion < 1: madeChanges = True # check to see if we have any of the older, misspelled property names and change to the correct ones if we do try: tmp = tmpProps['apcupsdDevceStateDisplay'] tmpProps['apcupsdDeviceStateDisplay'] = tmp del tmpProps['apcupsdDevceStateDisplay'] except KeyError: pass try: tmp = tmpProps['apcupsdstatealarmdel'] tmpProps['apcupsdStateALARMDEL'] = tmp del tmpProps['apcupsdstatealarmdel'] except KeyError: pass # continue with testing deviceVersion < 2, etc. as needed # and if we have any "forced" updates to made regardless of versions (usually only seen in development)... # try: # del tmpProps['apcupsdstatealarmdel'] # madeChanges = True # except KeyError: # pass if madeChanges is True: self.log.log(1, dbFlg, u"%s: Device %s updated to version %s" % (funcName, dev.name, k_deviceUpdateVersion), self.logName) tmpProps['version'] = k_deviceUpdateVersion dev.replacePluginPropsOnServer(tmpProps) if dev.enabled and not self.startingUp: self.log.log(2, dbFlg, u"%s: Resetting read loop to include device %s" % (funcName, dev.name), self.logName) self.readLoop = False self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) ######################################## def deviceStopComm(self, dev): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called for device %s" % (funcName, dev.name), self.logName) self.log.log(2, dbFlg, u"%s: Resetting read loop to drop device %s" % (funcName, dev.name), self.logName) self.readLoop = False self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) ######################################## def didDeviceCommPropertyChange(self, origDev, newDev): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called for device %s" % (funcName, origDev.name), self.logName) self.log.log(4, dbFlg, u"%s: origDev:\n%s\n\nnewDev:\n%s\n" % (funcName, origDev, newDev), self.logName) if (origDev.pluginProps != newDev.pluginProps): self.log.log(2, dbFlg, u"%s: Resetting read loop to include device %s" % (funcName, newDev.name), self.logName) self.readLoop = False self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return False # Don't bother callng devStartComm or devStopComm, we took care of restarting the read loop already ######################################## def deviceDeleted(self, dev): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called for device %s" % (funcName, dev.name), self.logName) self.log.log(2, dbFlg, u"%s: Resetting read loop to drop device %s" % (funcName, dev.name), self.logName) self.readLoop = False self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) ######################################## # Indigo Event Triggers: Start, Stop and Fre # ######################################## def triggerStartProcessing(self, trigger): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called for trigger %s" % (funcName, trigger.name), self.logName) self.log.log(4, dbFlg, u"%s: Received trigger:%s" % (funcName, trigger), self.logName) self.triggerList.append(trigger.id) # indigoDev = indigo.devices[int(trigger.pluginProps["indigoDevice"])] self.triggerDict[trigger.id] = trigger.pluginProps["indigoDevice"] # self.triggerDict[indigoDev.name] = trigger.pluginProps["indigoDevice"] ## Can't do ths. Two different keys in the same dict. # self.triggerDict["indigoDevice"] = indigoDev.name self.log.log(2, dbFlg, u"%s trigger %s started" % (funcName, trigger.name), self.logName) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) ######################################## def triggerStopProcessing(self, trigger): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called for trigger %s" % (funcName, trigger.name), self.logName) self.log.log(4, dbFlg, u"%s: Received trigger:%s" % (funcName, trigger), self.logName) if trigger.id in self.triggerDict: self.log.log(2, dbFlg, u"%s trigger %s found" % (funcName, trigger.name), self.logName) del self.triggerDict[trigger.id] self.log.log(2, dbFlg, u"%s trigger %s deleted" % (funcName, trigger.name), self.logName) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) ######################################## #def triggerUpdated(self, origDev, newDev): # self.log.log(4, u"<<-- entering triggerUpdated: %s" % origDev.name) # self.triggerStopProcessing(origDev) # self.triggerStartProcessing(newDev) ######################################## def triggerEvent(self, eventId, devId): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(3, dbFlg, u"%s: received trigger %s for device %s" % (funcName, eventId, devId), self.logName) try: for trigId in self.triggerDict: self.log.log(3, dbFlg, u"%s: found trigger ID %s" % (funcName, trigId), self.logName) trigger = indigo.triggers[trigId] self.log.log(3, dbFlg, u"%s: found trigger %s" % (funcName, trigger), self.logName) device = self.triggerDict[trigId] if trigger.pluginTypeId == eventId and trigger.pluginProps['indigoDevice'] == device: self.log.log(2, dbFlg, u"%s: matched trigger ID %s" % (funcName, trigId), self.logName) indigo.trigger.execute(trigger.id) except Exception as e: e1 = sys.exc_info()[0] self.log.logError(u"%s: Errors %s and %s" % (funcName, e, e1), self.logName) pass self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return ######################################## # Action callbacks # ######################################## def buildAction(self, event): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) try: devid, event = event.split(k_eventServerSeparator) self.log.log(3, dbFlg, u"%s: Received event %s for device %s" % (funcName, event, devid), self.logName) except ValueError: self.log.logError(u"%s: Received incorrectly formatted event %s, should be DEVNAME_OR_ID%sEVENTTYPE" % (funcName, event, k_eventServerSeparator), self.logName) return if event in k_eventServerEvents: self.log.log(3, dbFlg, u"%s: Validated event %s for device %s" % (funcName, event, devid), self.logName) else: self.log.logError(u"%s: Received bad event type %s for device %s" % (funcName, event, devid), self.logName) return if devid.isdigit(): # the following device lookup is based upon the variable's type so we must convert from str to int now devid = int(devid) try: dev = indigo.devices[devid] except KeyError: self.log.logError(u"%s: Unrecognized device name or ID %s for event %s" % (funcName, devid, event), self.logName) return # check now to see if specified device is really a device created by this plugin... if dev.pluginId != self.pluginId: self.log.logError(u"%s: Device name or ID %s is not associated with this plugin for event %s" % (funcName, devid, event), self.logName) return action = Action() action.pluginId = self.pluginId action.deviceId = dev.id action.props['actionType'] = event self.log.log(4, dbFlg, u"%s: built action: \n%s and retrieved dev: \n%s" % (funcName, action, dev), self.logName) self.actionControlApcupsd(action, dev) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) ######################################## def actionControlApcupsd(self, action, dev): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(2, dbFlg, u"%s: Entered for dev: %s, and action: %s" % (funcName, dev.name, action.description), self.logName) self.log.log(4, dbFlg, u"%s: Received action: \n%s\n and dev:\n%s" % (funcName, action, dev), self.logName) deviceId = int(action.deviceId) # Makes it easier to pass in our own events # All we have to do for these actons is read from the server... we will get updated states and do the right thing automatically try: apcupsdAction = action.props['actionType'] except KeyError: apcupsdAction = '' self.log.log(2, dbFlg, u"%s: found deviceId=%s, actionType=%s" % (funcName, action.deviceId, apcupsdAction), self.logName) if action.pluginTypeId == 'readApcupsd': self.readApcupsd(dev) elif action.pluginTypeId == 'logStatusReport': sAddress = indigo.devices[int(action.deviceId)].pluginProps["apcupsdAddress"] sPort = indigo.devices[int(action.deviceId)].pluginProps["apcupsdPort"] self.log.log(4, dbFlg, u"%s: doing '%s status' for address %s on port %s" % (funcName, self.utilityBinary, sAddress, sPort), self.logName) result, report = doShell(self, k_utilityCommand(binary=self.utilityBinary, address=sAddress, port=sPort)) self.log.log(0, dbFlg, u"\n\nFull APCUPSD Status report for %s:\n%s" % (indigo.devices[int(action.deviceId)].name, report), self.logName) elif apcupsdAction == 'commfailure': dev.setErrorStateOnServer(u'lost comm') self.triggerEvent(u'commfailure', deviceId) # self.apcupsdCommError = True ## we'll try letting readApcupsd manage this self.readApcupsd(dev) elif apcupsdAction == 'commok': dev.setErrorStateOnServer(None) self.triggerEvent(u'commok', dev.id) self.apcupsdCommError = True self.readApcupsd(dev) elif apcupsdAction == 'annoyme': self.triggerEvent(u'annoyme', deviceId) elif apcupsdAction == 'battattach': self.triggerEvent(u'battattach', deviceId) elif apcupsdAction == 'battdetach': self.triggerEvent(u'battdetach', deviceId) elif apcupsdAction == 'changeme': self.triggerEvent(u'changeme', deviceId) elif apcupsdAction == 'doreboot': self.triggerEvent(u'doreboot', deviceId) elif apcupsdAction == 'doshutdown': self.triggerEvent(u'doshutdown', deviceId) elif apcupsdAction == 'emergency': self.triggerEvent(u'emergency', deviceId) elif apcupsdAction == 'endselftest': self.triggerEvent(u'endselftest', deviceId) elif apcupsdAction == 'failing': self.triggerEvent(u'failing', deviceId) elif apcupsdAction == 'killpower': self.triggerEvent(u'killpower', deviceId) elif apcupsdAction == 'loadlimit': self.triggerEvent(u'loadlimit', deviceId) elif apcupsdAction == 'mainsback': self.triggerEvent(u'mainsback', deviceId) elif apcupsdAction == 'offbattery': self.triggerEvent(u'offbattery', deviceId) elif apcupsdAction == 'onbattery': self.triggerEvent(u'onbattery', deviceId) elif apcupsdAction == 'powerout': self.triggerEvent(u'powerout', deviceId) elif apcupsdAction == 'remotedown': self.triggerEvent(u'remotedown', deviceId) elif apcupsdAction == 'runlimit': self.triggerEvent(u'runlimit', deviceId) elif apcupsdAction == 'startselftest': self.triggerEvent(u'startselftest', deviceId) elif apcupsdAction == 'timeout': self.triggerEvent(u'timeout', deviceId) elif apcupsdAction == 'readApcupsd': self.readApcupsd(dev) else: self.log.logError(u"%s: unknown action %s requested" % (funcName, apcupsdAction), self.logName) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return ######################################## # UI Support ######################################## ######################################## # Button handlers def selectAllStates(self, valuesDict, typeId, devId): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(4, dbFlg, u"%s: received:\n>>valuesDict\n%s\n>>typeId\n%s\n>>devId\n%s\n" % (funcName, valuesDict, typeId, devId), self.logName) for key in valuesDict: if key.find('apcupsdState') != -1: valuesDict[key] = True self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return(valuesDict) ######################################## def deSelectAllStates(self, valuesDict, typeId, devId): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(4, dbFlg, u"%s: received:\n>>valuesDict\n%s\n>>typeId\n%s\n>>devId\n%s\n" % (funcName, valuesDict, typeId, devId), self.logName) for key in valuesDict: if key.find('apcupsdState') != -1: valuesDict[key] = False self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return(valuesDict) ######################################## def selectDefaultStates(self, valuesDict, typeId, devId): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(4, dbFlg, u"%s: received:\n>>valuesDict\n%s\n>>typeId\n%s\n>>devId\n%s\n" % (funcName, valuesDict, typeId, devId), self.logName) for key in valuesDict: if key.find('apcupsdState') != -1: try: defaultState = self.defaultStatesDict[key] self.log.log(3, dbFlg, u"%s: using '%s' default of %s" % (funcName, key, self.defaultStatesDict[key]), self.logName) except KeyError: self.log.log(3, dbFlg, u"%s: missing entry '%s' in defaultStates.dict, defaulting to False" % (funcName, key), self.logName) defaultsState = False valuesDict[key] = defaultState self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return(valuesDict) ######################################## def selectQueryDevice(self, valuesDict, typeId, devId): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(4, dbFlg, u"%s: received:\n>>valuesDict\n%s\n>>typeId\n%s\n>>devId\n%s\n" % (funcName, valuesDict, typeId, devId), self.logName) for key in valuesDict: if key.find('apcupsdState') != -1: valuesDict[key] = False tmpProps = indigo.Dict() tmpProps['apcupsdAddress'] = valuesDict['apcupsdAddress'] if valuesDict['apcupsdAddressType'] == k_localhostName or tmpProps['apcupsdAddress'] == "": tmpProps['apcupsdAddress'] = k_localhostAddress tmpProps['apcupsdPort'] = valuesDict['apcupsdPort'] self.log.log(4, dbFlg, u"%s: temporary properties for new device\n%s\n" % (funcName, tmpProps), self.logName) (returnStatus, metrics) = self.readApcupsd(0, True, tmpProps) if returnStatus == True: self.log.log(4, dbFlg, u"%s: returned\n>>device values\n%s\n" % (funcName, metrics), self.logName) for metric in metrics: key = "apcupsdState" + metric.upper() try: if key in valuesDict: self.log.log(3, dbFlg, u"%s: found matching state: %s" % (funcName, metric), self.logName) valuesDict[key] = True except: pass else: self.log.log(1, dbFlg, u"%s: Cannot determine which states the device might provide" % (funcName), self.logName) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return(valuesDict) ######################################## # editing of props def getDeviceDisplayStateId(self, dev): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(4, dbFlg, u"%s: received device:\n%s\n" % (funcName, unicode(dev)), self.logName) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) try: return dev.pluginProps['apcupsdDeviceStateDisplay'] except KeyError: return None ######################################## def getDeviceStateList(self, dev): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(4, dbFlg, u"%s: received device:\n%s\n" % (funcName, unicode(dev)), self.logName) statesList = [] stateKey = 'status' stateDict = {'Disabled': False, 'Key': stateKey, 'StateLabel': stateKey, 'TriggerLabel': stateKey, 'Type': 100} statesList.append(stateDict) for key in dev.pluginProps: if key.find('apcupsdState') != -1: if dev.pluginProps[key]: stateKey = key[12:].lower() stateDict = {'Disabled': False, 'Key': stateKey, 'StateLabel': stateKey, 'TriggerLabel': stateKey, 'Type': 100} statesList.append(stateDict) self.log.log(4, dbFlg, u"%s: %s added as state" % (funcName, key[12:]), self.logName) else: self.log.log(4, dbFlg, u"%s: %s property is not a state" % (funcName, key[12:]), self.logName) self.log.log(3, dbFlg, u"%s: returning statesList: %s" % (funcName, statesList), self.logName) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return(statesList) ######################################## # UI validation for devices def validateDeviceConfigUi(self, valuesDict, typeId, devId): funcName = inspect.stack()[0][3] dbFlg = False self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(4, dbFlg, u"%s: received:\n>>valuesDict\n%s\n>>typeId\n%s\n>>devId\n%s\n" % (funcName, valuesDict, typeId, devId), self.logName) if valuesDict['apcupsdAddressType'] == k_localhostName or valuesDict['apcupsdAddress'] == '': valuesDict['apcupsdAddress'] = k_localhostAddress self.log.log(4, dbFlg, u"%s: returned:\n>>valuesDict\n%s\n" % (funcName, valuesDict), self.logName) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) return (True, valuesDict) ######################################## # UI validation for the plugin configuration def validatePrefsConfigUi(self, valuesDict): funcName = inspect.stack()[0][3] dbFlg = False validationErr = False errorDict = indigo.Dict() self.log.log(2, dbFlg, u"%s called" % (funcName), self.logName) self.log.log(4, dbFlg, u"%s: received:\n>>valuesDict\n%s\n" % (funcName, valuesDict), self.logName) if valuesDict["overridePath"] and valuesDict["utilityPath"] != "": utilityBinaryPath = valuesDict["utilityPath"] utilityBinary = findInPath(self, self.utilityBinaryName, utilityBinaryPath) if self.utilityBinaryName == utilityBinary: validationErr = True errorDict["utilityPath"] = u"'%s' utility not found in this path" % (self.utilityBinaryName) errorDict["showAlertText"] = u"You must specify the UNIX-style path to the '%s' binary." % (self.utilityBinaryName) if valuesDict["useIpConn"] is True and (valuesDict["useIpConnAccess"] == "" or valuesDict["useIpConnAccess"].find(" ") != -1): validationErr = True errorDict["useIpConnAccess"] = u"Must not contain spaces between entries or be empty" errorDict["showAlertText"] = u"One or more IP addresses should be entered, separated by only a comma. Don't forget 127.0.0.1." self.log.log(4, dbFlg, u"%s: returned:\n>>valuesDict\n%s\n" % (funcName, valuesDict), self.logName) self.log.log(2, dbFlg, u"%s: Completed" % (funcName), self.logName) if validationErr is False: return (True, valuesDict) else: return (False, valuesDict, errorDict)
pyshell.py
#! /usr/bin/env python3 import sys if __name__ == "__main__": sys.modules['idlelib.pyshell'] = sys.modules['__main__'] try: from tkinter import * except ImportError: print("** IDLE can't import Tkinter.\n" "Your Python may not be configured for Tk. **", file=sys.__stderr__) raise SystemExit(1) # Valid arguments for the ...Awareness call below are defined in the following. # https://msdn.microsoft.com/en-us/library/windows/desktop/dn280512(v=vs.85).aspx if sys.platform == 'win32': try: import ctypes PROCESS_SYSTEM_DPI_AWARE = 1 # Int required. ctypes.OleDLL('shcore').SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE) except (ImportError, AttributeError, OSError): pass from tkinter import messagebox if TkVersion < 8.5: root = Tk() # otherwise create root in main root.withdraw() from idlelib.run import fix_scaling fix_scaling(root) messagebox.showerror("Idle Cannot Start", "Idle requires tcl/tk 8.5+, not %s." % TkVersion, parent=root) raise SystemExit(1) from code import InteractiveInterpreter import linecache import os import os.path from platform import python_version import re import socket import subprocess from textwrap import TextWrapper import threading import time import tokenize import warnings from idlelib.colorizer import ColorDelegator from idlelib.config import idleConf from idlelib.delegator import Delegator from idlelib import debugger from idlelib import debugger_r from idlelib.editor import EditorWindow, fixwordbreaks from idlelib.filelist import FileList from idlelib.outwin import OutputWindow from idlelib import replace from idlelib import rpc from idlelib.run import idle_formatwarning, StdInputFile, StdOutputFile from idlelib.undo import UndoDelegator # Default for testing; defaults to True in main() for running. use_subprocess = False HOST = '127.0.0.1' # python execution server on localhost loopback PORT = 0 # someday pass in host, port for remote debug capability # Override warnings module to write to warning_stream. Initialize to send IDLE # internal warnings to the console. ScriptBinding.check_syntax() will # temporarily redirect the stream to the shell window to display warnings when # checking user's code. warning_stream = sys.__stderr__ # None, at least on Windows, if no console. def idle_showwarning( message, category, filename, lineno, file=None, line=None): """Show Idle-format warning (after replacing warnings.showwarning). The differences are the formatter called, the file=None replacement, which can be None, the capture of the consequence AttributeError, and the output of a hard-coded prompt. """ if file is None: file = warning_stream try: file.write(idle_formatwarning( message, category, filename, lineno, line=line)) file.write(">>> ") except (AttributeError, OSError): pass # if file (probably __stderr__) is invalid, skip warning. _warnings_showwarning = None def capture_warnings(capture): "Replace warning.showwarning with idle_showwarning, or reverse." global _warnings_showwarning if capture: if _warnings_showwarning is None: _warnings_showwarning = warnings.showwarning warnings.showwarning = idle_showwarning else: if _warnings_showwarning is not None: warnings.showwarning = _warnings_showwarning _warnings_showwarning = None capture_warnings(True) def extended_linecache_checkcache(filename=None, orig_checkcache=linecache.checkcache): """Extend linecache.checkcache to preserve the <pyshell#...> entries Rather than repeating the linecache code, patch it to save the <pyshell#...> entries, call the original linecache.checkcache() (skipping them), and then restore the saved entries. orig_checkcache is bound at definition time to the original method, allowing it to be patched. """ cache = linecache.cache save = {} for key in list(cache): if key[:1] + key[-1:] == '<>': save[key] = cache.pop(key) orig_checkcache(filename) cache.update(save) # Patch linecache.checkcache(): linecache.checkcache = extended_linecache_checkcache class PyShellEditorWindow(EditorWindow): "Regular text edit window in IDLE, supports breakpoints" def __init__(self, *args): self.breakpoints = [] EditorWindow.__init__(self, *args) self.text.bind("<<set-breakpoint-here>>", self.set_breakpoint_here) self.text.bind("<<clear-breakpoint-here>>", self.clear_breakpoint_here) self.text.bind("<<open-python-shell>>", self.flist.open_shell) #TODO: don't read/write this from/to .idlerc when testing self.breakpointPath = os.path.join( idleConf.userdir, 'breakpoints.lst') # whenever a file is changed, restore breakpoints def filename_changed_hook(old_hook=self.io.filename_change_hook, self=self): self.restore_file_breaks() old_hook() self.io.set_filename_change_hook(filename_changed_hook) if self.io.filename: self.restore_file_breaks() self.color_breakpoint_text() rmenu_specs = [ ("Cut", "<<cut>>", "rmenu_check_cut"), ("Copy", "<<copy>>", "rmenu_check_copy"), ("Paste", "<<paste>>", "rmenu_check_paste"), (None, None, None), ("Set Breakpoint", "<<set-breakpoint-here>>", None), ("Clear Breakpoint", "<<clear-breakpoint-here>>", None) ] def color_breakpoint_text(self, color=True): "Turn colorizing of breakpoint text on or off" if self.io is None: # possible due to update in restore_file_breaks return if color: theme = idleConf.CurrentTheme() cfg = idleConf.GetHighlight(theme, "break") else: cfg = {'foreground': '', 'background': ''} self.text.tag_config('BREAK', cfg) def set_breakpoint(self, lineno): text = self.text filename = self.io.filename text.tag_add("BREAK", "%d.0" % lineno, "%d.0" % (lineno+1)) try: self.breakpoints.index(lineno) except ValueError: # only add if missing, i.e. do once self.breakpoints.append(lineno) try: # update the subprocess debugger debug = self.flist.pyshell.interp.debugger debug.set_breakpoint_here(filename, lineno) except: # but debugger may not be active right now.... pass def set_breakpoint_here(self, event=None): text = self.text filename = self.io.filename if not filename: text.bell() return lineno = int(float(text.index("insert"))) self.set_breakpoint(lineno) def clear_breakpoint_here(self, event=None): text = self.text filename = self.io.filename if not filename: text.bell() return lineno = int(float(text.index("insert"))) try: self.breakpoints.remove(lineno) except: pass text.tag_remove("BREAK", "insert linestart",\ "insert lineend +1char") try: debug = self.flist.pyshell.interp.debugger debug.clear_breakpoint_here(filename, lineno) except: pass def clear_file_breaks(self): if self.breakpoints: text = self.text filename = self.io.filename if not filename: text.bell() return self.breakpoints = [] text.tag_remove("BREAK", "1.0", END) try: debug = self.flist.pyshell.interp.debugger debug.clear_file_breaks(filename) except: pass def store_file_breaks(self): "Save breakpoints when file is saved" # XXX 13 Dec 2002 KBK Currently the file must be saved before it can # be run. The breaks are saved at that time. If we introduce # a temporary file save feature the save breaks functionality # needs to be re-verified, since the breaks at the time the # temp file is created may differ from the breaks at the last # permanent save of the file. Currently, a break introduced # after a save will be effective, but not persistent. # This is necessary to keep the saved breaks synched with the # saved file. # # Breakpoints are set as tagged ranges in the text. # Since a modified file has to be saved before it is # run, and since self.breakpoints (from which the subprocess # debugger is loaded) is updated during the save, the visible # breaks stay synched with the subprocess even if one of these # unexpected breakpoint deletions occurs. breaks = self.breakpoints filename = self.io.filename try: with open(self.breakpointPath, "r") as fp: lines = fp.readlines() except OSError: lines = [] try: with open(self.breakpointPath, "w") as new_file: for line in lines: if not line.startswith(filename + '='): new_file.write(line) self.update_breakpoints() breaks = self.breakpoints if breaks: new_file.write(filename + '=' + str(breaks) + '\n') except OSError as err: if not getattr(self.root, "breakpoint_error_displayed", False): self.root.breakpoint_error_displayed = True messagebox.showerror(title='IDLE Error', message='Unable to update breakpoint list:\n%s' % str(err), parent=self.text) def restore_file_breaks(self): self.text.update() # this enables setting "BREAK" tags to be visible if self.io is None: # can happen if IDLE closes due to the .update() call return filename = self.io.filename if filename is None: return if os.path.isfile(self.breakpointPath): with open(self.breakpointPath, "r") as fp: lines = fp.readlines() for line in lines: if line.startswith(filename + '='): breakpoint_linenumbers = eval(line[len(filename)+1:]) for breakpoint_linenumber in breakpoint_linenumbers: self.set_breakpoint(breakpoint_linenumber) def update_breakpoints(self): "Retrieves all the breakpoints in the current window" text = self.text ranges = text.tag_ranges("BREAK") linenumber_list = self.ranges_to_linenumbers(ranges) self.breakpoints = linenumber_list def ranges_to_linenumbers(self, ranges): lines = [] for index in range(0, len(ranges), 2): lineno = int(float(ranges[index].string)) end = int(float(ranges[index+1].string)) while lineno < end: lines.append(lineno) lineno += 1 return lines # XXX 13 Dec 2002 KBK Not used currently # def saved_change_hook(self): # "Extend base method - clear breaks if module is modified" # if not self.get_saved(): # self.clear_file_breaks() # EditorWindow.saved_change_hook(self) def _close(self): "Extend base method - clear breaks when module is closed" self.clear_file_breaks() EditorWindow._close(self) class PyShellFileList(FileList): "Extend base class: IDLE supports a shell and breakpoints" # override FileList's class variable, instances return PyShellEditorWindow # instead of EditorWindow when new edit windows are created. EditorWindow = PyShellEditorWindow pyshell = None def open_shell(self, event=None): if self.pyshell: self.pyshell.top.wakeup() else: self.pyshell = PyShell(self) if self.pyshell: if not self.pyshell.begin(): return None return self.pyshell class ModifiedColorDelegator(ColorDelegator): "Extend base class: colorizer for the shell window itself" def recolorize_main(self): self.tag_remove("TODO", "1.0", "iomark") self.tag_add("SYNC", "1.0", "iomark") ColorDelegator.recolorize_main(self) def removecolors(self): # Don't remove shell color tags before "iomark" for tag in self.tagdefs: self.tag_remove(tag, "iomark", "end") class ModifiedUndoDelegator(UndoDelegator): "Extend base class: forbid insert/delete before the I/O mark" def insert(self, index, chars, tags=None): try: if self.delegate.compare(index, "<", "iomark"): self.delegate.bell() return except TclError: pass UndoDelegator.insert(self, index, chars, tags) def delete(self, index1, index2=None): try: if self.delegate.compare(index1, "<", "iomark"): self.delegate.bell() return except TclError: pass UndoDelegator.delete(self, index1, index2) def undo_event(self, event): # Temporarily monkey-patch the delegate's .insert() method to # always use the "stdin" tag. This is needed for undo-ing # deletions to preserve the "stdin" tag, because UndoDelegator # doesn't preserve tags for deleted text. orig_insert = self.delegate.insert self.delegate.insert = \ lambda index, chars: orig_insert(index, chars, "stdin") try: super().undo_event(event) finally: self.delegate.insert = orig_insert class UserInputTaggingDelegator(Delegator): """Delegator used to tag user input with "stdin".""" def insert(self, index, chars, tags=None): if tags is None: tags = "stdin" self.delegate.insert(index, chars, tags) class MyRPCClient(rpc.RPCClient): def handle_EOF(self): "Override the base class - just re-raise EOFError" raise EOFError def restart_line(width, filename): # See bpo-38141. """Return width long restart line formatted with filename. Fill line with balanced '='s, with any extras and at least one at the beginning. Do not end with a trailing space. """ tag = f"= RESTART: {filename or 'Shell'} =" if width >= len(tag): div, mod = divmod((width -len(tag)), 2) return f"{(div+mod)*'='}{tag}{div*'='}" else: return tag[:-2] # Remove ' ='. class ModifiedInterpreter(InteractiveInterpreter): def __init__(self, tkconsole): self.tkconsole = tkconsole locals = sys.modules['__main__'].__dict__ InteractiveInterpreter.__init__(self, locals=locals) self.restarting = False self.subprocess_arglist = None self.port = PORT self.original_compiler_flags = self.compile.compiler.flags _afterid = None rpcclt = None rpcsubproc = None def spawn_subprocess(self): if self.subprocess_arglist is None: self.subprocess_arglist = self.build_subprocess_arglist() self.rpcsubproc = subprocess.Popen(self.subprocess_arglist) def build_subprocess_arglist(self): assert (self.port!=0), ( "Socket should have been assigned a port number.") w = ['-W' + s for s in sys.warnoptions] # Maybe IDLE is installed and is being accessed via sys.path, # or maybe it's not installed and the idle.py script is being # run from the IDLE source directory. del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc', default=False, type='bool') command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,) return [sys.executable] + w + ["-c", command, str(self.port)] def start_subprocess(self): addr = (HOST, self.port) # GUI makes several attempts to acquire socket, listens for connection for i in range(3): time.sleep(i) try: self.rpcclt = MyRPCClient(addr) break except OSError: pass else: self.display_port_binding_error() return None # if PORT was 0, system will assign an 'ephemeral' port. Find it out: self.port = self.rpcclt.listening_sock.getsockname()[1] # if PORT was not 0, probably working with a remote execution server if PORT != 0: # To allow reconnection within the 2MSL wait (cf. Stevens TCP # V1, 18.6), set SO_REUSEADDR. Note that this can be problematic # on Windows since the implementation allows two active sockets on # the same address! self.rpcclt.listening_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.spawn_subprocess() #time.sleep(20) # test to simulate GUI not accepting connection # Accept the connection from the Python execution server self.rpcclt.listening_sock.settimeout(10) try: self.rpcclt.accept() except TimeoutError: self.display_no_subprocess_error() return None self.rpcclt.register("console", self.tkconsole) self.rpcclt.register("stdin", self.tkconsole.stdin) self.rpcclt.register("stdout", self.tkconsole.stdout) self.rpcclt.register("stderr", self.tkconsole.stderr) self.rpcclt.register("flist", self.tkconsole.flist) self.rpcclt.register("linecache", linecache) self.rpcclt.register("interp", self) self.transfer_path(with_cwd=True) self.poll_subprocess() return self.rpcclt def restart_subprocess(self, with_cwd=False, filename=''): if self.restarting: return self.rpcclt self.restarting = True # close only the subprocess debugger debug = self.getdebugger() if debug: try: # Only close subprocess debugger, don't unregister gui_adap! debugger_r.close_subprocess_debugger(self.rpcclt) except: pass # Kill subprocess, spawn a new one, accept connection. self.rpcclt.close() self.terminate_subprocess() console = self.tkconsole was_executing = console.executing console.executing = False self.spawn_subprocess() try: self.rpcclt.accept() except TimeoutError: self.display_no_subprocess_error() return None self.transfer_path(with_cwd=with_cwd) console.stop_readline() # annotate restart in shell window and mark it console.text.delete("iomark", "end-1c") console.write('\n') console.write(restart_line(console.width, filename)) console.text.mark_set("restart", "end-1c") console.text.mark_gravity("restart", "left") if not filename: console.showprompt() # restart subprocess debugger if debug: # Restarted debugger connects to current instance of debug GUI debugger_r.restart_subprocess_debugger(self.rpcclt) # reload remote debugger breakpoints for all PyShellEditWindows debug.load_breakpoints() self.compile.compiler.flags = self.original_compiler_flags self.restarting = False return self.rpcclt def __request_interrupt(self): self.rpcclt.remotecall("exec", "interrupt_the_server", (), {}) def interrupt_subprocess(self): threading.Thread(target=self.__request_interrupt).start() def kill_subprocess(self): if self._afterid is not None: self.tkconsole.text.after_cancel(self._afterid) try: self.rpcclt.listening_sock.close() except AttributeError: # no socket pass try: self.rpcclt.close() except AttributeError: # no socket pass self.terminate_subprocess() self.tkconsole.executing = False self.rpcclt = None def terminate_subprocess(self): "Make sure subprocess is terminated" try: self.rpcsubproc.kill() except OSError: # process already terminated return else: try: self.rpcsubproc.wait() except OSError: return def transfer_path(self, with_cwd=False): if with_cwd: # Issue 13506 path = [''] # include Current Working Directory path.extend(sys.path) else: path = sys.path self.runcommand("""if 1: import sys as _sys _sys.path = %r del _sys \n""" % (path,)) active_seq = None def poll_subprocess(self): clt = self.rpcclt if clt is None: return try: response = clt.pollresponse(self.active_seq, wait=0.05) except (EOFError, OSError, KeyboardInterrupt): # lost connection or subprocess terminated itself, restart # [the KBI is from rpc.SocketIO.handle_EOF()] if self.tkconsole.closing: return response = None self.restart_subprocess() if response: self.tkconsole.resetoutput() self.active_seq = None how, what = response console = self.tkconsole.console if how == "OK": if what is not None: print(repr(what), file=console) elif how == "EXCEPTION": if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"): self.remote_stack_viewer() elif how == "ERROR": errmsg = "pyshell.ModifiedInterpreter: Subprocess ERROR:\n" print(errmsg, what, file=sys.__stderr__) print(errmsg, what, file=console) # we received a response to the currently active seq number: try: self.tkconsole.endexecuting() except AttributeError: # shell may have closed pass # Reschedule myself if not self.tkconsole.closing: self._afterid = self.tkconsole.text.after( self.tkconsole.pollinterval, self.poll_subprocess) debugger = None def setdebugger(self, debugger): self.debugger = debugger def getdebugger(self): return self.debugger def open_remote_stack_viewer(self): """Initiate the remote stack viewer from a separate thread. This method is called from the subprocess, and by returning from this method we allow the subprocess to unblock. After a bit the shell requests the subprocess to open the remote stack viewer which returns a static object looking at the last exception. It is queried through the RPC mechanism. """ self.tkconsole.text.after(300, self.remote_stack_viewer) return def remote_stack_viewer(self): from idlelib import debugobj_r oid = self.rpcclt.remotequeue("exec", "stackviewer", ("flist",), {}) if oid is None: self.tkconsole.root.bell() return item = debugobj_r.StubObjectTreeItem(self.rpcclt, oid) from idlelib.tree import ScrolledCanvas, TreeNode top = Toplevel(self.tkconsole.root) theme = idleConf.CurrentTheme() background = idleConf.GetHighlight(theme, 'normal')['background'] sc = ScrolledCanvas(top, bg=background, highlightthickness=0) sc.frame.pack(expand=1, fill="both") node = TreeNode(sc.canvas, None, item) node.expand() # XXX Should GC the remote tree when closing the window gid = 0 def execsource(self, source): "Like runsource() but assumes complete exec source" filename = self.stuffsource(source) self.execfile(filename, source) def execfile(self, filename, source=None): "Execute an existing file" if source is None: with tokenize.open(filename) as fp: source = fp.read() if use_subprocess: source = (f"__file__ = r'''{os.path.abspath(filename)}'''\n" + source + "\ndel __file__") try: code = compile(source, filename, "exec") except (OverflowError, SyntaxError): self.tkconsole.resetoutput() print('*** Error in script or command!\n' 'Traceback (most recent call last):', file=self.tkconsole.stderr) InteractiveInterpreter.showsyntaxerror(self, filename) self.tkconsole.showprompt() else: self.runcode(code) def runsource(self, source): "Extend base class method: Stuff the source in the line cache first" filename = self.stuffsource(source) # at the moment, InteractiveInterpreter expects str assert isinstance(source, str) # InteractiveInterpreter.runsource() calls its runcode() method, # which is overridden (see below) return InteractiveInterpreter.runsource(self, source, filename) def stuffsource(self, source): "Stuff source in the filename cache" filename = "<pyshell#%d>" % self.gid self.gid = self.gid + 1 lines = source.split("\n") linecache.cache[filename] = len(source)+1, 0, lines, filename return filename def prepend_syspath(self, filename): "Prepend sys.path with file's directory if not already included" self.runcommand("""if 1: _filename = %r import sys as _sys from os.path import dirname as _dirname _dir = _dirname(_filename) if not _dir in _sys.path: _sys.path.insert(0, _dir) del _filename, _sys, _dirname, _dir \n""" % (filename,)) def showsyntaxerror(self, filename=None): """Override Interactive Interpreter method: Use Colorizing Color the offending position instead of printing it and pointing at it with a caret. """ tkconsole = self.tkconsole text = tkconsole.text text.tag_remove("ERROR", "1.0", "end") type, value, tb = sys.exc_info() msg = getattr(value, 'msg', '') or value or "<no detail available>" lineno = getattr(value, 'lineno', '') or 1 offset = getattr(value, 'offset', '') or 0 if offset == 0: lineno += 1 #mark end of offending line if lineno == 1: pos = "iomark + %d chars" % (offset-1) else: pos = "iomark linestart + %d lines + %d chars" % \ (lineno-1, offset-1) tkconsole.colorize_syntax_error(text, pos) tkconsole.resetoutput() self.write("SyntaxError: %s\n" % msg) tkconsole.showprompt() def showtraceback(self): "Extend base class method to reset output properly" self.tkconsole.resetoutput() self.checklinecache() InteractiveInterpreter.showtraceback(self) if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"): self.tkconsole.open_stack_viewer() def checklinecache(self): c = linecache.cache for key in list(c.keys()): if key[:1] + key[-1:] != "<>": del c[key] def runcommand(self, code): "Run the code without invoking the debugger" # The code better not raise an exception! if self.tkconsole.executing: self.display_executing_dialog() return 0 if self.rpcclt: self.rpcclt.remotequeue("exec", "runcode", (code,), {}) else: exec(code, self.locals) return 1 def runcode(self, code): "Override base class method" if self.tkconsole.executing: self.restart_subprocess() self.checklinecache() debugger = self.debugger try: self.tkconsole.beginexecuting() if not debugger and self.rpcclt is not None: self.active_seq = self.rpcclt.asyncqueue("exec", "runcode", (code,), {}) elif debugger: debugger.run(code, self.locals) else: exec(code, self.locals) except SystemExit: if not self.tkconsole.closing: if messagebox.askyesno( "Exit?", "Do you want to exit altogether?", default="yes", parent=self.tkconsole.text): raise else: self.showtraceback() else: raise except: if use_subprocess: print("IDLE internal error in runcode()", file=self.tkconsole.stderr) self.showtraceback() self.tkconsole.endexecuting() else: if self.tkconsole.canceled: self.tkconsole.canceled = False print("KeyboardInterrupt", file=self.tkconsole.stderr) else: self.showtraceback() finally: if not use_subprocess: try: self.tkconsole.endexecuting() except AttributeError: # shell may have closed pass def write(self, s): "Override base class method" return self.tkconsole.stderr.write(s) def display_port_binding_error(self): messagebox.showerror( "Port Binding Error", "IDLE can't bind to a TCP/IP port, which is necessary to " "communicate with its Python execution server. This might be " "because no networking is installed on this computer. " "Run IDLE with the -n command line switch to start without a " "subprocess and refer to Help/IDLE Help 'Running without a " "subprocess' for further details.", parent=self.tkconsole.text) def display_no_subprocess_error(self): messagebox.showerror( "Subprocess Connection Error", "IDLE's subprocess didn't make connection.\n" "See the 'Startup failure' section of the IDLE doc, online at\n" "https://docs.python.org/3/library/idle.html#startup-failure", parent=self.tkconsole.text) def display_executing_dialog(self): messagebox.showerror( "Already executing", "The Python Shell window is already executing a command; " "please wait until it is finished.", parent=self.tkconsole.text) class PyShell(OutputWindow): from idlelib.squeezer import Squeezer shell_title = "IDLE Shell " + python_version() # Override classes ColorDelegator = ModifiedColorDelegator UndoDelegator = ModifiedUndoDelegator # Override menus menu_specs = [ ("file", "_File"), ("edit", "_Edit"), ("debug", "_Debug"), ("options", "_Options"), ("window", "_Window"), ("help", "_Help"), ] # Extend right-click context menu rmenu_specs = OutputWindow.rmenu_specs + [ ("Squeeze", "<<squeeze-current-text>>"), ] allow_line_numbers = False user_input_insert_tags = "stdin" # New classes from idlelib.history import History from idlelib.sidebar import ShellSidebar def __init__(self, flist=None): if use_subprocess: ms = self.menu_specs if ms[2][0] != "shell": ms.insert(2, ("shell", "She_ll")) self.interp = ModifiedInterpreter(self) if flist is None: root = Tk() fixwordbreaks(root) root.withdraw() flist = PyShellFileList(root) self.shell_sidebar = None # initialized below OutputWindow.__init__(self, flist, None, None) self.usetabs = False # indentwidth must be 8 when using tabs. See note in EditorWindow: self.indentwidth = 4 self.sys_ps1 = sys.ps1 if hasattr(sys, 'ps1') else '>>>\n' self.prompt_last_line = self.sys_ps1.split('\n')[-1] self.prompt = self.sys_ps1 # Changes when debug active text = self.text text.configure(wrap="char") text.bind("<<newline-and-indent>>", self.enter_callback) text.bind("<<plain-newline-and-indent>>", self.linefeed_callback) text.bind("<<interrupt-execution>>", self.cancel_callback) text.bind("<<end-of-file>>", self.eof_callback) text.bind("<<open-stack-viewer>>", self.open_stack_viewer) text.bind("<<toggle-debugger>>", self.toggle_debugger) text.bind("<<toggle-jit-stack-viewer>>", self.toggle_jit_stack_viewer) if use_subprocess: text.bind("<<view-restart>>", self.view_restart_mark) text.bind("<<restart-shell>>", self.restart_shell) self.squeezer = self.Squeezer(self) text.bind("<<squeeze-current-text>>", self.squeeze_current_text_event) self.save_stdout = sys.stdout self.save_stderr = sys.stderr self.save_stdin = sys.stdin from idlelib import iomenu self.stdin = StdInputFile(self, "stdin", iomenu.encoding, iomenu.errors) self.stdout = StdOutputFile(self, "stdout", iomenu.encoding, iomenu.errors) self.stderr = StdOutputFile(self, "stderr", iomenu.encoding, "backslashreplace") self.console = StdOutputFile(self, "console", iomenu.encoding, iomenu.errors) if not use_subprocess: sys.stdout = self.stdout sys.stderr = self.stderr sys.stdin = self.stdin try: # page help() text to shell. import pydoc # import must be done here to capture i/o rebinding. # XXX KBK 27Dec07 use text viewer someday, but must work w/o subproc pydoc.pager = pydoc.plainpager except: sys.stderr = sys.__stderr__ raise # self.history = self.History(self.text) # self.pollinterval = 50 # millisec self.shell_sidebar = self.ShellSidebar(self) # Insert UserInputTaggingDelegator at the top of the percolator, # but make calls to text.insert() skip it. This causes only insert # events generated in Tcl/Tk to go through this delegator. self.text.insert = self.per.top.insert self.per.insertfilter(UserInputTaggingDelegator()) def ResetFont(self): super().ResetFont() if self.shell_sidebar is not None: self.shell_sidebar.update_font() def ResetColorizer(self): super().ResetColorizer() theme = idleConf.CurrentTheme() tag_colors = { "stdin": {'background': None, 'foreground': None}, "stdout": idleConf.GetHighlight(theme, "stdout"), "stderr": idleConf.GetHighlight(theme, "stderr"), "console": idleConf.GetHighlight(theme, "normal"), } for tag, tag_colors_config in tag_colors.items(): self.text.tag_configure(tag, **tag_colors_config) if self.shell_sidebar is not None: self.shell_sidebar.update_colors() def replace_event(self, event): replace.replace(self.text, insert_tags="stdin") return "break" def get_standard_extension_names(self): return idleConf.GetExtensions(shell_only=True) reading = False executing = False canceled = False endoffile = False closing = False _stop_readline_flag = False def set_warning_stream(self, stream): global warning_stream warning_stream = stream def get_warning_stream(self): return warning_stream def toggle_debugger(self, event=None): if self.executing: messagebox.showerror("Don't debug now", "You can only toggle the debugger when idle", parent=self.text) self.set_debugger_indicator() return "break" else: db = self.interp.getdebugger() if db: self.close_debugger() else: self.open_debugger() def set_debugger_indicator(self): db = self.interp.getdebugger() self.setvar("<<toggle-debugger>>", not not db) def toggle_jit_stack_viewer(self, event=None): pass # All we need is the variable def close_debugger(self): db = self.interp.getdebugger() if db: self.interp.setdebugger(None) db.close() if self.interp.rpcclt: debugger_r.close_remote_debugger(self.interp.rpcclt) self.resetoutput() self.console.write("[DEBUG OFF]\n") self.prompt = self.sys_ps1 self.showprompt() self.set_debugger_indicator() def open_debugger(self): if self.interp.rpcclt: dbg_gui = debugger_r.start_remote_debugger(self.interp.rpcclt, self) else: dbg_gui = debugger.Debugger(self) self.interp.setdebugger(dbg_gui) dbg_gui.load_breakpoints() self.prompt = "[DEBUG ON]\n" + self.sys_ps1 self.showprompt() self.set_debugger_indicator() def debug_menu_postcommand(self): state = 'disabled' if self.executing else 'normal' self.update_menu_state('debug', '*tack*iewer', state) def beginexecuting(self): "Helper for ModifiedInterpreter" self.resetoutput() self.executing = True def endexecuting(self): "Helper for ModifiedInterpreter" self.executing = False self.canceled = False self.showprompt() def close(self): "Extend EditorWindow.close()" if self.executing: response = messagebox.askokcancel( "Kill?", "Your program is still running!\n Do you want to kill it?", default="ok", parent=self.text) if response is False: return "cancel" self.stop_readline() self.canceled = True self.closing = True return EditorWindow.close(self) def _close(self): "Extend EditorWindow._close(), shut down debugger and execution server" self.close_debugger() if use_subprocess: self.interp.kill_subprocess() # Restore std streams sys.stdout = self.save_stdout sys.stderr = self.save_stderr sys.stdin = self.save_stdin # Break cycles self.interp = None self.console = None self.flist.pyshell = None self.history = None EditorWindow._close(self) def ispythonsource(self, filename): "Override EditorWindow method: never remove the colorizer" return True def short_title(self): return self.shell_title COPYRIGHT = \ 'Type "help", "copyright", "credits" or "license()" for more information.' def begin(self): self.text.mark_set("iomark", "insert") self.resetoutput() if use_subprocess: nosub = '' client = self.interp.start_subprocess() if not client: self.close() return False else: nosub = ("==== No Subprocess ====\n\n" + "WARNING: Running IDLE without a Subprocess is deprecated\n" + "and will be removed in a later version. See Help/IDLE Help\n" + "for details.\n\n") sys.displayhook = rpc.displayhook self.write("Python %s on %s\n%s\n%s" % (sys.version, sys.platform, self.COPYRIGHT, nosub)) self.text.focus_force() self.showprompt() # User code should use separate default Tk root window import tkinter tkinter._support_default_root = True tkinter._default_root = None return True def stop_readline(self): if not self.reading: # no nested mainloop to exit. return self._stop_readline_flag = True self.top.quit() def readline(self): save = self.reading try: self.reading = True self.top.mainloop() # nested mainloop() finally: self.reading = save if self._stop_readline_flag: self._stop_readline_flag = False return "" line = self.text.get("iomark", "end-1c") if len(line) == 0: # may be EOF if we quit our mainloop with Ctrl-C line = "\n" self.resetoutput() if self.canceled: self.canceled = False if not use_subprocess: raise KeyboardInterrupt if self.endoffile: self.endoffile = False line = "" return line def isatty(self): return True def cancel_callback(self, event=None): try: if self.text.compare("sel.first", "!=", "sel.last"): return # Active selection -- always use default binding except: pass if not (self.executing or self.reading): self.resetoutput() self.interp.write("KeyboardInterrupt\n") self.showprompt() return "break" self.endoffile = False self.canceled = True if (self.executing and self.interp.rpcclt): if self.interp.getdebugger(): self.interp.restart_subprocess() else: self.interp.interrupt_subprocess() if self.reading: self.top.quit() # exit the nested mainloop() in readline() return "break" def eof_callback(self, event): if self.executing and not self.reading: return # Let the default binding (delete next char) take over if not (self.text.compare("iomark", "==", "insert") and self.text.compare("insert", "==", "end-1c")): return # Let the default binding (delete next char) take over if not self.executing: self.resetoutput() self.close() else: self.canceled = False self.endoffile = True self.top.quit() return "break" def linefeed_callback(self, event): # Insert a linefeed without entering anything (still autoindented) if self.reading: self.text.insert("insert", "\n") self.text.see("insert") else: self.newline_and_indent_event(event) return "break" def enter_callback(self, event): if self.executing and not self.reading: return # Let the default binding (insert '\n') take over # If some text is selected, recall the selection # (but only if this before the I/O mark) try: sel = self.text.get("sel.first", "sel.last") if sel: if self.text.compare("sel.last", "<=", "iomark"): self.recall(sel, event) return "break" except: pass # If we're strictly before the line containing iomark, recall # the current line, less a leading prompt, less leading or # trailing whitespace if self.text.compare("insert", "<", "iomark linestart"): # Check if there's a relevant stdin range -- if so, use it. # Note: "stdin" blocks may include several successive statements, # so look for "console" tags on the newline before each statement # (and possibly on prompts). prev = self.text.tag_prevrange("stdin", "insert") if ( prev and self.text.compare("insert", "<", prev[1]) and # The following is needed to handle empty statements. "console" not in self.text.tag_names("insert") ): prev_cons = self.text.tag_prevrange("console", "insert") if prev_cons and self.text.compare(prev_cons[1], ">=", prev[0]): prev = (prev_cons[1], prev[1]) next_cons = self.text.tag_nextrange("console", "insert") if next_cons and self.text.compare(next_cons[0], "<", prev[1]): prev = (prev[0], self.text.index(next_cons[0] + "+1c")) self.recall(self.text.get(prev[0], prev[1]), event) return "break" next = self.text.tag_nextrange("stdin", "insert") if next and self.text.compare("insert lineend", ">=", next[0]): next_cons = self.text.tag_nextrange("console", "insert lineend") if next_cons and self.text.compare(next_cons[0], "<", next[1]): next = (next[0], self.text.index(next_cons[0] + "+1c")) self.recall(self.text.get(next[0], next[1]), event) return "break" # No stdin mark -- just get the current line, less any prompt indices = self.text.tag_nextrange("console", "insert linestart") if indices and \ self.text.compare(indices[0], "<=", "insert linestart"): self.recall(self.text.get(indices[1], "insert lineend"), event) else: self.recall(self.text.get("insert linestart", "insert lineend"), event) return "break" # If we're between the beginning of the line and the iomark, i.e. # in the prompt area, move to the end of the prompt if self.text.compare("insert", "<", "iomark"): self.text.mark_set("insert", "iomark") # If we're in the current input and there's only whitespace # beyond the cursor, erase that whitespace first s = self.text.get("insert", "end-1c") if s and not s.strip(): self.text.delete("insert", "end-1c") # If we're in the current input before its last line, # insert a newline right at the insert point if self.text.compare("insert", "<", "end-1c linestart"): self.newline_and_indent_event(event) return "break" # We're in the last line; append a newline and submit it self.text.mark_set("insert", "end-1c") if self.reading: self.text.insert("insert", "\n") self.text.see("insert") else: self.newline_and_indent_event(event) self.text.update_idletasks() if self.reading: self.top.quit() # Break out of recursive mainloop() else: self.runit() return "break" def recall(self, s, event): # remove leading and trailing empty or whitespace lines s = re.sub(r'^\s*\n', '', s) s = re.sub(r'\n\s*$', '', s) lines = s.split('\n') self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") prefix = self.text.get("insert linestart", "insert") if prefix.rstrip().endswith(':'): self.newline_and_indent_event(event) prefix = self.text.get("insert linestart", "insert") self.text.insert("insert", lines[0].strip(), self.user_input_insert_tags) if len(lines) > 1: orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0) new_base_indent = re.search(r'^([ \t]*)', prefix).group(0) for line in lines[1:]: if line.startswith(orig_base_indent): # replace orig base indentation with new indentation line = new_base_indent + line[len(orig_base_indent):] self.text.insert('insert', '\n' + line.rstrip(), self.user_input_insert_tags) finally: self.text.see("insert") self.text.undo_block_stop() _last_newline_re = re.compile(r"[ \t]*(\n[ \t]*)?\Z") def runit(self): index_before = self.text.index("end-2c") line = self.text.get("iomark", "end-1c") # Strip off last newline and surrounding whitespace. # (To allow you to hit return twice to end a statement.) line = self._last_newline_re.sub("", line) input_is_complete = self.interp.runsource(line) if not input_is_complete: if self.text.get(index_before) == '\n': self.text.tag_remove(self.user_input_insert_tags, index_before) self.shell_sidebar.update_sidebar() def open_stack_viewer(self, event=None): if self.interp.rpcclt: return self.interp.remote_stack_viewer() try: sys.last_traceback except: messagebox.showerror("No stack trace", "There is no stack trace yet.\n" "(sys.last_traceback is not defined)", parent=self.text) return from idlelib.stackviewer import StackBrowser StackBrowser(self.root, self.flist) def view_restart_mark(self, event=None): self.text.see("iomark") self.text.see("restart") def restart_shell(self, event=None): "Callback for Run/Restart Shell Cntl-F6" self.interp.restart_subprocess(with_cwd=True) def showprompt(self): self.resetoutput() prompt = self.prompt if self.sys_ps1 and prompt.endswith(self.sys_ps1): prompt = prompt[:-len(self.sys_ps1)] self.text.tag_add("console", "iomark-1c") self.console.write(prompt) self.shell_sidebar.update_sidebar() self.text.mark_set("insert", "end-1c") self.set_line_and_column() self.io.reset_undo() def show_warning(self, msg): width = self.interp.tkconsole.width wrapper = TextWrapper(width=width, tabsize=8, expand_tabs=True) wrapped_msg = '\n'.join(wrapper.wrap(msg)) if not wrapped_msg.endswith('\n'): wrapped_msg += '\n' self.per.bottom.insert("iomark linestart", wrapped_msg, "stderr") def resetoutput(self): source = self.text.get("iomark", "end-1c") if self.history: self.history.store(source) if self.text.get("end-2c") != "\n": self.text.insert("end-1c", "\n") self.text.mark_set("iomark", "end-1c") self.set_line_and_column() self.ctip.remove_calltip_window() def write(self, s, tags=()): try: self.text.mark_gravity("iomark", "right") count = OutputWindow.write(self, s, tags, "iomark") self.text.mark_gravity("iomark", "left") except: raise ###pass # ### 11Aug07 KBK if we are expecting exceptions # let's find out what they are and be specific. if self.canceled: self.canceled = False if not use_subprocess: raise KeyboardInterrupt return count def rmenu_check_cut(self): try: if self.text.compare('sel.first', '<', 'iomark'): return 'disabled' except TclError: # no selection, so the index 'sel.first' doesn't exist return 'disabled' return super().rmenu_check_cut() def rmenu_check_paste(self): if self.text.compare('insert','<','iomark'): return 'disabled' return super().rmenu_check_paste() def squeeze_current_text_event(self, event=None): self.squeezer.squeeze_current_text() self.shell_sidebar.update_sidebar() def on_squeezed_expand(self, index, text, tags): self.shell_sidebar.update_sidebar() def fix_x11_paste(root): "Make paste replace selection on x11. See issue #5124." if root._windowingsystem == 'x11': for cls in 'Text', 'Entry', 'Spinbox': root.bind_class( cls, '<<Paste>>', 'catch {%W delete sel.first sel.last}\n' + root.bind_class(cls, '<<Paste>>')) usage_msg = """\ USAGE: idle [-deins] [-t title] [file]* idle [-dns] [-t title] (-c cmd | -r file) [arg]* idle [-dns] [-t title] - [arg]* -h print this help message and exit -n run IDLE without a subprocess (DEPRECATED, see Help/IDLE Help for details) The following options will override the IDLE 'settings' configuration: -e open an edit window -i open a shell window The following options imply -i and will open a shell: -c cmd run the command in a shell, or -r file run script from file -d enable the debugger -s run $IDLESTARTUP or $PYTHONSTARTUP before anything else -t title set title of shell window A default edit window will be bypassed when -c, -r, or - are used. [arg]* are passed to the command (-c) or script (-r) in sys.argv[1:]. Examples: idle Open an edit window or shell depending on IDLE's configuration. idle foo.py foobar.py Edit the files, also open a shell if configured to start with shell. idle -est "Baz" foo.py Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell window with the title "Baz". idle -c "import sys; print(sys.argv)" "foo" Open a shell window and run the command, passing "-c" in sys.argv[0] and "foo" in sys.argv[1]. idle -d -s -r foo.py "Hello World" Open a shell window, run a startup script, enable the debugger, and run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in sys.argv[1]. echo "import sys; print(sys.argv)" | idle - "foobar" Open a shell window, run the script piped in, passing '' in sys.argv[0] and "foobar" in sys.argv[1]. """ def main(): import getopt from platform import system from idlelib import testing # bool value from idlelib import macosx global flist, root, use_subprocess capture_warnings(True) use_subprocess = True enable_shell = False enable_edit = False debug = False cmd = None script = None startup = False try: opts, args = getopt.getopt(sys.argv[1:], "c:deihnr:st:") except getopt.error as msg: print("Error: %s\n%s" % (msg, usage_msg), file=sys.stderr) sys.exit(2) for o, a in opts: if o == '-c': cmd = a enable_shell = True if o == '-d': debug = True enable_shell = True if o == '-e': enable_edit = True if o == '-h': sys.stdout.write(usage_msg) sys.exit() if o == '-i': enable_shell = True if o == '-n': print(" Warning: running IDLE without a subprocess is deprecated.", file=sys.stderr) use_subprocess = False if o == '-r': script = a if os.path.isfile(script): pass else: print("No script file: ", script) sys.exit() enable_shell = True if o == '-s': startup = True enable_shell = True if o == '-t': PyShell.shell_title = a enable_shell = True if args and args[0] == '-': cmd = sys.stdin.read() enable_shell = True # process sys.argv and sys.path: for i in range(len(sys.path)): sys.path[i] = os.path.abspath(sys.path[i]) if args and args[0] == '-': sys.argv = [''] + args[1:] elif cmd: sys.argv = ['-c'] + args elif script: sys.argv = [script] + args elif args: enable_edit = True pathx = [] for filename in args: pathx.append(os.path.dirname(filename)) for dir in pathx: dir = os.path.abspath(dir) if not dir in sys.path: sys.path.insert(0, dir) else: dir = os.getcwd() if dir not in sys.path: sys.path.insert(0, dir) # check the IDLE settings configuration (but command line overrides) edit_start = idleConf.GetOption('main', 'General', 'editor-on-startup', type='bool') enable_edit = enable_edit or edit_start enable_shell = enable_shell or not enable_edit # Setup root. Don't break user code run in IDLE process. # Don't change environment when testing. if use_subprocess and not testing: NoDefaultRoot() root = Tk(className="Idle") root.withdraw() from idlelib.run import fix_scaling fix_scaling(root) # set application icon icondir = os.path.join(os.path.dirname(__file__), 'Icons') if system() == 'Windows': iconfile = os.path.join(icondir, 'idle.ico') root.wm_iconbitmap(default=iconfile) elif not macosx.isAquaTk(): if TkVersion >= 8.6: ext = '.png' sizes = (16, 32, 48, 256) else: ext = '.gif' sizes = (16, 32, 48) iconfiles = [os.path.join(icondir, 'idle_%d%s' % (size, ext)) for size in sizes] icons = [PhotoImage(master=root, file=iconfile) for iconfile in iconfiles] root.wm_iconphoto(True, *icons) # start editor and/or shell windows: fixwordbreaks(root) fix_x11_paste(root) flist = PyShellFileList(root) macosx.setupApp(root, flist) if enable_edit: if not (cmd or script): for filename in args[:]: if flist.open(filename) is None: # filename is a directory actually, disconsider it args.remove(filename) if not args: flist.new() if enable_shell: shell = flist.open_shell() if not shell: return # couldn't open shell if macosx.isAquaTk() and flist.dict: # On OSX: when the user has double-clicked on a file that causes # IDLE to be launched the shell window will open just in front of # the file she wants to see. Lower the interpreter window when # there are open files. shell.top.lower() else: shell = flist.pyshell # Handle remaining options. If any of these are set, enable_shell # was set also, so shell must be true to reach here. if debug: shell.open_debugger() if startup: filename = os.environ.get("IDLESTARTUP") or \ os.environ.get("PYTHONSTARTUP") if filename and os.path.isfile(filename): shell.interp.execfile(filename) if cmd or script: shell.interp.runcommand("""if 1: import sys as _sys _sys.argv = %r del _sys \n""" % (sys.argv,)) if cmd: shell.interp.execsource(cmd) elif script: shell.interp.prepend_syspath(script) shell.interp.execfile(script) elif shell: # If there is a shell window and no cmd or script in progress, # check for problematic issues and print warning message(s) in # the IDLE shell window; this is less intrusive than always # opening a separate window. # Warn if using a problematic OS X Tk version. tkversionwarning = macosx.tkVersionWarning(root) if tkversionwarning: shell.show_warning(tkversionwarning) # Warn if the "Prefer tabs when opening documents" system # preference is set to "Always". prefer_tabs_preference_warning = macosx.preferTabsPreferenceWarning() if prefer_tabs_preference_warning: shell.show_warning(prefer_tabs_preference_warning) while flist.inversedict: # keep IDLE running while files are open. root.mainloop() root.destroy() capture_warnings(False) if __name__ == "__main__": main() capture_warnings(False) # Make sure turned off; see issue 18081
main.py
import logging import time import sys from gui import App from mower import Mower from parser import Parser from threading import Thread from environment import Environment from PyQt5.QtWidgets import QApplication DEFAULT_INPUT_FILE_PATH = "input.txt" class Simulation: """ Simple class used to organized things better. """ def __init__(self, input_file, logs=False, gui=False): self.logs = logs self.gui = False self.parser = Parser(input_file) self.environment = None self.mowers = [] self._setup() def _setup(self): """ Parse info and instructions using the Parser. Create the environment and the mowers """ self.parser.parse() self.width, self.height = self.parser.grid_size self.environment = Environment(self.width, self.height) # Creating mowers for mower_dict in self.parser.mowers: new_mower = Mower( **mower_dict, environment=self.environment, logs=self.logs) self.mowers.append(new_mower) def setup_gui(self): """ Create the GUI application and connect its start signal to the thread creation @return: QWidget. Widget that hold the field and buttons to play with simulation """ self.gui = App(self.width, self.height, self.environment, self.mowers) self.gui.start.connect(self.setup_thread) return gui def setup_thread(self): """ Create a thread to run the simulation. It's needed when GUI is needed. """ thread = Thread(target=self.run) thread.start() def run(self): """ Run the simulation. It basicaly means to iterate over all mower's instructions sequentialy. It print the mower position and its orientation after last instruction. It also update the gui if needed. """ for m in self.mowers: for p, o in m: if self.gui: time.sleep(0.2) self.gui.redraw() # Print output print("{} {} {}".format(*p, o)) # Entrypoint if __name__ == '__main__': logs = False gui = False # CLI for index, arg in enumerate(sys.argv): if arg in ['--logs', '-l']: logs = True # Configure logger logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) if arg in ['--gui']: gui = True # Create the simulation simulation = Simulation(DEFAULT_INPUT_FILE_PATH, logs=logs) if gui: app = QApplication(sys.argv) widget = simulation.setup_gui() sys.exit(app.exec_()) else: simulation.run()
tb_gateway_service.py
# Copyright 2022. ThingsBoard # # 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 logging import logging.config import logging.handlers from copy import deepcopy from os import execv, listdir, path, pathsep, stat, system from queue import SimpleQueue from random import choice from string import ascii_lowercase, hexdigits from sys import argv, executable, getsizeof from threading import RLock, Thread from time import sleep, time from simplejson import JSONDecodeError, dumps, load, loads from yaml import safe_load from thingsboard_gateway.gateway.constant_enums import DeviceActions, Status from thingsboard_gateway.gateway.constants import CONNECTED_DEVICES_FILENAME, CONNECTOR_PARAMETER, PERSISTENT_GRPC_CONNECTORS_KEY_FILENAME from thingsboard_gateway.gateway.tb_client import TBClient from thingsboard_gateway.storage.file.file_event_storage import FileEventStorage from thingsboard_gateway.storage.memory.memory_event_storage import MemoryEventStorage from thingsboard_gateway.storage.sqlite.sqlite_event_storage import SQLiteEventStorage from thingsboard_gateway.tb_utility.tb_gateway_remote_configurator import RemoteConfigurator from thingsboard_gateway.tb_utility.tb_loader import TBModuleLoader from thingsboard_gateway.tb_utility.tb_logger import TBLoggerHandler from thingsboard_gateway.tb_utility.tb_remote_shell import RemoteShell from thingsboard_gateway.tb_utility.tb_updater import TBUpdater from thingsboard_gateway.tb_utility.tb_utility import TBUtility GRPC_LOADED = False try: from thingsboard_gateway.gateway.grpc_service.grpc_connector import GrpcConnector from thingsboard_gateway.gateway.grpc_service.tb_grpc_manager import TBGRPCServerManager GRPC_LOADED = True except ImportError: print("Cannot load GRPC connector!") log = logging.getLogger('service') main_handler = logging.handlers.MemoryHandler(-1) DEFAULT_CONNECTORS = { "mqtt": "MqttConnector", "modbus": "ModbusConnector", "opcua": "OpcUaConnector", "ble": "BLEConnector", "request": "RequestConnector", "can": "CanConnector", "bacnet": "BACnetConnector", "odbc": "OdbcConnector", "rest": "RESTConnector", "snmp": "SNMPConnector", "ftp": "FTPConnector", "socket": "SocketConnector" } def load_file(path_to_file): content = None with open(path_to_file, 'r') as target_file: content = load(target_file) return content class TBGatewayService: def __init__(self, config_file=None): self.stopped = False self.__lock = RLock() self.async_device_actions = { DeviceActions.CONNECT: self.add_device, DeviceActions.DISCONNECT: self.del_device } self.__async_device_actions_queue = SimpleQueue() self.__process_async_actions_thread = Thread(target=self.__process_async_device_actions, name="Async device actions processing thread", daemon=True) if config_file is None: config_file = path.dirname(path.dirname(path.abspath(__file__))) + '/config/tb_gateway.yaml'.replace('/', path.sep) with open(config_file) as general_config: self.__config = safe_load(general_config) self._config_dir = path.dirname(path.abspath(config_file)) + path.sep logging_error = None try: logging.config.fileConfig(self._config_dir + "logs.conf", disable_existing_loggers=False) except Exception as e: logging_error = e global log log = logging.getLogger('service') log.info("Gateway starting...") self.__updater = TBUpdater() self.__updates_check_period_ms = 300000 self.__updates_check_time = 0 self.version = self.__updater.get_version() log.info("ThingsBoard IoT gateway version: %s", self.version["current_version"]) self.available_connectors = {} self.__connector_incoming_messages = {} self.__connected_devices = {} self.__renamed_devices = {} self.__saved_devices = {} self.__events = [] self.name = ''.join(choice(ascii_lowercase) for _ in range(64)) self.__rpc_register_queue = SimpleQueue() self.__rpc_requests_in_progress = {} self.tb_client = TBClient(self.__config["thingsboard"], self._config_dir) try: self.tb_client.disconnect() except Exception as e: log.exception(e) self.tb_client.connect() self.subscribe_to_required_topics() self.__subscribed_to_rpc_topics = True if logging_error is not None: self.tb_client.client.send_telemetry({"ts": time() * 1000, "values": { "LOGS": "Logging loading exception, logs.conf is wrong: %s" % (str(logging_error),)}}) TBLoggerHandler.set_default_handler() self.counter = 0 self.__rpc_reply_sent = False global main_handler self.main_handler = main_handler self.remote_handler = TBLoggerHandler(self) self.main_handler.setTarget(self.remote_handler) self._default_connectors = DEFAULT_CONNECTORS self.__converted_data_queue = SimpleQueue() self.__save_converted_data_thread = Thread(name="Save converted data", daemon=True, target=self.__send_to_storage) self.__save_converted_data_thread.start() self._implemented_connectors = {} self._event_storage_types = { "memory": MemoryEventStorage, "file": FileEventStorage, "sqlite": SQLiteEventStorage, } self.__gateway_rpc_methods = { "ping": self.__rpc_ping, "stats": self.__form_statistics, "devices": self.__rpc_devices, "update": self.__rpc_update, "version": self.__rpc_version, "device_renamed": self.__process_renamed_gateway_devices, "device_deleted": self.__process_deleted_gateway_devices, } self.__remote_shell = None if self.__config["thingsboard"].get("remoteShell"): log.warning("Remote shell is enabled. Please be carefully with this feature.") self.__remote_shell = RemoteShell(platform=self.__updater.get_platform(), release=self.__updater.get_release()) self.__rpc_remote_shell_command_in_progress = None self.__scheduled_rpc_calls = [] self.__rpc_processing_queue = SimpleQueue() self.__rpc_scheduled_methods_functions = { "restart": {"function": execv, "arguments": (executable, [executable.split(pathsep)[-1]] + argv)}, "reboot": {"function": system, "arguments": ("reboot 0",)}, } self.__rpc_processing_thread = Thread(target=self.__send_rpc_reply_processing, daemon=True, name="RPC processing thread") self.__rpc_processing_thread.start() self._event_storage = self._event_storage_types[self.__config["storage"]["type"]](self.__config["storage"]) self.connectors_configs = {} self.__remote_configurator = None self.__request_config_after_connect = False self.__load_persistent_devices() self.__init_remote_configuration() self.__grpc_config = self.__config.get('grpc') self.__grpc_manager = None self.__grpc_connectors = {} if GRPC_LOADED and self.__grpc_config is not None and self.__grpc_config.get("enabled"): self.__process_async_actions_thread.start() self.__grpc_manager = TBGRPCServerManager(self, self.__grpc_config) self.__grpc_manager.set_gateway_read_callbacks(self.__register_connector, self.__unregister_connector) self._load_connectors() self._connect_with_connectors() self.__load_persistent_devices() self._published_events = SimpleQueue() self._send_thread = Thread(target=self.__read_data_from_storage, daemon=True, name="Send data to Thingsboard Thread") self._send_thread.start() self.__min_pack_send_delay_ms = self.__config['thingsboard'].get('minPackSendDelayMS', 500) / 1000.0 log.info("Gateway started.") try: gateway_statistic_send = 0 connectors_configuration_check_time = 0 while not self.stopped: cur_time = time() * 1000 if not self.tb_client.is_connected() and self.__subscribed_to_rpc_topics: self.__subscribed_to_rpc_topics = False if self.tb_client.is_connected() and not self.__subscribed_to_rpc_topics: for device in self.__saved_devices: self.add_device(device, {"connector": self.__saved_devices[device]["connector"]}, device_type=self.__saved_devices[device]["device_type"]) self.subscribe_to_required_topics() self.__subscribed_to_rpc_topics = True if self.__scheduled_rpc_calls: for rpc_call_index in range(len(self.__scheduled_rpc_calls)): rpc_call = self.__scheduled_rpc_calls[rpc_call_index] if cur_time > rpc_call[0]: rpc_call = self.__scheduled_rpc_calls.pop(rpc_call_index) result = None try: result = rpc_call[1]["function"](*rpc_call[1]["arguments"]) except Exception as e: log.exception(e) if result == 256: log.warning("Error on RPC command: 256. Permission denied.") if (self.__rpc_requests_in_progress or not self.__rpc_register_queue.empty()) and self.tb_client.is_connected(): new_rpc_request_in_progress = {} if self.__rpc_requests_in_progress: for rpc_in_progress, data in self.__rpc_requests_in_progress.items(): if cur_time >= data[1]: data[2](rpc_in_progress) self.cancel_rpc_request(rpc_in_progress) self.__rpc_requests_in_progress[rpc_in_progress] = "del" new_rpc_request_in_progress = {key: value for key, value in self.__rpc_requests_in_progress.items() if value != 'del'} if not self.__rpc_register_queue.empty(): rpc_request_from_queue = self.__rpc_register_queue.get(False) topic = rpc_request_from_queue["topic"] data = rpc_request_from_queue["data"] new_rpc_request_in_progress[topic] = data self.__rpc_requests_in_progress = new_rpc_request_in_progress else: try: sleep(0.2) except Exception as e: log.exception(e) break if not self.__request_config_after_connect and self.tb_client.is_connected() and not self.tb_client.client.get_subscriptions_in_progress(): self.__request_config_after_connect = True self.__check_shared_attributes() if cur_time - gateway_statistic_send > self.__config["thingsboard"].get("statsSendPeriodInSeconds", 3600) * 1000 and self.tb_client.is_connected(): summary_messages = self.__form_statistics() # with self.__lock: self.tb_client.client.send_telemetry(summary_messages) gateway_statistic_send = time() * 1000 # self.__check_shared_attributes() if cur_time - connectors_configuration_check_time > self.__config["thingsboard"].get( "checkConnectorsConfigurationInSeconds", 60) * 1000: self.check_connector_configuration_updates() connectors_configuration_check_time = time() * 1000 if cur_time - self.__updates_check_time >= self.__updates_check_period_ms: self.__updates_check_time = time() * 1000 self.version = self.__updater.get_version() except KeyboardInterrupt: self.__stop_gateway() except Exception as e: log.exception(e) self.__stop_gateway() self.__close_connectors() log.info("The gateway has been stopped.") self.tb_client.stop() def __close_connectors(self): for current_connector in self.available_connectors: try: self.available_connectors[current_connector].close() log.debug("Connector %s closed connection.", current_connector) except Exception as e: log.exception(e) def __stop_gateway(self): self.stopped = True self.__updater.stop() log.info("Stopping...") if self.__grpc_manager is not None: self.__grpc_manager.stop() self.__close_connectors() self._event_storage.stop() log.info("The gateway has been stopped.") self.tb_client.disconnect() self.tb_client.stop() def __init_remote_configuration(self, force=False): if (self.__config["thingsboard"].get("remoteConfiguration") or force) and self.__remote_configurator is None: try: self.__remote_configurator = RemoteConfigurator(self, self.__config) if self.tb_client.is_connected() and not self.tb_client.client.get_subscriptions_in_progress(): self.__check_shared_attributes() except Exception as e: log.exception(e) if self.__remote_configurator is not None: self.__remote_configurator.send_current_configuration() def _attributes_parse(self, content, *args): try: log.debug("Received data: %s", content) if content is not None: shared_attributes = content.get("shared", {}) client_attributes = content.get("client", {}) if shared_attributes or client_attributes: self.__process_attributes_response(shared_attributes, client_attributes) else: self.__process_attribute_update(content) if shared_attributes: log.debug("Shared attributes received (%s).", ", ".join([attr for attr in shared_attributes.keys()])) if client_attributes: log.debug("Client attributes received (%s).", ", ".join([attr for attr in client_attributes.keys()])) except Exception as e: log.exception(e) def __process_attribute_update(self, content): self.__process_remote_logging_update(content.get("RemoteLoggingLevel")) self.__process_remote_configuration(content.get("configuration")) def __process_attributes_response(self, shared_attributes, client_attributes): self.__process_remote_logging_update(shared_attributes.get('RemoteLoggingLevel')) self.__process_remote_configuration(shared_attributes.get("configuration")) def __process_remote_logging_update(self, remote_logging_level): if remote_logging_level == 'NONE': self.remote_handler.deactivate() log.info('Remote logging has being deactivated.') elif remote_logging_level is not None: if self.remote_handler.current_log_level != remote_logging_level or not self.remote_handler.activated: self.main_handler.setLevel(remote_logging_level) self.remote_handler.activate(remote_logging_level) log.info('Remote logging has being updated. Current logging level is: %s ', remote_logging_level) def __process_deleted_gateway_devices(self, deleted_device_name: str): log.info("Received deleted gateway device notification: %s", deleted_device_name) if deleted_device_name in list(self.__renamed_devices.values()): first_device_name = TBUtility.get_dict_key_by_value(self.__renamed_devices, deleted_device_name) del self.__renamed_devices[first_device_name] deleted_device_name = first_device_name log.debug("Current renamed_devices dict: %s", self.__renamed_devices) if deleted_device_name in self.__connected_devices: del self.__connected_devices[deleted_device_name] log.debug("Device %s - was removed", deleted_device_name) self.__save_persistent_devices() self.__load_persistent_devices() def __process_renamed_gateway_devices(self, renamed_device: dict): if self.__config.get('handleDeviceRenaming', True): log.info("Received renamed gateway device notification: %s", renamed_device) old_device_name, new_device_name = renamed_device.popitem() if old_device_name in list(self.__renamed_devices.values()): device_name_key = TBUtility.get_dict_key_by_value(self.__renamed_devices, old_device_name) else: device_name_key = new_device_name self.__renamed_devices[device_name_key] = new_device_name self.__save_persistent_devices() self.__load_persistent_devices() log.debug("Current renamed_devices dict: %s", self.__renamed_devices) else: log.debug("Received renamed device notification %r, but device renaming handle is disabled", renamed_device) def __process_remote_configuration(self, new_configuration): if new_configuration is not None and self.__remote_configurator is not None: try: self.__remote_configurator.process_configuration(new_configuration) self.__remote_configurator.send_current_configuration() except Exception as e: log.exception(e) def get_config_path(self): return self._config_dir def subscribe_to_required_topics(self): self.tb_client.client.clean_device_sub_dict() self.tb_client.client.gw_set_server_side_rpc_request_handler(self._rpc_request_handler) self.tb_client.client.set_server_side_rpc_request_handler(self._rpc_request_handler) self.tb_client.client.subscribe_to_all_attributes(self._attribute_update_callback) self.tb_client.client.gw_subscribe_to_all_attributes(self._attribute_update_callback) def __check_shared_attributes(self): self.tb_client.client.request_attributes(callback=self._attributes_parse) def __register_connector(self, session_id, connector_key): if self.__grpc_connectors.get(connector_key) is not None and self.__grpc_connectors[connector_key]['name'] not in self.available_connectors: target_connector = self.__grpc_connectors.get(connector_key) connector = GrpcConnector(self, target_connector['config'], self.__grpc_manager, session_id) connector.setName(target_connector['name']) self.available_connectors[connector.get_name()] = connector self.__grpc_manager.registration_finished(Status.SUCCESS, session_id, target_connector) log.info("GRPC connector with key %s registered with name %s", connector_key, connector.get_name()) elif self.__grpc_connectors.get(connector_key) is not None: self.__grpc_manager.registration_finished(Status.FAILURE, session_id, None) log.error("GRPC connector with key: %s - already registered!", connector_key) else: self.__grpc_manager.registration_finished(Status.NOT_FOUND, session_id, None) log.error("GRPC configuration for connector with key: %s - not found", connector_key) def __unregister_connector(self, session_id, connector_key): if self.__grpc_connectors.get(connector_key) is not None and self.__grpc_connectors[connector_key]['name'] in self.available_connectors: connector_name = self.__grpc_connectors[connector_key]['name'] target_connector: GrpcConnector = self.available_connectors.pop(connector_name) self.__grpc_manager.unregister(Status.SUCCESS, session_id, target_connector) log.info("GRPC connector with key %s and name %s - unregistered", connector_key, target_connector.get_name()) elif self.__grpc_connectors.get(connector_key) is not None: self.__grpc_manager.unregister(Status.NOT_FOUND, session_id, None) log.error("GRPC connector with key: %s - is not registered!", connector_key) else: self.__grpc_manager.unregister(Status.FAILURE, session_id, None) log.error("GRPC configuration for connector with key: %s - not found in configuration and not registered", connector_key) def _load_connectors(self): self.connectors_configs = {} connectors_persistent_keys = self.__load_persistent_connector_keys() if self.__config.get("connectors"): for connector in self.__config['connectors']: try: connector_persistent_key = None if connector['type'] == "grpc" and self.__grpc_manager is None: log.error("Cannot load connector with name: %s and type grpc. GRPC server is disabled!", connector['name']) continue if connector['type'] != "grpc": connector_class = TBModuleLoader.import_module(connector['type'], self._default_connectors.get(connector['type'], connector.get('class'))) self._implemented_connectors[connector['type']] = connector_class elif connector['type'] == "grpc": if connector.get('key') == "auto": if connectors_persistent_keys and connectors_persistent_keys.get(connector['name']) is not None: connector_persistent_key = connectors_persistent_keys[connector['name']] else: connector_persistent_key = "".join(choice(hexdigits) for _ in range(10)) connectors_persistent_keys[connector['name']] = connector_persistent_key else: connector_persistent_key = connector['key'] log.info("Connector key for GRPC connector with name [%s] is: [%s]", connector['name'], connector_persistent_key) config_file_path = self._config_dir + connector['configuration'] connector_conf_file_data = '' with open(config_file_path, 'r', encoding="UTF-8") as conf_file: connector_conf_file_data = conf_file.read() connector_conf = connector_conf_file_data try: connector_conf = loads(connector_conf_file_data) except JSONDecodeError as e: log.debug(e) log.warning("Cannot parse connector configuration as a JSON, it will be passed as a string.") if not self.connectors_configs.get(connector['type']): self.connectors_configs[connector['type']] = [] if connector['type'] != 'grpc' and isinstance(connector_conf, dict): connector_conf["name"] = connector['name'] self.connectors_configs[connector['type']].append({"name": connector['name'], "config": {connector['configuration']: connector_conf} if connector[ 'type'] != 'grpc' else connector_conf, "config_updated": stat(config_file_path), "config_file_path": config_file_path, "grpc_key": connector_persistent_key}) except Exception as e: log.exception("Error on loading connector: %r", e) if connectors_persistent_keys: self.__save_persistent_keys(connectors_persistent_keys) else: log.error("Connectors - not found! Check your configuration!") self.__init_remote_configuration(force=True) log.info("Remote configuration is enabled forcibly!") def _connect_with_connectors(self): for connector_type in self.connectors_configs: for connector_config in self.connectors_configs[connector_type]: if connector_type.lower() != 'grpc': for config in connector_config["config"]: connector = None try: if connector_config["config"][config] is not None: if self._implemented_connectors[connector_type]: connector = self._implemented_connectors[connector_type](self, connector_config["config"][config], connector_type) connector.setName(connector_config["name"]) self.available_connectors[connector.get_name()] = connector connector.open() else: log.warning("Connector implementation not found for %s", connector_config["name"]) else: log.info("Config not found for %s", connector_type) except Exception as e: log.exception(e) if connector is not None: connector.close() else: self.__grpc_connectors.update({connector_config['grpc_key']: connector_config}) def check_connector_configuration_updates(self): configuration_changed = False for connector_type in self.connectors_configs: for connector_config in self.connectors_configs[connector_type]: if stat(connector_config["config_file_path"]) != connector_config["config_updated"]: configuration_changed = True break if configuration_changed: break if configuration_changed: self.__close_connectors() self._load_connectors() self._connect_with_connectors() def send_to_storage(self, connector_name, data): try: self.__converted_data_queue.put((connector_name, data), True, 100) return Status.SUCCESS except Exception as e: log.exception("Cannot put converted data!", e) return Status.FAILURE def __send_to_storage(self): while True: try: if not self.__converted_data_queue.empty(): connector_name, event = self.__converted_data_queue.get(True, 100) data_array = event if isinstance(event, list) else [event] for data in data_array: if not connector_name == self.name: if 'telemetry' not in data: data['telemetry'] = [] if 'attributes' not in data: data['attributes'] = [] if not TBUtility.validate_converted_data(data): log.error("Data from %s connector is invalid.", connector_name) continue if data.get('deviceType') is None: device_name = data['deviceName'] if self.__connected_devices.get(device_name) is not None: data["deviceType"] = self.__connected_devices[device_name]['device_type'] elif self.__saved_devices.get(device_name) is not None: data["deviceType"] = self.__saved_devices[device_name]['device_type'] else: data["deviceType"] = "default" if data["deviceName"] not in self.get_devices() and self.tb_client.is_connected(): self.add_device(data["deviceName"], {"connector": self.available_connectors[connector_name]}, device_type=data["deviceType"]) if not self.__connector_incoming_messages.get(connector_name): self.__connector_incoming_messages[connector_name] = 0 else: self.__connector_incoming_messages[connector_name] += 1 else: data["deviceName"] = "currentThingsBoardGateway" data = self.__convert_telemetry_to_ts(data) max_data_size = self.__config["thingsboard"].get("maxPayloadSizeBytes", 1024) if self.__get_data_size(data) >= max_data_size: adopted_data = {"deviceName": data['deviceName'], "deviceType": data['deviceType'], "attributes": {}, "telemetry": []} for attribute in data['attributes']: adopted_data_size = self.__get_data_size(adopted_data) if adopted_data_size >= max_data_size: self.__send_data_pack_to_storage(adopted_data, connector_name) adopted_data['attributes'] = {} adopted_data['attributes'].update({attribute: data['attributes'][attribute]}) for ts_kv_list in data['telemetry']: ts = ts_kv_list['ts'] for kv in ts_kv_list['values']: adopted_data_size = self.__get_data_size(adopted_data) if adopted_data_size >= max_data_size: self.__send_data_pack_to_storage(adopted_data, connector_name) adopted_data['telemetry'] = [] if len(adopted_data['telemetry']) == 0: adopted_data['telemetry'] = [{'ts': ts, 'values': {kv: ts_kv_list['values'][kv]}}] else: for adopted_kv in adopted_data['telemetry']: if adopted_kv['ts'] == ts: adopted_kv['values'].update({kv: ts_kv_list['values'][kv]}) else: self.__send_data_pack_to_storage(data, connector_name) else: sleep(0.2) except Exception as e: log.error(e) @staticmethod def __get_data_size(data: dict): return getsizeof(str(data)) @staticmethod def __convert_telemetry_to_ts(data): telemetry = {} telemetry_with_ts = [] for item in data["telemetry"]: if item.get("ts") is None: telemetry = {**telemetry, **item} else: telemetry_with_ts.append({"ts": item["ts"], "values": {**item["values"]}}) if telemetry_with_ts: data["telemetry"] = telemetry_with_ts elif len(data['telemetry']) > 0: data["telemetry"] = {"ts": int(time() * 1000), "values": telemetry} return data def __send_data_pack_to_storage(self, data, connector_name): json_data = dumps(data) save_result = self._event_storage.put(json_data) if not save_result: log.error('Data from the device "%s" cannot be saved, connector name is %s.', data["deviceName"], connector_name) def check_size(self, devices_data_in_event_pack): if self.__get_data_size(devices_data_in_event_pack) >= self.__config["thingsboard"].get("maxPayloadSizeBytes", 1024): self.__send_data(devices_data_in_event_pack) for device in devices_data_in_event_pack: devices_data_in_event_pack[device]["telemetry"] = [] devices_data_in_event_pack[device]["attributes"] = {} def __read_data_from_storage(self): devices_data_in_event_pack = {} log.debug("Send data Thread has been started successfully.") while not self.stopped: try: if self.tb_client.is_connected(): size = self.__get_data_size(devices_data_in_event_pack) - 2 events = [] if self.__remote_configurator is None or not self.__remote_configurator.in_process: events = self._event_storage.get_event_pack() if events: for event in events: self.counter += 1 try: current_event = loads(event) except Exception as e: log.exception(e) continue if not devices_data_in_event_pack.get(current_event["deviceName"]): devices_data_in_event_pack[current_event["deviceName"]] = {"telemetry": [], "attributes": {}} if current_event.get("telemetry"): if isinstance(current_event["telemetry"], list): for item in current_event["telemetry"]: self.check_size(devices_data_in_event_pack) devices_data_in_event_pack[current_event["deviceName"]]["telemetry"].append( item) else: self.check_size(devices_data_in_event_pack) devices_data_in_event_pack[current_event["deviceName"]]["telemetry"].append( current_event["telemetry"]) if current_event.get("attributes"): if isinstance(current_event["attributes"], list): for item in current_event["attributes"]: self.check_size(devices_data_in_event_pack) devices_data_in_event_pack[current_event["deviceName"]]["attributes"].update( item.items()) else: self.check_size(devices_data_in_event_pack) devices_data_in_event_pack[current_event["deviceName"]]["attributes"].update( current_event["attributes"].items()) if devices_data_in_event_pack: if not self.tb_client.is_connected(): continue while self.__rpc_reply_sent: sleep(.2) self.__send_data(devices_data_in_event_pack) sleep(self.__min_pack_send_delay_ms) if self.tb_client.is_connected() and ( self.__remote_configurator is None or not self.__remote_configurator.in_process): success = True while not self._published_events.empty(): if (self.__remote_configurator is not None and self.__remote_configurator.in_process) or \ not self.tb_client.is_connected() or \ self._published_events.empty() or \ self.__rpc_reply_sent: success = False break event = self._published_events.get(False, 10) try: if self.tb_client.is_connected() and ( self.__remote_configurator is None or not self.__remote_configurator.in_process): if self.tb_client.client.quality_of_service == 1: success = event.get() == event.TB_ERR_SUCCESS else: success = True else: break except Exception as e: log.exception(e) success = False sleep(0.2) if success and self.tb_client.is_connected(): self._event_storage.event_pack_processing_done() del devices_data_in_event_pack devices_data_in_event_pack = {} else: continue else: sleep(0.2) else: sleep(0.2) except Exception as e: log.exception(e) sleep(1) def __send_data(self, devices_data_in_event_pack): try: for device in devices_data_in_event_pack: final_device_name = device if self.__renamed_devices.get(device) is None else self.__renamed_devices[device] if devices_data_in_event_pack[device].get("attributes"): if device == self.name or device == "currentThingsBoardGateway": self._published_events.put( self.tb_client.client.send_attributes(devices_data_in_event_pack[device]["attributes"])) else: self._published_events.put(self.tb_client.client.gw_send_attributes(final_device_name, devices_data_in_event_pack[ device]["attributes"])) if devices_data_in_event_pack[device].get("telemetry"): if device == self.name or device == "currentThingsBoardGateway": self._published_events.put( self.tb_client.client.send_telemetry(devices_data_in_event_pack[device]["telemetry"])) else: self._published_events.put(self.tb_client.client.gw_send_telemetry(final_device_name, devices_data_in_event_pack[ device]["telemetry"])) devices_data_in_event_pack[device] = {"telemetry": [], "attributes": {}} except Exception as e: log.exception(e) def _rpc_request_handler(self, request_id, content): try: device = content.get("device") if device is not None: connector_name = self.get_devices()[device].get("connector") if connector_name is not None: connector_name.server_side_rpc_handler(content) else: log.error("Received RPC request but connector for the device %s not found. Request data: \n %s", content["device"], dumps(content)) else: try: method_split = content["method"].split('_') module = None if len(method_split) > 0: module = method_split[0] if module is not None: result = None if self.connectors_configs.get(module): log.debug("Connector \"%s\" for RPC request \"%s\" found", module, content["method"]) for connector_name in self.available_connectors: if self.available_connectors[connector_name]._connector_type == module: log.debug("Sending command RPC %s to connector %s", content["method"], connector_name) result = self.available_connectors[connector_name].server_side_rpc_handler(content) elif module == 'gateway' or module in self.__remote_shell.shell_commands: result = self.__rpc_gateway_processing(request_id, content) else: log.error("Connector \"%s\" not found", module) result = {"error": "%s - connector not found in available connectors." % module, "code": 404} if result is None: self.send_rpc_reply(None, request_id, success_sent=False) elif "qos" in result: self.send_rpc_reply(None, request_id, dumps({k: v for k, v in result.items() if k != "qos"}), quality_of_service=result["qos"]) else: self.send_rpc_reply(None, request_id, dumps(result)) except Exception as e: self.send_rpc_reply(None, request_id, "{\"error\":\"%s\", \"code\": 500}" % str(e)) log.exception(e) except Exception as e: log.exception(e) def __rpc_gateway_processing(self, request_id, content): log.info("Received RPC request to the gateway, id: %s, method: %s", str(request_id), content["method"]) arguments = content.get('params', {}) method_to_call = content["method"].replace("gateway_", "") result = None if self.__remote_shell is not None: method_function = self.__remote_shell.shell_commands.get(method_to_call, self.__gateway_rpc_methods.get(method_to_call)) else: log.info("Remote shell is disabled.") method_function = self.__gateway_rpc_methods.get(method_to_call) if method_function is None and method_to_call in self.__rpc_scheduled_methods_functions: seconds_to_restart = arguments * 1000 if arguments and arguments != '{}' else 0 self.__scheduled_rpc_calls.append( [time() * 1000 + seconds_to_restart, self.__rpc_scheduled_methods_functions[method_to_call]]) log.info("Gateway %s scheduled in %i seconds", method_to_call, seconds_to_restart / 1000) result = {"success": True} elif method_function is None: log.error("RPC method %s - Not found", content["method"]) return {"error": "Method not found", "code": 404} elif isinstance(arguments, list): result = method_function(*arguments) elif arguments: result = method_function(arguments) else: result = method_function() return result @staticmethod def __rpc_ping(*args): return {"code": 200, "resp": "pong"} def __rpc_devices(self, *args): data_to_send = {} for device in self.__connected_devices: if self.__connected_devices[device]["connector"] is not None: data_to_send[device] = self.__connected_devices[device]["connector"].get_name() return {"code": 200, "resp": data_to_send} def __rpc_update(self, *args): try: result = {"resp": self.__updater.update(), "code": 200, } except Exception as e: result = {"error": str(e), "code": 500 } return result def __rpc_version(self, *args): try: result = {"resp": self.__updater.get_version(), "code": 200, } except Exception as e: result = {"error": str(e), "code": 500 } return result def is_rpc_in_progress(self, topic): return topic in self.__rpc_requests_in_progress def rpc_with_reply_processing(self, topic, content): req_id = self.__rpc_requests_in_progress[topic][0]["data"]["id"] device = self.__rpc_requests_in_progress[topic][0]["device"] log.info("Outgoing RPC. Device: %s, ID: %d", device, req_id) self.send_rpc_reply(device, req_id, content) def send_rpc_reply(self, device=None, req_id=None, content=None, success_sent=None, wait_for_publish=None, quality_of_service=0): self.__rpc_processing_queue.put((device, req_id, content, success_sent, wait_for_publish, quality_of_service)) def __send_rpc_reply_processing(self): while not self.stopped: if not self.__rpc_processing_queue.empty(): args = self.__rpc_processing_queue.get() self.__send_rpc_reply(*args) else: sleep(.1) def __send_rpc_reply(self, device=None, req_id=None, content=None, success_sent=None, wait_for_publish=None, quality_of_service=0): try: self.__rpc_reply_sent = True rpc_response = {"success": False} if success_sent is not None: if success_sent: rpc_response["success"] = True if device is not None and success_sent is not None: self.tb_client.client.gw_send_rpc_reply(device, req_id, dumps(rpc_response), quality_of_service=quality_of_service) elif device is not None and req_id is not None and content is not None: self.tb_client.client.gw_send_rpc_reply(device, req_id, content, quality_of_service=quality_of_service) elif device is None and success_sent is not None: self.tb_client.client.send_rpc_reply(req_id, dumps(rpc_response), quality_of_service=quality_of_service, wait_for_publish=wait_for_publish) elif device is None and content is not None: self.tb_client.client.send_rpc_reply(req_id, content, quality_of_service=quality_of_service, wait_for_publish=wait_for_publish) self.__rpc_reply_sent = False except Exception as e: log.exception(e) def register_rpc_request_timeout(self, content, timeout, topic, cancel_method): # Put request in outgoing RPC queue. It will be eventually dispatched. self.__rpc_register_queue.put({"topic": topic, "data": (content, timeout, cancel_method)}, False) def cancel_rpc_request(self, rpc_request): content = self.__rpc_requests_in_progress[rpc_request][0] self.send_rpc_reply(device=content["device"], req_id=content["data"]["id"], success_sent=False) def _attribute_update_callback(self, content, *args): log.debug("Attribute request received with content: \"%s\"", content) log.debug(args) if content.get('device') is not None: try: self.__connected_devices[content["device"]]["connector"].on_attributes_update(content) except Exception as e: log.exception(e) else: self._attributes_parse(content) def __form_statistics(self): summary_messages = {"eventsProduced": 0, "eventsSent": 0} telemetry = {} for connector in self.available_connectors: connector_camel_case = connector.lower().replace(' ', '') telemetry[(connector_camel_case + ' EventsProduced').replace(' ', '')] = \ self.available_connectors[connector].statistics['MessagesReceived'] self.available_connectors[connector].statistics['MessagesReceived'] = 0 telemetry[(connector_camel_case + ' EventsSent').replace(' ', '')] = \ self.available_connectors[connector].statistics['MessagesSent'] self.available_connectors[connector].statistics['MessagesSent'] = 0 summary_messages['eventsProduced'] += telemetry[ str(connector_camel_case + ' EventsProduced').replace(' ', '')] summary_messages['eventsSent'] += telemetry[ str(connector_camel_case + ' EventsSent').replace(' ', '')] summary_messages.update(**telemetry) return summary_messages def add_device_async(self, data): if data['deviceName'] not in self.__saved_devices: self.__async_device_actions_queue.put((DeviceActions.CONNECT, data)) return Status.SUCCESS else: return Status.FAILURE def add_device(self, device_name, content, device_type=None): if device_name not in self.__saved_devices: device_type = device_type if device_type is not None else 'default' self.__connected_devices[device_name] = {**content, "device_type": device_type} self.__saved_devices[device_name] = {**content, "device_type": device_type} self.__save_persistent_devices() self.tb_client.client.gw_connect_device(device_name, device_type) def update_device(self, device_name, event, content): if event == 'connector' and self.__connected_devices[device_name].get(event) != content: self.__save_persistent_devices() self.__connected_devices[device_name][event] = content def del_device_async(self, data): if data['deviceName'] in self.__saved_devices: self.__async_device_actions_queue.put((DeviceActions.DISCONNECT, data)) return Status.SUCCESS else: return Status.FAILURE def del_device(self, device_name): del self.__connected_devices[device_name] del self.__saved_devices[device_name] self.tb_client.client.gw_disconnect_device(device_name) self.__save_persistent_devices() def get_devices(self): return self.__connected_devices def __process_async_device_actions(self): while not self.stopped: if not self.__async_device_actions_queue.empty(): action, data = self.__async_device_actions_queue.get() if action == DeviceActions.CONNECT: self.add_device(data['deviceName'], {CONNECTOR_PARAMETER: self.available_connectors[data['name']]}, data.get('deviceType')) elif action == DeviceActions.DISCONNECT: self.del_device(data['deviceName']) else: sleep(.2) def __load_persistent_connector_keys(self): persistent_keys = {} if PERSISTENT_GRPC_CONNECTORS_KEY_FILENAME in listdir(self._config_dir) and \ path.getsize(self._config_dir + PERSISTENT_GRPC_CONNECTORS_KEY_FILENAME) > 0: try: persistent_keys = load_file(self._config_dir + PERSISTENT_GRPC_CONNECTORS_KEY_FILENAME) except Exception as e: log.exception(e) log.debug("Loaded keys: %s", persistent_keys) else: log.debug("Persistent keys file not found") return persistent_keys def __save_persistent_keys(self, persistent_keys): try: with open(self._config_dir + PERSISTENT_GRPC_CONNECTORS_KEY_FILENAME, 'w') as persistent_keys_file: persistent_keys_file.write(dumps(persistent_keys, indent=2, sort_keys=True)) except Exception as e: log.exception(e) def __load_persistent_devices(self): devices = None if CONNECTED_DEVICES_FILENAME in listdir(self._config_dir) and \ path.getsize(self._config_dir + CONNECTED_DEVICES_FILENAME) > 0: try: devices = load_file(self._config_dir + CONNECTED_DEVICES_FILENAME) except Exception as e: log.exception(e) else: open(self._config_dir + CONNECTED_DEVICES_FILENAME, 'w').close() if devices is not None: log.debug("Loaded devices:\n %s", devices) for device_name in devices: try: if not isinstance(devices[device_name], list): open(self._config_dir + CONNECTED_DEVICES_FILENAME, 'w').close() log.debug("Old connected_devices file, new file will be created") return if self.available_connectors.get(devices[device_name][0]): device_data_to_save = { "connector": self.available_connectors[devices[device_name][0]], "device_type": devices[device_name][1]} if len(devices[device_name]) > 2 and device_name not in self.__renamed_devices: new_device_name = devices[device_name][2] self.__renamed_devices[device_name] = new_device_name self.__connected_devices[device_name] = device_data_to_save self.__saved_devices[device_name] = device_data_to_save except Exception as e: log.exception(e) continue else: log.debug("No device found in connected device file.") self.__connected_devices = {} if self.__connected_devices is None else self.__connected_devices def __save_persistent_devices(self): data_to_save = {} for device in self.__connected_devices: if self.__connected_devices[device]["connector"] is not None: data_to_save[device] = [self.__connected_devices[device]["connector"].get_name(), self.__connected_devices[device]["device_type"]] if device in self.__renamed_devices: data_to_save[device].append(self.__renamed_devices.get(device)) with open(self._config_dir + CONNECTED_DEVICES_FILENAME, 'w') as config_file: try: config_file.write(dumps(data_to_save, indent=2, sort_keys=True)) except Exception as e: log.exception(e) log.debug("Saved connected devices.") if __name__ == '__main__': TBGatewayService( path.dirname(path.dirname(path.abspath(__file__))) + '/config/tb_gateway.yaml'.replace('/', path.sep))
ur3e_rtqhe_x.py
import math from robot_con.ur.robotiq import rtq_eseries_gripper as r2f from robot_con.ur.robotiq import rtq_ft300 as rft from basis import robot_math as rm import drivers.urx.ur_robot as urrobot import robot_con.ur.program_builder as pb import numpy as np import threading import socket import struct import os import motion.trajectory as traj class UR3ERtqHE(): """ author: weiwei date: 20180131, 20210401osaka """ def __init__(self, robot_ip='10.2.0.50', pc_ip='10.2.0.91'): """ :param robot_ip: :param pc_ip: """ # setup arm self._arm = urrobot.URRobot(robot_ip) self._arm.set_tcp((0, 0, 0, 0, 0, 0)) self._arm.set_payload(1.0) # setup hand self._hand = r2f.RobotiqETwoFinger(type='hande') # setup ftsensor self._ftsensor = rft.RobotiqFT300() self._ftsensor_socket_addr = (robot_ip, 63351) self._ftsensor_urscript = self._ftsensor.get_program_to_run() # setup pc server self._pc_server_socket_addr = (pc_ip, 0) # 0: the system finds an available port self._pc_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._pc_server_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self._pc_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._pc_server_socket.bind(self._pc_server_socket_addr) self._pc_server_socket.listen(5) self._jointscaler = 1e6 self._pb = pb.ProgramBuilder() script_dir = os.path.dirname(__file__) self._pb.load_prog(os.path.join(script_dir, "urscripts_cbseries/moderndriver_eseries.script")) self._pc_server_urscript = self._pb.get_program_to_run() self._pc_server_urscript = self._pc_server_urscript.replace("parameter_ip", self._pc_server_socket_addr[0]) self._pc_server_urscript = self._pc_server_urscript.replace("parameter_port", str(self._pc_server_socket_addr[1])) self._pc_server_urscript = self._pc_server_urscript.replace("parameter_jointscaler", str(self._jointscaler)) self._ftsensor_thread = None self._ftsensor_values = [] self.trajt = traj.Trajectory(method='quintic') @property def arm(self): # read-only property return self._arm @property def ftsensor_urscript(self): # read-only property return self._ftsensor_urscript @property def ftsensor_socket_addr(self): # read-only property return self._ftsensor_socket_addr def open_gripper(self, speedpercentange=70, forcepercentage=50, fingerdistance=50.0): """ open the rtq85 hand on the arm specified by arm_name :param arm_name: :return: author: weiwei date: 20180220 """ self._arm.send_program(self._hand.return_program_to_run(speedpercentange, forcepercentage, fingerdistance)) def close_gripper(self, speedpercentange=80, forcepercentage=50): """ close the rtq85 hand on the arm specified by arm_name :param arm_name: :return: author: weiwei date: 20180220 """ self._arm.send_program(self._hand.return_program_to_run(speedpercentange, forcepercentage, 0)) def start_recvft(self): """ start receive ft values using thread the values are in the local frame of the force sensors transformation is to be done by higher-level code :return: """ def recvft(): self._arm.send_program(self._ftsensor_urscript) ftsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ftsocket.connect(self._ftsensor_socket_addr) while True: ftdata = ftsocket.recv(1024) ftdata = ftdata.decode() ftdata = ftdata.strip('()') self._ftsensor_values.append([float(x) for x in ftdata.split(',')]) self._ftsensor_thread = threading.Thread(target=recvft, name="threadft") self._ftsensor_thread.start() def stop_recvft(self): self._ftsensor_thread.join() def reset_ftsensor(self): pass def clear_ftsensor_values(self): self._ftsensor_values = [] def move_jnts(self, jnt_values, radius=0.01): """ :param jnt_values: a 1-by-6 list in degree :param arm_name: :return: author: weiwei date: 20170411 """ jointsrad = [math.radians(angdeg) for angdeg in jnt_values] self._arm.movej(jointsrad, acc=1, vel=1, wait=True) # targetarm.movejr(jointsrad, acc = 1, vel = 1, radius = radius, wait = False) def regulate_jnts_pmpi(self): """ TODO allow settings for pmpi pm 2pi the function move all joints back to -360,360 due to improper operations, some joints could be out of 360 this function moves the outlier joints back :return: author: weiwei date: 20180202 """ jnt_values = self.get_jnt_values() regulated_jnt_values = rm.regulate_angle(-math.pi, math.pi, jnt_values) self.move_jnts(regulated_jnt_values) def move_jntspace_path(self, path, control_frequency=.005, interval_time=1.0, method=None): """ move robot_s arm following a given jointspace path :param path: :param control_frequency: the program will sample interval_time/control_frequency confs, see motion.trajectory :param interval_time: equals to expandis/speed, speed = degree/second by default, the value is 1.0 and the speed is expandis/second :param method :return: author: weiwei date: 20210331 """ self.trajt.set_interpolation_method(method) interpolated_confs, interpolated_spds = self.trajt.piecewise_interpolation(path, control_frequency, interval_time) # upload a urscript to connect to the pc server started by this class self._arm.send_program(self._pc_server_urscript) # accept arm socket pc_server_socket, pc_server_socket_addr = self._pc_server_socket.accept() print("Connected by ", pc_server_socket_addr) # send trajectory keepalive = 1 buf = bytes() for id, conf in enumerate(interpolated_confs): if id == len(interpolated_confs) - 1: keepalive = 0 jointsradint = [int(jnt_value * self._jointscaler) for jnt_value in conf] buf += struct.pack('!iiiiiii', jointsradint[0], jointsradint[1], jointsradint[2], jointsradint[3], jointsradint[4], jointsradint[5], keepalive) pc_server_socket.send(buf) pc_server_socket.close() def get_jnt_values(self): """ get the joint angles in radian :param arm_name: :return: author: ochi, revised by weiwei date: 20180410 """ return self._arm.getj() if __name__ == '__main__': import visualization.panda.world as wd base = wd.World(cam_pos=[3, 1, 2], lookat_pos=[0, 0, 0]) u3erhe_x = UR3ERtqHE(robot_ip='10.0.2.2', pc_ip='10.2.0.91') u3erhe_x.opengripper() base.run()
server.py
import socket from threading import Thread def func(conn): conn.send('线程server'.encode('utf-8')) msg = conn.recv(1024).decode('utf-8') print(msg) sk = socket.socket() sk.bind(('127.0.0.1',8080)) sk.listen() while True: conn,addr = sk.accept() t = Thread(target=func,args=(conn,)) t.start()
expiry_maxttl.py
from random import randint from threading import Thread from BucketLib.bucket import Bucket from Cb_constants import DocLoading from cb_tools.cbepctl import Cbepctl from cb_tools.cbstats import Cbstats from couchbase_helper.documentgenerator import doc_generator from basetestcase import ClusterSetup from BucketLib.BucketOperations import BucketHelper from error_simulation.cb_error import CouchbaseError from remote.remote_util import RemoteMachineShellConnection from sdk_client3 import SDKClient from sdk_exceptions import SDKException from table_view import TableView class ExpiryMaxTTL(ClusterSetup): def setUp(self): super(ExpiryMaxTTL, self).setUp() # Create default bucket self.create_bucket(self.cluster) self.key = 'test_ttl_docs'.rjust(self.key_size, '0') if self.target_vbucket and type(self.target_vbucket) is not list: self.target_vbucket = [self.target_vbucket] self.bucket_util.get_all_buckets(self.cluster) self.bucket_helper_obj = BucketHelper(self.cluster.master) self.cluster_util.print_cluster_stats(self.cluster) self.bucket_util.print_bucket_stats(self.cluster) # Create sdk_clients for pool if self.sdk_client_pool: self.log.info("Creating SDK client pool") self.sdk_client_pool.create_clients( self.cluster.buckets[0], self.cluster.nodes_in_cluster, req_clients=self.sdk_pool_capacity, compression_settings=self.sdk_compression) self.log.info("==========Finished ExpiryMaxTTL base setup========") def getTargetNodes(self): def select_randam_node(nodes): rand_node_index = randint(1, self.nodes_init-1) if self.cluster.nodes_in_cluster[rand_node_index] not in node_list: nodes.append(self.cluster.nodes_in_cluster[rand_node_index]) node_list = list() num_nodes_affected = 1 if self.num_replicas > 1: num_nodes_affected = 2 if len(self.cluster.nodes_in_cluster) > 1: # Choose random nodes while len(node_list) != num_nodes_affected: select_randam_node(node_list) return node_list def _load_json(self, bucket, num_items, exp=0, op_type="create"): self.log.info("Creating doc_generator..") doc_create = doc_generator( self.key, 0, num_items, doc_size=self.doc_size, doc_type="json", target_vbucket=self.target_vbucket, vbuckets=self.cluster.vbuckets) self.log.info("doc_generator created") task = self.task.async_load_gen_docs( self.cluster, bucket, doc_create, op_type, exp, batch_size=10, process_concurrency=8, replicate_to=self.replicate_to, persist_to=self.persist_to, durability=self.durability_level, timeout_secs=self.sdk_timeout, compression=self.sdk_compression, sdk_client_pool=self.sdk_client_pool) self.task.jython_task_manager.get_task_result(task) self.bucket_util._wait_for_stats_all_buckets(self.cluster, self.cluster.buckets) self.bucket_util.verify_stats_all_buckets(self.cluster, self.num_items) return def load_docs_in_parallel(self, bucket, non_ttl_gen, ttl_gen, non_ttl_task_property, ttl_task_property): tasks_info = dict() self.log.info("Starting doc_loading tasks") non_ttl_task = self.task.async_load_gen_docs( self.cluster, bucket, non_ttl_gen, non_ttl_task_property["op_type"], 0, batch_size=10, process_concurrency=4, replicate_to=non_ttl_task_property["replicate_to"], persist_to=non_ttl_task_property["persist_to"], durability=non_ttl_task_property["durability"], timeout_secs=self.sdk_timeout, compression=self.sdk_compression, sdk_client_pool=self.sdk_client_pool) ttl_task = self.task.async_load_gen_docs( self.cluster, bucket, ttl_gen, ttl_task_property["op_type"], self.maxttl, batch_size=10, process_concurrency=4, replicate_to=ttl_task_property["replicate_to"], persist_to=ttl_task_property["persist_to"], durability=ttl_task_property["durability"], timeout_secs=self.sdk_timeout, compression=self.sdk_compression, print_ops_rate=False, sdk_client_pool=self.sdk_client_pool) tasks_info[non_ttl_task] = self.bucket_util.get_doc_op_info_dict( bucket, non_ttl_task_property["op_type"], 0, replicate_to=non_ttl_task_property["replicate_to"], persist_to=non_ttl_task_property["persist_to"], durability=non_ttl_task_property["durability"], timeout=self.sdk_timeout, time_unit="seconds") tasks_info[ttl_task] = self.bucket_util.get_doc_op_info_dict( bucket, non_ttl_task_property["op_type"], 0, replicate_to=non_ttl_task_property["replicate_to"], persist_to=non_ttl_task_property["persist_to"], durability=non_ttl_task_property["durability"], timeout=self.sdk_timeout, time_unit="seconds") # Wait for tasks completion and validate failures for task in tasks_info: self.task_manager.get_task_result(task) self.bucket_util.verify_doc_op_task_exceptions(tasks_info, self.cluster) self.bucket_util.log_doc_ops_task_failures(tasks_info) def test_maxttl_lesser_doc_expiry(self): """ A simple test to create a bucket with maxTTL and check whether new creates with greater exp are deleted when maxTTL has lapsed :return: """ for bucket in self.cluster.buckets: self._load_json(bucket, self.num_items, exp=self.maxttl) self.sleep(self.maxttl, "Waiting for docs to expire as per maxTTL") self.bucket_util._expiry_pager(self.cluster) self.log.info("Calling compaction after expiry pager call") compact_tasks = [] for bucket in self.cluster.buckets: compact_tasks.append(self.task.async_compact_bucket(self.cluster.master, bucket)) for task in compact_tasks: self.task.jython_task_manager.get_task_result(task) self.assertTrue(task.result, "Compaction failed due to:" + str(task.exception)) self.sleep(20, "Waiting for item count to come down...") for bucket in self.cluster.buckets: items = self.bucket_helper_obj.get_active_key_count(bucket.name) self.log.info("Doc expiry {0}s, maxTTL {1}s, " "after {2}s, item count {3}" .format(self.maxttl, self.maxttl, self.maxttl, items)) if items > 0: self.fail("Bucket maxTTL of {0} is not honored" .format(self.maxttl)) else: self.log.info("SUCCESS: Doc expiry={0}s, maxTTL {1}s, " "after {2}s, item count {3}" .format(int(self.maxttl), self.maxttl, self.maxttl, items)) def test_maxttl_greater_doc_expiry(self): """ maxTTL is set to 200s in this test, Docs have lesser TTL. :return: """ for bucket in self.cluster.buckets: self._load_json(bucket, self.num_items, exp=int(self.maxttl)-100) self.sleep(self.maxttl-100, "Waiting for docs to expire as per maxTTL") self.bucket_util._expiry_pager(self.cluster) self.sleep(20, "Waiting for item count to come down...") for bucket in self.cluster.buckets: items = self.bucket_helper_obj.get_active_key_count(bucket.name) self.log.info("Doc expiry={0}s, maxTTL={1}s, " "after {2}s, item count={3}" .format(int(self.maxttl) - 100, self.maxttl-100, self.maxttl-100, items)) if items == 0: self.log.info("SUCCESS: Docs with lesser expiry deleted") else: self.fail("FAIL: Doc with lesser expiry still exists past ttl") def test_set_maxttl_on_existing_bucket(self): """ 1. Create a bucket with no max_ttl 2. Upload 1000 docs with 'doc_init_expiry' seconds 3. Set maxTTL on bucket as 'doc_new_expiry' seconds 4. After 'doc_init_expiry' seconds, run expiry pager and get item count, must be 1000 5. After 'doc_new_expiry' seconds, run expiry pager again and get item count, must be 0 6. Now load another set of docs with 'doc_init_expiry' seconds 7. Run expiry pager after 'doc_new_expiry' seconds and get item count, must be 0 """ doc_ttl = 180 bucket_ttl = 60 def_bucket = self.cluster.buckets[0] self.log.info("Inserting docs with expiry=%s" % doc_ttl) self._load_json(def_bucket, self.num_items, exp=doc_ttl) self.log.info("Updating bucket ttl=%s" % bucket_ttl) self.bucket_util.update_all_bucket_maxTTL(self.cluster, maxttl=bucket_ttl) self.sleep(bucket_ttl, "Wait for bucket_ttl expiry time") self.bucket_util._expiry_pager(self.cluster) self.sleep(20, "Waiting for items to get purged") items = self.bucket_helper_obj.get_active_key_count(def_bucket.name) self.assertTrue(items == self.num_items, "After %ss, items expected (%s) != actual (%s). " "Items with larger doc_ttl expired before " "maxTTL updation deleted!" % (bucket_ttl, self.num_items, items)) self.sleep(doc_ttl-bucket_ttl, "Wait for doc_ttl-bucket_ttl time") self.bucket_util._expiry_pager(self.cluster) self.sleep(20, "Waiting for items to get purged") items = self.bucket_helper_obj.get_active_key_count(def_bucket.name) self.assertTrue(items == 0, "After %ss, items expected (0) != actual (%s). " "Items with not greater expiry set before " "maxTTL updation not deleted after elapsed TTL!" % (doc_ttl-bucket_ttl, items)) self.log.info("Inserting docs with expiry=%s" % doc_ttl) for def_bucket in self.cluster.buckets: self._load_json(def_bucket, self.num_items, exp=doc_ttl) self.sleep(bucket_ttl, "Wait only till bucket_ttl time") self.bucket_util._expiry_pager(self.cluster) self.sleep(20, "Waiting for items to get purged") items = self.bucket_helper_obj.get_active_key_count(def_bucket.name) self.assertTrue(items == 0, "After %ss, items expected (0) != actual (%s). " "Items with not greater expiry not " "deleted after elapsed maxTTL!" % (bucket_ttl, items)) def test_maxttl_possible_values(self): """ Test 1. min - 0 2. max - 2147483647q 3. default - 0 4. negative values, date, string """ # default default_bucket = self.bucket_util.get_all_buckets(self.cluster)[0] if default_bucket.maxTTL != 0: self.fail("FAIL: default maxTTL if left unset must be 0 but is {0}" .format(default_bucket.maxTTL)) self.log.info("Verified: default maxTTL if left unset is {0}" .format(default_bucket.maxTTL)) # max value try: self.bucket_util.update_all_bucket_maxTTL(self.cluster, maxttl=2147483648) except Exception as e: self.log.info("Expected exception : {0}".format(e)) try: self.bucket_util.update_all_bucket_maxTTL(self.cluster, maxttl=2147483647) except Exception as e: self.fail("Unable to set max value for maxTTL=2147483647: {0}" .format(e)) else: self.log.info("Verified: Max value permitted is 2147483647") else: self.fail("Able to set maxTTL greater than 2147483647") # min value try: self.bucket_util.update_all_bucket_maxTTL(self.cluster, maxttl=0) except Exception as e: self.fail("Unable to set maxTTL=0, the min permitted value: {0}" .format(e)) else: self.log.info("Verified: Min value permitted is 0") # negative value try: self.bucket_util.update_all_bucket_maxTTL(self.cluster, maxttl=-60) except Exception as e: self.log.info("Verified: negative values denied, exception: {0}" .format(e)) else: self.fail("FAIL: Able to set a negative maxTTL") # date/string try: self.bucket_util.update_all_bucket_maxTTL(self.cluster, maxttl="12/23/2016") except Exception as e: self.log.info("Verified: string not permitted, exception : {0}" .format(e)) else: self.fail("FAIL: Able to set a date string maxTTL") def test_update_maxttl(self): """ 1. Create a bucket with ttl = 200s 2. Upload 1000 docs with exp = 100s 3. Update ttl = 40s 4. After 40s, run expiry pager again and get item count, must be 1000 5. After 60s, run expiry pager again and get item count, must be 0 6. Now load another set of docs with exp = 100s 7. Run expiry pager after 40s and get item count, must be 0 """ for bucket in self.cluster.buckets: self._load_json(bucket, self.num_items, exp=100) self.bucket_util.update_all_bucket_maxTTL(self.cluster, maxttl=40) self.sleep(40, "waiting before running expiry pager...") self.bucket_util._expiry_pager(self.cluster) self.sleep(20, "waiting for item count to come down...") for bucket in self.cluster.buckets: items = self.bucket_helper_obj.get_active_key_count(bucket.name) self.log.info("Doc expiry=100s, maxTTL during doc creation = 200s" " updated maxttl=40s, after 40s item count = {0}" .format(items)) if items != self.num_items: self.fail("FAIL: Updated ttl affects docs with larger expiry " "before updation!") self.sleep(60, "waiting before running expiry pager...") self.bucket_util._expiry_pager(self.cluster) self.sleep(20, "waiting for item count to come down...") for bucket in self.cluster.buckets: items = self.bucket_helper_obj.get_active_key_count(bucket.name) self.log.info("Doc expiry=100s, maxTTL during doc creation=200s" " updated maxttl=40s, after 100s item count = {0}" .format(items)) if items != 0: self.fail("FAIL: Docs with 100s as expiry before " "maxTTL updation still alive!") def test_maxttl_with_doc_updates(self): """ 1. Create a bucket with ttl = self.maxttl 2. Upload 1000 docs with exp = self.maxttl - 20 3. After 20s, Update docs with exp = self.maxttl 4. After 40s, run expiry pager again and get item count, must be 1000 5. After 20s, run expiry pager again and get item count, must be 0 """ for bucket in self.cluster.buckets: self._load_json(bucket, self.num_items, exp=self.maxttl-20) self.sleep(20, "Waiting to update docs with exp={0}s" .format(self.maxttl)) for bucket in self.cluster.buckets: self._load_json(bucket, self.num_items, exp=self.maxttl, op_type="update") self.sleep(self.maxttl-20, "waiting before running expiry pager...") self.bucket_util._expiry_pager(self.cluster) for bucket in self.cluster.buckets: items = self.bucket_helper_obj.get_active_key_count(bucket.name) self.log.info("Items: {0}".format(items)) if items != self.num_items: self.fail("FAIL: Docs with updated expiry deleted") self.sleep(20, "waiting before running expiry pager...") self.bucket_util._expiry_pager(self.cluster) self.sleep(20, "waiting for item count to come down...") for bucket in self.cluster.buckets: items = self.bucket_helper_obj.get_active_key_count(bucket.name) self.log.info("Items: {0}".format(items)) if items != 0: self.fail("FAIL: Docs with updated expiry not deleted after " "new exp has elapsed!") def test_maxttl_with_sync_writes(self): """ 1. Load few docs without TTL 2. Load few docs with TTL set in parallel to #1 3. Validate docs get expiry after the TTL time :return: """ def_bucket = self.cluster.buckets[0] self.maxttl = self.input.param("doc_ttl", self.maxttl) doc_ops_type = self.input.param("doc_ops_type", "sync;sync").split(";") # Create default doc_load options for TTL and non-TTL tasks non_ttl_task_property = dict() ttl_task_property = dict() # Create generators for TTL and non_TTL loading self.log.info("Creating doc_generators") ttl_gen_create = doc_generator( self.key, 0, self.num_items, doc_size=self.doc_size, doc_type=self.doc_type, target_vbucket=self.target_vbucket, vbuckets=self.cluster.vbuckets) non_ttl_gen_create = doc_generator( self.key, self.num_items, self.num_items*2, doc_size=self.doc_size, doc_type=self.doc_type, target_vbucket=self.target_vbucket, vbuckets=self.cluster.vbuckets) # Set durability levels based on doc_ops_type non_ttl_task_property["op_type"] = "create" ttl_task_property["op_type"] = "create" if doc_ops_type[0] == "sync": non_ttl_task_property["replicate_to"] = 0 non_ttl_task_property["persist_to"] = 0 non_ttl_task_property["durability"] = self.durability_level else: non_ttl_task_property["replicate_to"] = self.replicate_to non_ttl_task_property["persist_to"] = self.persist_to non_ttl_task_property["durability"] = "None" if doc_ops_type[1] == "sync": ttl_task_property["replicate_to"] = 0 ttl_task_property["persist_to"] = 0 ttl_task_property["durability"] = self.durability_level else: ttl_task_property["replicate_to"] = self.replicate_to ttl_task_property["persist_to"] = self.persist_to ttl_task_property["durability"] = "None" self.load_docs_in_parallel(def_bucket, non_ttl_gen_create, ttl_gen_create, non_ttl_task_property, ttl_task_property) # Validate doc_count before expiry of docs self.bucket_util._wait_for_stats_all_buckets(self.cluster, self.cluster.buckets) self.bucket_util.verify_stats_all_buckets(self.cluster, self.num_items*2) self.sleep(self.maxttl, "Sleep for maxTTL time") self.bucket_util._expiry_pager(self.cluster) self.sleep(25, "Waiting for items to be purged") # Read all expired docs to validate EONENT status ttl_task = self.task.async_load_gen_docs( self.cluster, def_bucket, ttl_gen_create, "read", self.maxttl, batch_size=10, process_concurrency=8, timeout_secs=self.sdk_timeout, compression=self.sdk_compression, sdk_client_pool=self.sdk_client_pool) self.task.jython_task_manager.get_task_result(ttl_task) # Max-TTL doc expiry validation self.log.info("Validating expiry of docs") if len(ttl_task.success.keys()) != 0: self.fail("Items present after MaxTTL time: %s" % ttl_task.success.keys()) invalid_exception_tbl = TableView(self.log.info) invalid_exception_tbl.set_headers(["Doc_Key", "CAS"]) for doc_key, result in ttl_task.fail.items(): if result["cas"] != 0 and result["error"] is not None: invalid_exception_tbl.add_row([doc_key, result["cas"]]) invalid_exception_tbl.display("Invalid exceptions for following keys") if len(invalid_exception_tbl.rows) != 0: self.fail("Seen invalid document exception") # Validate doc_count after doc_expiry self.bucket_util._wait_for_stats_all_buckets(self.cluster, self.cluster.buckets) self.bucket_util.verify_stats_all_buckets(self.cluster, self.num_items) # Document mutations after doc_expiry non_ttl_task_property["op_type"] = "update" self.load_docs_in_parallel(def_bucket, non_ttl_gen_create, ttl_gen_create, non_ttl_task_property, ttl_task_property) # Validate doc_count before expiry of docs self.bucket_util._wait_for_stats_all_buckets(self.cluster, self.cluster.buckets) self.bucket_util.verify_stats_all_buckets(self.cluster, self.num_items*2) def test_maxttl_with_timeout(self): """ 1. Stop Memcached on target_nodes based on replicas configured. 2. Initiate doc_ops with higher sdk_timeout 3. Sleep for time within the configured sdk_timeout 4. Resume Memcached on target_nodes to make sure doc_ops go through 5. Make sure maxTTL is calculated as soon as the active vbucket receives the mutation :return: """ shell_conn = dict() target_vbuckets = list() target_nodes = self.getTargetNodes() def_bucket = self.cluster.buckets[0] self.maxttl = self.input.param("doc_ttl", self.maxttl) # Open required SDK connections before error_simulation gen_create = doc_generator( self.key, 0, self.num_items, doc_size=self.doc_size, doc_type=self.doc_type, target_vbucket=target_vbuckets, vbuckets=self.cluster.vbuckets) doc_op_task = self.task.async_load_gen_docs( self.cluster, def_bucket, gen_create, "create", self.maxttl, batch_size=10, process_concurrency=8, replicate_to=self.replicate_to, persist_to=self.persist_to, durability=self.durability_level, timeout_secs=self.sdk_timeout, compression=self.sdk_compression, start_task=False, sdk_client_pool=self.sdk_client_pool) # Open shell_conn and create Memcached error for testing MaxTTL self.log.info("1. Stopping Memcached on target_nodes") for node in target_nodes: shell_conn[node.ip] = RemoteMachineShellConnection(node) cbstats = Cbstats(shell_conn[node.ip]) target_vbuckets += cbstats.vbucket_list(def_bucket.name, "replica") cb_error = CouchbaseError(self.log, shell_conn[node.ip]) cb_error.create(CouchbaseError.STOP_MEMCACHED, def_bucket.name) self.log.info("2. Initiating the doc_ops with doc TTL") self.task_manager.add_new_task(doc_op_task) self.sleep(self.maxttl, "3. Sleep for max_ttl time") # Revert Memcached error and close the shell_conn self.log.info("4. Resuming Memcached on target_nodes") for node in target_nodes: cb_error = CouchbaseError(self.log, shell_conn[node.ip]) cb_error.revert(CouchbaseError.STOP_MEMCACHED, def_bucket.name) shell_conn[node.ip].disconnect() self.log.info("5. Waiting for doc_ops to complete") self.task.jython_task_manager.get_task_result(doc_op_task) self.bucket_util._expiry_pager(self.cluster, val=1) self.sleep(10, "6. Waiting for items to be purged") # Read all expired docs to validate all keys present doc_op_task = self.task.async_load_gen_docs( self.cluster, def_bucket, gen_create, "read", batch_size=10, process_concurrency=8, timeout_secs=self.sdk_timeout, sdk_client_pool=self.sdk_client_pool) self.task.jython_task_manager.get_task_result(doc_op_task) self.log.info("7. Validating docs expired after TTL, " "even before sync_write succeeds") if len(doc_op_task.success.keys()) == self.num_items: self.fail("No docs deleted after MaxTTL time: %s" % doc_op_task.success.keys()) self.sleep(10, "8. Waiting for all docs to be purged") # Read all expired docs to validate all keys present doc_op_task = self.task.async_load_gen_docs( self.cluster, def_bucket, gen_create, "read", batch_size=10, process_concurrency=8, timeout_secs=self.sdk_timeout, sdk_client_pool=self.sdk_client_pool) self.task.jython_task_manager.get_task_result(doc_op_task) self.log.info("9. Validating docs expired after TTL") if len(doc_op_task.fail.keys()) != self.num_items: self.fail("Items not deleted after MaxTTL time: %s" % doc_op_task.success.keys()) # Validate cas for purged items keys_with_cas = list() for key, result in doc_op_task.fail.items(): if result['cas'] != 0: keys_with_cas.append(key) if len(keys_with_cas) != 0: self.fail("Following failed keys has CAS: %s" % keys_with_cas) # Recreate all docs without any node issues doc_op_task = self.task.async_load_gen_docs( self.cluster, def_bucket, gen_create, "create", 0, batch_size=10, process_concurrency=8, durability=self.durability_level, timeout_secs=self.sdk_timeout, compression=self.sdk_compression, sdk_client_pool=self.sdk_client_pool) self.task.jython_task_manager.get_task_result(doc_op_task) self.log.info("10. Validating docs exists after creation") if len(doc_op_task.fail.keys()) != 0: self.fail("Doc recreate failed for keys: %s" % doc_op_task.fail.keys()) # Final doc_count validation self.bucket_util._wait_for_stats_all_buckets(self.cluster, self.cluster.buckets) self.bucket_util.verify_stats_all_buckets(self.cluster, self.num_items) def test_ttl_less_than_durability_timeout(self): """ MB-43238 1. Regular write with TTL 1 second for some key 2. Disable expiry pager (to prevent raciness) 3. Wait TTL period 4. Disable persistence on the node with the replica vBucket for that key 5. SyncWrite PersistMajority to active vBucket for that key (should hang) 6. Access key on other thread to trigger expiry 7. Observe DCP connection being torn down without fix """ def perform_sync_write(): client.crud(DocLoading.Bucket.DocOps.CREATE, key, {}, durability=Bucket.DurabilityLevel.PERSIST_TO_MAJORITY, timeout=60) doc_ttl = 5 shell = None target_node = None key = "test_ttl_doc" vb_for_key = self.bucket_util.get_vbucket_num_for_key(key) bucket = self.cluster.buckets[0] # Find target node for replica VB for target_node in self.cluster.nodes_in_cluster: shell = RemoteMachineShellConnection(target_node) cb_stats = Cbstats(shell) if vb_for_key in cb_stats.vbucket_list(bucket.name, "replica"): break shell.disconnect() self.log.info("Target node: %s, Key: %s" % (target_node.ip, key)) self.log.info("Disabling expiry_pager") cb_ep_ctl = Cbepctl(shell) cb_ep_ctl.set(bucket.name, "flush_param", "exp_pager_stime", 0) # Create SDK client client = SDKClient([self.cluster.master], bucket) self.log.info("Non-sync write with TTL=%s" % doc_ttl) client.crud(DocLoading.Bucket.DocOps.CREATE, key, {}, exp=doc_ttl) self.sleep(doc_ttl, "Wait for document to expire") self.bucket_util._wait_for_stats_all_buckets(self.cluster, self.cluster.buckets) self.log.info("Stopping persistence on replica VB node using cbepctl") cb_ep_ctl.persistence(bucket.name, "stop") # Start doc_load with lesser ttl doc_create_thread = Thread(target=perform_sync_write) doc_create_thread.start() self.sleep(2, "Wait for sync_write thread to start") self.log.info("Read key from another thread to trigger expiry") failure = None result = client.crud(DocLoading.Bucket.DocOps.READ, key) if SDKException.DocumentNotFoundException not in str(result["error"]): failure = "Invalid exception: %s" % result["error"] self.log.info("Resuming persistence on target node") cb_ep_ctl.persistence(bucket.name, "start") # Wait for doc_create_thread to complete doc_create_thread.join() # Close SDK client and shell connections client.close() shell.disconnect() if failure: self.fail(failure) for node in self.cluster.nodes_in_cluster: shell = RemoteMachineShellConnection(node) cb_stats = Cbstats(shell).all_stats(bucket.name) self.log.info("Node: %s, ep_expired_access: %s" % (node.ip, cb_stats["ep_expired_access"])) shell.disconnect() self.assertEqual(int(cb_stats["ep_expired_access"]), 0, "%s: ep_expired_access != 0" % node.ip)
n1ql_window_functions_syntax_check.py
from .tuq import QueryTests import random import string from random import randint from membase.api.exception import CBQError import threading import copy class WindowFunctionsSyntaxTest(QueryTests): def setUp(self): super(WindowFunctionsSyntaxTest, self).setUp() self.log_config_info() self.log.info("============== WindowFunctionsSyntaxTest setup has started ==============") self.primary_idx = {'name': '#primary', 'bucket': 'test_bucket', 'fields': (), 'state': 'online', 'using': self.index_type.lower(), 'is_primary': True} self.idx_1 = {'name': 'ix_char', 'bucket': 'test_bucket', 'fields': [('char_field', 0)], 'state': 'online', 'using': self.index_type.lower(), 'is_primary': False} self.idx_2 = {'name': 'ix_decimal', 'bucket': 'test_bucket', 'fields': [('decimal_field', 0)], 'state': 'online', 'using': self.index_type.lower(), 'is_primary': False} self.idx_3 = {'name': 'ix_int', 'bucket': 'test_bucket', 'fields': [('int_field', 0)], 'state': 'online', 'using': self.index_type.lower(), 'is_primary': False} self.indexes = [self.primary_idx, self.idx_1, self.idx_2, self.idx_3] if self.test_buckets != 'test_bucket': self.test_buckets = 'test_bucket' self.query_bucket = self.get_query_buckets(deferred_bucket=self.test_buckets)[-1] self.log.info("============== WindowFunctionsTest setup has completed ==============") def tearDown(self): self.log_config_info() self.log.info("============== WindowFunctionsSyntaxTest tearDown has started ==============") super(WindowFunctionsSyntaxTest, self).tearDown() self.log.info("============== WindowFunctionsSyntaxTest tearDown has completed ==============") def suite_setUp(self): super(WindowFunctionsSyntaxTest, self).suite_setUp() if self.test_buckets != 'test_bucket': self.test_buckets = 'test_bucket' self.query_bucket = self.get_query_buckets(deferred_bucket=self.test_buckets)[-1] self.init_nodes() self.load_test_data(self.query_bucket) self.create_primary_index(self.query_bucket) self.create_secondary_indexes(self.query_bucket) self.adopt_test_data(self.query_bucket) self.log_config_info() self.log.info("============== WindowFunctionsSyntaxTest suite_setup has started ==============") self.log.info("============== WindowFunctionsSyntaxTest suite_setup has completed ==============") def suite_tearDown(self): self.log_config_info() self.log.info("============== WindowFunctionsSyntaxTest suite_tearDown has started ==============") super(WindowFunctionsSyntaxTest, self).suite_tearDown() self.log.info("============== WindowFunctionsSyntaxTest suite_tearDown has completed ==============") def run_all(self): # commenting from ... select queries to reduce overall test suite execution time. #self.test_from_select_batches() self.test_select_from_batches() def generate_from_select_queries(self): result = [] counter = 0 window_function_values = [' LAST_VALUE(t1.decimal_field) OVER (PARTITION BY t1.char_field ORDER BY ' 't1.decimal_field RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) '] alias_values = [' wf '] bucket_alias_values = [' ', ' as '] let_where_values = [' ', ' where t1.int_field > 1000 ', ' let int_val=1000 where t1.int_field > int_val '] group_by_values = [' ', ' group by t1.char_field, t1.decimal_field '] letting_having_values = [' ', ' having t1.char_field="E" ', ' letting char_val="E" having t1.char_field=char_val '] order_by_values = [' ', ' order by t1.char_field '] asc_desc_values = [' ', ' asc ', ' desc '] limit_values = [' ', ' limit 100 '] offset_values = [' ', ' offset 10 '] join_values = [' ', ' inner join ', ' left join ', ' left outer join ', ' inner nest ', ' left nest '] union_values = [' ', ' union ', ' union all '] namespace_values = ['', 'default:'] use_keys_values = [' ', ' use primary keys[\'test\'] ', ' use keys[\'test\'] ', ' use index(`ix_char`) ', ' use index(`ix_char`, `ix_decimal`) ', ' use index(`ix_char` using gsi) '] join_predicate_values = [' on t1.primary_key=t2.primary_key ', ' on primary keys[\'test\']', ' on keys t1.char_field ', ' on key t2.char_field for t1 ', ' on primary key t2.primary_key for t1 '] unnest_flatten_values = [' unnest ', ' left unnest ', ' flatten ', ' left flatten '] for window_function_value in window_function_values: for alias_value in alias_values: for let_where_value in let_where_values: for group_by_value in group_by_values: for letting_having_value in letting_having_values: if group_by_value == ' ': letting_having_value = ' ' for order_by_value in order_by_values: for asc_desc_value in asc_desc_values: if order_by_value == ' ': asc_desc_value = ' ' for limit_value in limit_values: for offset_value in offset_values: for bucket_alias_value in bucket_alias_values: for namespace_value in namespace_values: for use_keys_value in use_keys_values: for unnest_flatten_value in unnest_flatten_values: for join_value in join_values: for join_predicate_value in join_predicate_values: join_expression = ' ' if join_value != ' ': join_expression = join_value + ' ' + namespace_value + ' {0} '.format(self.query_bucket) + bucket_alias_value + ' t2 ' + use_keys_value + join_predicate_value else: join_expression = unnest_flatten_value + ' t1.char_field ' for union_value in union_values: union_left_parenthesis = '' union_right_parenthesis = '' right_union_expression = '' if union_value != ' ': union_left_parenthesis = '(' union_right_parenthesis = ')' right_union_expression = union_left_parenthesis + "select t1.char_field, t1.decimal_field, " + window_function_value + alias_value + " " \ "from " + namespace_value + ' {0} '.format(self.query_bucket) + bucket_alias_value + " t1 " + use_keys_value + join_expression + let_where_value + group_by_value + letting_having_value + \ order_by_value + asc_desc_value + limit_value + offset_value + union_right_parenthesis query = "from (" + union_left_parenthesis + "select t1.char_field, t1.decimal_field, " + window_function_value + alias_value + " " \ "from " + namespace_value + ' {0} '.format(self.query_bucket) + bucket_alias_value + " t1 " + use_keys_value + join_expression + let_where_value + group_by_value + letting_having_value + \ order_by_value + asc_desc_value + limit_value + offset_value + union_right_parenthesis + union_value + right_union_expression + ") a select a.wf" result.append(query) counter += 1 return result def generate_select_from_queries(self): result = [] counter = 0 window_function_values = [ ' LAST_VALUE(t1.decimal_field) OVER (PARTITION BY t1.char_field ORDER BY t1.decimal_field RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) '] alias_values = [' wf '] bucket_alias_values = [' ', ' as '] let_where_values = [' ', ' where t1.int_field > 1000 ', ' let int_val=1000 where t1.int_field > int_val '] group_by_values = [' ', ' group by t1.char_field, t1.decimal_field '] letting_having_values = [' ', ' having t1.char_field="E" ', ' letting char_val="E" having t1.char_field=char_val '] order_by_values = [' ', ' order by t1.char_field '] asc_desc_values = [' ', ' asc ', ' desc '] limit_values = [' ', ' limit 100 '] offset_values = [' ', ' offset 10 '] join_values = [' ', ' inner join ', ' left join ', ' left outer join ', ' inner nest ', ' left nest '] union_values = [' ', ' union ', ' union all '] namespace_values = ['', 'default:'] use_keys_values = [' ', ' use primary keys[\'test\'] ', ' use keys[\'test\'] ', ' use index(`ix_char`) ', ' use index(`ix_char`, `ix_decimal`) ', ' use index(`ix_char` using gsi) '] join_predicate_values = [' on t1.primary_key=t2.primary_key ', ' on primary keys[\'test\']', ' on keys t1.char_field ', ' on key t2.char_field for t1 ', ' on primary key t2.primary_key for t1 '] unnest_flatten_values = [' unnest ', ' left unnest ', ' flatten ', ' left flatten '] for window_function_value in window_function_values: for alias_value in alias_values: for let_where_value in let_where_values: for group_by_value in group_by_values: for letting_having_value in letting_having_values: if group_by_value == ' ': letting_having_value = ' ' for order_by_value in order_by_values: for asc_desc_value in asc_desc_values: if order_by_value == ' ': asc_desc_value = ' ' for limit_value in limit_values: for offset_value in offset_values: for bucket_alias_value in bucket_alias_values: for namespace_value in namespace_values: for use_keys_value in use_keys_values: for unnest_flatten_value in unnest_flatten_values: for join_value in join_values: for join_predicate_value in join_predicate_values: join_expression = ' ' if join_value != ' ': join_expression = join_value + ' ' + namespace_value + ' {0} '.format(self.query_bucket) + bucket_alias_value + ' t2 ' + use_keys_value + join_predicate_value else: join_expression = unnest_flatten_value + ' t1.char_field ' for union_value in union_values: union_left_parenthesis = '' union_right_parenthesis = '' right_union_expression = '' if union_value != ' ': union_left_parenthesis = '(' union_right_parenthesis = ')' right_union_expression = union_left_parenthesis + "select t1.char_field, t1.decimal_field, " + window_function_value + alias_value + " " \ "from " + namespace_value + ' {0} '.format(self.query_bucket) + bucket_alias_value + " t1 " + use_keys_value + join_expression + let_where_value + group_by_value + letting_having_value + \ order_by_value + asc_desc_value + limit_value + offset_value + union_right_parenthesis query = union_left_parenthesis + "select t1.char_field, t1.decimal_field, " + window_function_value + alias_value + \ " from " + namespace_value + ' {0} '.format(self.query_bucket) + bucket_alias_value + " t1 " + use_keys_value + join_expression + let_where_value + group_by_value + \ letting_having_value + order_by_value + asc_desc_value + limit_value + offset_value + union_right_parenthesis + union_value + right_union_expression result.append(query) counter += 1 return result def test_from_select_batches(self): queries = self.generate_from_select_queries() batches = self.produce_batches(queries, 4) for batch in batches: threads = [] for b in batch: t = threading.Thread(target=self._run_test, args=(b,)) t.daemon = True threads.append(t) t.start() for th in threads: th.join() threads.remove(th) def _run_test(self, query): try: self.run_cbq_query(query=query, debug_query=False) except CBQError as e: self.assertEqual('True', 'False', 'Wrong query - ' + str(query)) def test_select_from_batches(self): queries = self.generate_select_from_queries() batches = self.produce_batches(queries, 4) for batch in batches: threads = [] for b in batch: t = threading.Thread(target=self._run_test, args=(b,)) t.daemon = True threads.append(t) t.start() for th in threads: th.join() threads.remove(th) def produce_batches(self, queries, batch_size): result = [] counter = 0 arr = [] for query in queries: if counter < batch_size: arr.append(query) counter += 1 else: add = copy.copy(arr) result.append(add) arr = [] arr.append(query) counter = 1 return result def init_nodes(self): test_bucket_params = self._create_bucket_params(server=self.master, size=self.bucket_size, replicas=self.num_replicas, bucket_type=self.bucket_type, enable_replica_index=self.enable_replica_index, eviction_policy=self.eviction_policy, lww=self.lww) self.cluster.create_standard_bucket(self.test_bucket, 11222, test_bucket_params) def load_test_data(self, bucket_name='test_bucket'): for i in range(0, 1, 1): initial_statement = (" INSERT INTO {0} (KEY, VALUE) VALUES ('primary_key_" + str(i) + "',").format( bucket_name) initial_statement += "{" initial_statement += "'primary_key':'primary_key_" + str(i) + "','char_field':'" + random.choice( string.ascii_uppercase) + \ "','decimal_field':" + str(round(10000 * random.random(), 0)) + ",'int_field':" + str( randint(0, 100000000)) + "})" self.run_cbq_query(initial_statement) def adopt_test_data(self, bucket_name='test_bucket'): self.run_cbq_query("update {0} set decimal_field=null where char_field='A'".format(bucket_name)) self.run_cbq_query("update {0} set decimal_field=missing where char_field='B'".format(bucket_name)) self.run_cbq_query( "update {0} set decimal_field=null where char_field='C' and decimal_field%2=0".format(bucket_name)) self.run_cbq_query( "update {0} set decimal_field=missing where char_field='C' and decimal_field%3=0".format(bucket_name)) self.run_cbq_query( "update {0} set decimal_field=2 where char_field='D' and decimal_field%2=0".format(bucket_name)) self.run_cbq_query("update {0} set decimal_field=1 where char_field='E'".format(bucket_name)) def create_primary_index(self, bucket_name='test_bucket'): self.run_cbq_query("CREATE PRIMARY INDEX `#primary` ON {0}".format(bucket_name)) def create_secondary_indexes(self, bucket_name='test_bucket'): self.run_cbq_query('CREATE INDEX ix_char ON {0}(char_field);'.format(bucket_name)) self.run_cbq_query('CREATE INDEX ix_decimal ON {0}(decimal_field);'.format(bucket_name)) self.run_cbq_query('CREATE INDEX ix_int ON {0}(int_field);'.format(bucket_name)) self.run_cbq_query('CREATE INDEX ix_primary ON {0}(primary_key);'.format(bucket_name))
stream.py
from urllib.parse import urlencode from collections import defaultdict from datetime import datetime import threading import websocket import queue import time import json from pymeritrade.errors import TDAPermissionsError, check_assert from pymeritrade.stream.schemas import SUB_ID_TO_NAME, SUB_TYPES class StreamData: def __init__(self, type_name, data): self.name = type_name self.raw = data self.meta = SUB_TYPES[type_name] self.data = {} for raw_item in self.raw: key = raw_item["key"] item_dict = {"seq": raw_item.get("seq")} for i, clean_name in enumerate(self.meta[3]): idx_key = str(i) if idx_key in raw_item: item_dict[clean_name] = raw_item[idx_key] self.data[key] = item_dict def __getitem__(self, key): return self.data[key] def __repr__(self): return f"<StreamData ({self.name}) [{','.join(self.data)}]>" class TDAStream: def __init__(self, client, debug=False): self.principles = client.principles self.ws_uri = "wss://" + self.principles["streamerInfo"]["streamerSocketUrl"] + "/ws" self.token_ts = _iso_to_ms(self.principles["streamerInfo"]["tokenTimestamp"]) self.acc_id = self.principles["accounts"][0]["accountId"] self.app_id = self.principles["streamerInfo"]["appId"] self.debug = debug self.cmd_buffer = [] self.req_id_cnt = 0 self.ws = None self.ws_started = False self.ws_ready = False self.thread = None self.data_qs = defaultdict(lambda: None) def _log(self, *args): if self.debug: print(*args) def _cmd(self, service, command, params={}, id_=None, send=True): if id_ is None: self.req_id_cnt += 1 id_ = self.req_id_cnt for key, val in params.items(): if type(val) == list: params[key] = ",".join([str(v) for v in val]) self.cmd_buffer.append( { "service": service.upper(), "command": command.upper(), "requestid": str(id_), "account": self.acc_id, "source": self.app_id, "parameters": params, } ) if send: reqs = {"requests": self.cmd_buffer} self.ws.send(json.dumps(reqs)) self.cmd_buffer = [] self._log("SENT", reqs) return id_ def _on_ws_open(self, ws): creds = { "userid": self.acc_id, "token": self.principles["streamerInfo"]["token"], "company": self.principles["accounts"][0]["company"], "segment": self.principles["accounts"][0]["segment"], "cddomain": self.principles["accounts"][0]["accountCdDomainId"], "usergroup": self.principles["streamerInfo"]["userGroup"], "accesslevel": self.principles["streamerInfo"]["accessLevel"], "authorized": "Y", "timestamp": self.token_ts, "appid": self.app_id, "acl": self.principles["streamerInfo"]["acl"], } login_params = { "credential": urlencode(creds), "token": self.principles["streamerInfo"]["token"], "version": "1.0", } self.ws = ws self._cmd("admin", "login", login_params, id_="login") def _on_ws_msg(self, msg): msg_json = json.loads(msg) for resp in msg_json.get("response", []): self._on_resp(resp) for note in msg_json.get("notify", []): self._on_notify(note) for data in msg_json.get("data", []): self._on_data(data) def _on_ws_error(self, err): self._log("ERROR", err) def _on_ws_close(self): self._log("CLOSED") def _on_resp(self, resp): self._log("RESP", resp) if resp["requestid"] == "login": self.ws_ready = True def _on_notify(self, info): self._log("NOTIFY", info) def _on_data(self, data): key = _msg_to_key(data) name = SUB_ID_TO_NAME[key] self._log("DATA", key, data) def _append_data(q): if q is not None: q.put((name, data["content"])) _append_data(self.data_qs[key]) _append_data(self.data_qs["*"]) def start(self): ws = websocket.WebSocketApp( self.ws_uri, on_message=lambda ws, msg: self._on_ws_msg(msg), on_error=lambda err: self._on_ws_error(err), on_close=lambda ws: self._on_ws_close(), on_open=lambda ws: self._on_ws_open(ws), ) self.ws_started = True self.thread = threading.Thread(target=ws.run_forever) self.thread.start() while not self.ws_ready: time.sleep(0.1) def subscribe(self, name, **params): check_assert(self.ws_ready, "Websocket not ready") check_assert(name in SUB_TYPES) check_assert(len(params["symbols"]) > 0, "At least one symbol needed.") service, cmd, id_, output_names, default_fields, mods = SUB_TYPES[name] for mod, translation in mods.items(): selected = translation.get(params.get(mod)) check_assert(selected is not None, mod + " not provided") service = service.replace(mod, selected) id_ = id_.replace(mod, selected) self._cmd(service, cmd, {"keys": params.get("symbols", ""), "fields": params.get("fields", default_fields)}) return self._make_queue_iter("news", id_) def live_data(self): return self._make_queue_iter("*", "*")() def _make_queue_iter(self, clean_name, name): data_q = self.data_qs[name] if data_q is None: data_q = queue.Queue() self.data_qs[name] = data_q def data_iter(): while True: type_name, items = data_q.get(block=True) yield StreamData(type_name, items) return data_iter def logout(self): check_assert(self.ws_ready, "Websocket not ready") self._cmd("admin", "logout") def _iso_to_ms(iso_date): date = datetime.strptime(iso_date, "%Y-%m-%dT%H:%M:%S%z") return int(date.timestamp() * 1000) def _msg_to_key(msg): return "{}-{}".format(msg["service"], msg["command"])
tofino-model.py
# coding=utf-8 # Copyright 2018-present Open Networking Foundation # SPDX-License-Identifier: Apache-2.0 ''' This module contains a switch class for Mininet: StratumTofinoModel Usage ----- From withing the Docker container, you can run Mininet using the following: $ mn --custom tools/mininet/tofino-model.py --switch stratum-t-model --link tofino ''' import json import multiprocessing import os import socket import threading import time from mininet.log import warn from mininet.node import Switch, Host from mininet.link import Link TOFINO_MODEL_BIN = 'tofino-model' STRATUM_BIN = 'stratum_bf' # DEV_STRATUM_BIN = '/root/stratum/bazel-bin/stratum/hal/bin/barefoot/stratum_bf' def watchdog(sw): try: with open(sw.keepalive, "w") as f: f.write(f"Remove this file to terminate {sw.name}") while True: if StratumTofinoModel.mininet_exception == 1 \ or not os.path.isfile(sw.keepalive): sw.stop() return if sw.stopped: return # protect against already crashed process, will be none and fail to poll() if sw.modelProc_h is not None and sw.stratumProc_h is not None: # poll open proc handles if sw.modelProc_h.poll() is None and sw.stratumProc_h.poll() is None: time.sleep(1) else: warn("\n*** WARN: switch %s died ☠️ \n" % sw.name) sw.stop() return except Exception as e: warn("*** ERROR: " + e.message) sw.stop() class StratumTofinoModel(Switch): mininet_exception = multiprocessing.Value('i', 0) nextNodeId = 0 def __init__(self, name, inNamespace = True, sdeInstall="/root/sde/install", bfSwitchdConfig="/etc/stratum/tofino_skip_p4.conf", **kwargs): Switch.__init__(self, name, inNamespace = True, **kwargs) self.sdeInstall = sdeInstall self.bfSwitchdConfig = bfSwitchdConfig self.nodeId = StratumTofinoModel.nextNodeId * 64 StratumTofinoModel.nextNodeId += 1 self.tmpDir = '/tmp/%s' % self.name self.chassisConfigFile = '%s/chassis-config.txt' % self.tmpDir self.portVethFile = '%s/ports.json' % self.tmpDir # process handles for tofino model and stratum self.modelProcHandle = None self.stratumProcHandle = None # !(run) or run ? boolean bit self.stopped = True # In case of exceptions, mininet removes *.out files from /tmp. We use # this as a signal to terminate the switch instance (if active). self.keepalive = '/tmp/%s-watchdog.out' % self.name # Remove files from previous executions self.cmd("rm -rf %s" % self.tmpDir) os.mkdir(self.tmpDir) def stop(self, deleteIntfs=True): """Terminate switch.""" self.stopped = True if self.anyProcHandleLive(): self.tryTerminate() self.modelProcHandle = None self.stratumProcHandle = None Switch.stop(self, deleteIntfs) def start(self, controllers): if not self.stopped: return #TODO this could prob be replaced by setting an ip in the parent.init # or something to trigger ip link up... self.cmd("/usr/sbin/ip l set dev lo up") with open(self.chassisConfigFile, 'w') as fp: fp.write(self.getChassisConfig()) with open(self.portVethFile, 'w') as fp: fp.write(self.getPortVethMap()) tof_cmd_string = " ".join( [ TOFINO_MODEL_BIN, f'--p4-target-config={self.bfSwitchdConfig}', f'-f{self.portVethFile}' ] ) stratum_cmd_string = " ".join( [ STRATUM_BIN, f'-chassis_config_file={self.chassisConfigFile}', '-enable_onlp=false', '-bf_switchd_background=false', '-v=2', f'-bf_sde_install={self.sdeInstall}', f'-bf_switchd_cfg={self.bfSwitchdConfig}', ] ) try: # Write cmd_string to log for debugging. self.modelLogHandle = open(f'{self.tmpDir}/tofino_model_process.log' , "w") self.modelLogHandle.write(tof_cmd_string + "\n\n" + "-" * 80 + "\n\n") self.modelLogHandle.flush() self.stratumLogHandle = open(f'{self.tmpDir}/stratum_process.log', "w") self.stratumLogHandle.write(stratum_cmd_string + "\n\n" + "-" * 80 + "\n\n") self.stratumLogHandle.flush() self.modelProcHandle = self.popen(tof_cmd_string, stdout=self.t_logfd, stderr=self.t_logfd) self.stratumProcHandle = self.popen(stratum_cmd_string, stdout=self.s_logfd, stderr=self.s_logfd) # We want to be notified if processes quits prematurely... self.stopped = False threading.Thread(target=watchdog, args=[self]).start() except Exception: StratumTofinoModel.mininet_exception = 1 self.stop() raise def getPortVethMap(self): intf_number = 1 portsVeth = list() for intf_name in self.intfNames(): if intf_name == 'lo': continue portsVeth.append( { "device_port": intf_number, "veth1": int(intf_name[4:]), "veth2": int(intf_name[4:])+100 } ) intf_number+=1 data = { "PortToVeth": portsVeth } return json.dumps(data, indent=4) + "\n" def getChassisConfig(self): config = """description: "chassis config bf tofino model {name}" chassis {{ platform: PLT_GENERIC_BAREFOOT_TOFINO name: "{name}" }} nodes {{ id: {nodeId} name: "{name}" slot: 1 index: 1 }}\n""".format(name=self.name, nodeId=self.nodeId) intf_number = 1 for intf_name in self.intfNames(): if intf_name == 'lo': continue config = config + """singleton_ports {{ id: {intfNumber} name: "{intfName}" slot: 1 port: {intfNumber} channel: 1 speed_bps: 10000000000 config_params {{ admin_state: ADMIN_STATE_ENABLED }} node: {nodeId} }}\n""".format(intfName=intf_name, intfNumber=intf_number, nodeId=self.nodeId) intf_number += 1 return config def anyProcHandleLive(self): return self.modelProcHandle is not None or self.stratumProcHandle is not None def tryTerminate(self): if self.modelProcHandle is not None: if self.modelProcHandle.poll() is None: self.modelProcHandle.terminate() self.modelProcHandle.wait() if self.stratumProc_h is not None: if self.stratumProcHandle.poll() is None: self.stratumProcHandle.terminate() self.stratumProcHandle.wait() if self.modelLogHandle is not None: self.modelLogHandle.close() self.modelLogHandle = None if self.stratumLogHandle is not None: self.stratumLogHandle.close() self.stratumLogHandle = None class NoOffloadHost(Host): def __init__(self, name, inNamespace=True, **params): Host.__init__(self, name, inNamespace=inNamespace, **params) def config(self, **params): r = super(Host, self).config(**params) for off in ["rx", "tx", "sg"]: cmd = "/sbin/ethtool --offload %s %s off" \ % (self.defaultIntf(), off) self.cmd(cmd) return r class TofinoLink(Link): "Link with tofino port numbering i.e. only allows veth%d" def __init__(self, *args, **kwargs): Link.__init__(self, *args, **kwargs) def intfName(self, node, n): "Construct a tofmodel veth interface vethN for interface n." # skip over Hosts as the nodeId not present if isinstance(node, Host): return node.name + '-eth' + repr( n ) return f"veth{node.nodeId-1+n}" # Exports for bin/mn switches = {'stratum-t-model': StratumTofinoModel} hosts = {'no-offload-host': NoOffloadHost} LINKS = { 'default': Link, # Note: overridden below # 'tc': TCLink, # 'tcu': TCULink, # 'ovs': OVSLink, 'tofino': TofinoLink}
test_urllib.py
"""Regresssion tests for urllib""" import urllib import httplib import unittest import os import sys import mimetools import tempfile import StringIO from test import test_support from base64 import b64encode def hexescape(char): """Escape char as RFC 2396 specifies""" hex_repr = hex(ord(char))[2:].upper() if len(hex_repr) == 1: hex_repr = "0%s" % hex_repr return "%" + hex_repr class FakeHTTPMixin(object): def fakehttp(self, fakedata): class FakeSocket(StringIO.StringIO): def sendall(self, data): FakeHTTPConnection.buf = data def makefile(self, *args, **kwds): return self def read(self, amt=None): if self.closed: return "" return StringIO.StringIO.read(self, amt) def readline(self, length=None): if self.closed: return "" return StringIO.StringIO.readline(self, length) class FakeHTTPConnection(httplib.HTTPConnection): # buffer to store data for verification in urlopen tests. buf = "" def connect(self): self.sock = FakeSocket(fakedata) assert httplib.HTTP._connection_class == httplib.HTTPConnection httplib.HTTP._connection_class = FakeHTTPConnection def unfakehttp(self): httplib.HTTP._connection_class = httplib.HTTPConnection class urlopen_FileTests(unittest.TestCase): """Test urlopen() opening a temporary file. Try to test as much functionality as possible so as to cut down on reliance on connecting to the Net for testing. """ def setUp(self): """Setup of a temp file to use for testing""" self.text = "test_urllib: %s\n" % self.__class__.__name__ FILE = file(test_support.TESTFN, 'wb') try: FILE.write(self.text) finally: FILE.close() self.pathname = test_support.TESTFN self.returned_obj = urllib.urlopen("file:%s" % self.pathname) def tearDown(self): """Shut down the open object""" self.returned_obj.close() os.remove(test_support.TESTFN) def test_interface(self): # Make sure object returned by urlopen() has the specified methods for attr in ("read", "readline", "readlines", "fileno", "close", "info", "geturl", "getcode", "__iter__"): self.assertTrue(hasattr(self.returned_obj, attr), "object returned by urlopen() lacks %s attribute" % attr) def test_read(self): self.assertEqual(self.text, self.returned_obj.read()) def test_readline(self): self.assertEqual(self.text, self.returned_obj.readline()) self.assertEqual('', self.returned_obj.readline(), "calling readline() after exhausting the file did not" " return an empty string") def test_readlines(self): lines_list = self.returned_obj.readlines() self.assertEqual(len(lines_list), 1, "readlines() returned the wrong number of lines") self.assertEqual(lines_list[0], self.text, "readlines() returned improper text") def test_fileno(self): file_num = self.returned_obj.fileno() self.assertIsInstance(file_num, int, "fileno() did not return an int") self.assertEqual(os.read(file_num, len(self.text)), self.text, "Reading on the file descriptor returned by fileno() " "did not return the expected text") def test_close(self): # Test close() by calling it hear and then having it be called again # by the tearDown() method for the test self.returned_obj.close() def test_info(self): self.assertIsInstance(self.returned_obj.info(), mimetools.Message) def test_geturl(self): self.assertEqual(self.returned_obj.geturl(), self.pathname) def test_getcode(self): self.assertEqual(self.returned_obj.getcode(), None) def test_iter(self): # Test iterator # Don't need to count number of iterations since test would fail the # instant it returned anything beyond the first line from the # comparison for line in self.returned_obj.__iter__(): self.assertEqual(line, self.text) def test_relativelocalfile(self): self.assertRaises(ValueError,urllib.urlopen,'./' + self.pathname) class ProxyTests(unittest.TestCase): def setUp(self): # Records changes to env vars self.env = test_support.EnvironmentVarGuard() # Delete all proxy related env vars for k in os.environ.keys(): if 'proxy' in k.lower(): self.env.unset(k) def tearDown(self): # Restore all proxy related env vars self.env.__exit__() del self.env def test_getproxies_environment_keep_no_proxies(self): self.env.set('NO_PROXY', 'localhost') proxies = urllib.getproxies_environment() # getproxies_environment use lowered case truncated (no '_proxy') keys self.assertEqual('localhost', proxies['no']) # List of no_proxies with space. self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com') self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com')) class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin): """Test urlopen() opening a fake http connection.""" def test_read(self): self.fakehttp('Hello!') try: fp = urllib.urlopen("http://python.org/") self.assertEqual(fp.readline(), 'Hello!') self.assertEqual(fp.readline(), '') self.assertEqual(fp.geturl(), 'http://python.org/') self.assertEqual(fp.getcode(), 200) finally: self.unfakehttp() def test_url_fragment(self): # Issue #11703: geturl() omits fragments in the original URL. url = 'http://docs.python.org/library/urllib.html#OK' self.fakehttp('Hello!') try: fp = urllib.urlopen(url) self.assertEqual(fp.geturl(), url) finally: self.unfakehttp() def test_read_bogus(self): # urlopen() should raise IOError for many error codes. self.fakehttp('''HTTP/1.1 401 Authentication Required Date: Wed, 02 Jan 2008 03:03:54 GMT Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e Connection: close Content-Type: text/html; charset=iso-8859-1 ''') try: self.assertRaises(IOError, urllib.urlopen, "http://python.org/") finally: self.unfakehttp() def test_invalid_redirect(self): # urlopen() should raise IOError for many error codes. self.fakehttp("""HTTP/1.1 302 Found Date: Wed, 02 Jan 2008 03:03:54 GMT Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e Location: file:README Connection: close Content-Type: text/html; charset=iso-8859-1 """) try: self.assertRaises(IOError, urllib.urlopen, "http://python.org/") finally: self.unfakehttp() def test_empty_socket(self): # urlopen() raises IOError if the underlying socket does not send any # data. (#1680230) self.fakehttp('') try: self.assertRaises(IOError, urllib.urlopen, 'http://something') finally: self.unfakehttp() def test_missing_localfile(self): self.assertRaises(IOError, urllib.urlopen, 'file://localhost/a/missing/file.py') fd, tmp_file = tempfile.mkstemp() tmp_fileurl = 'file://localhost/' + tmp_file.replace(os.path.sep, '/') self.assertTrue(os.path.exists(tmp_file)) try: fp = urllib.urlopen(tmp_fileurl) fp.close() finally: os.close(fd) os.unlink(tmp_file) self.assertFalse(os.path.exists(tmp_file)) self.assertRaises(IOError, urllib.urlopen, tmp_fileurl) def test_ftp_nonexisting(self): self.assertRaises(IOError, urllib.urlopen, 'ftp://localhost/not/existing/file.py') def test_userpass_inurl(self): self.fakehttp('Hello!') try: fakehttp_wrapper = httplib.HTTP._connection_class fp = urllib.urlopen("http://user:pass@python.org/") authorization = ("Authorization: Basic %s\r\n" % b64encode('user:pass')) # The authorization header must be in place self.assertIn(authorization, fakehttp_wrapper.buf) self.assertEqual(fp.readline(), "Hello!") self.assertEqual(fp.readline(), "") self.assertEqual(fp.geturl(), 'http://user:pass@python.org/') self.assertEqual(fp.getcode(), 200) finally: self.unfakehttp() def test_userpass_with_spaces_inurl(self): self.fakehttp('Hello!') try: url = "http://a b:c d@python.org/" fakehttp_wrapper = httplib.HTTP._connection_class authorization = ("Authorization: Basic %s\r\n" % b64encode('a b:c d')) fp = urllib.urlopen(url) # The authorization header must be in place self.assertIn(authorization, fakehttp_wrapper.buf) self.assertEqual(fp.readline(), "Hello!") self.assertEqual(fp.readline(), "") # the spaces are quoted in URL so no match self.assertNotEqual(fp.geturl(), url) self.assertEqual(fp.getcode(), 200) finally: self.unfakehttp() class urlretrieve_FileTests(unittest.TestCase): """Test urllib.urlretrieve() on local files""" def setUp(self): # Create a list of temporary files. Each item in the list is a file # name (absolute path or relative to the current working directory). # All files in this list will be deleted in the tearDown method. Note, # this only helps to makes sure temporary files get deleted, but it # does nothing about trying to close files that may still be open. It # is the responsibility of the developer to properly close files even # when exceptional conditions occur. self.tempFiles = [] # Create a temporary file. self.registerFileForCleanUp(test_support.TESTFN) self.text = 'testing urllib.urlretrieve' try: FILE = file(test_support.TESTFN, 'wb') FILE.write(self.text) FILE.close() finally: try: FILE.close() except: pass def tearDown(self): # Delete the temporary files. for each in self.tempFiles: try: os.remove(each) except: pass def constructLocalFileUrl(self, filePath): return "file://%s" % urllib.pathname2url(os.path.abspath(filePath)) def createNewTempFile(self, data=""): """Creates a new temporary file containing the specified data, registers the file for deletion during the test fixture tear down, and returns the absolute path of the file.""" newFd, newFilePath = tempfile.mkstemp() try: self.registerFileForCleanUp(newFilePath) newFile = os.fdopen(newFd, "wb") newFile.write(data) newFile.close() finally: try: newFile.close() except: pass return newFilePath def registerFileForCleanUp(self, fileName): self.tempFiles.append(fileName) def test_basic(self): # Make sure that a local file just gets its own location returned and # a headers value is returned. result = urllib.urlretrieve("file:%s" % test_support.TESTFN) self.assertEqual(result[0], test_support.TESTFN) self.assertIsInstance(result[1], mimetools.Message, "did not get a mimetools.Message instance as " "second returned value") def test_copy(self): # Test that setting the filename argument works. second_temp = "%s.2" % test_support.TESTFN self.registerFileForCleanUp(second_temp) result = urllib.urlretrieve(self.constructLocalFileUrl( test_support.TESTFN), second_temp) self.assertEqual(second_temp, result[0]) self.assertTrue(os.path.exists(second_temp), "copy of the file was not " "made") FILE = file(second_temp, 'rb') try: text = FILE.read() FILE.close() finally: try: FILE.close() except: pass self.assertEqual(self.text, text) def test_reporthook(self): # Make sure that the reporthook works. def hooktester(count, block_size, total_size, count_holder=[0]): self.assertIsInstance(count, int) self.assertIsInstance(block_size, int) self.assertIsInstance(total_size, int) self.assertEqual(count, count_holder[0]) count_holder[0] = count_holder[0] + 1 second_temp = "%s.2" % test_support.TESTFN self.registerFileForCleanUp(second_temp) urllib.urlretrieve(self.constructLocalFileUrl(test_support.TESTFN), second_temp, hooktester) def test_reporthook_0_bytes(self): # Test on zero length file. Should call reporthook only 1 time. report = [] def hooktester(count, block_size, total_size, _report=report): _report.append((count, block_size, total_size)) srcFileName = self.createNewTempFile() urllib.urlretrieve(self.constructLocalFileUrl(srcFileName), test_support.TESTFN, hooktester) self.assertEqual(len(report), 1) self.assertEqual(report[0][2], 0) def test_reporthook_5_bytes(self): # Test on 5 byte file. Should call reporthook only 2 times (once when # the "network connection" is established and once when the block is # read). Since the block size is 8192 bytes, only one block read is # required to read the entire file. report = [] def hooktester(count, block_size, total_size, _report=report): _report.append((count, block_size, total_size)) srcFileName = self.createNewTempFile("x" * 5) urllib.urlretrieve(self.constructLocalFileUrl(srcFileName), test_support.TESTFN, hooktester) self.assertEqual(len(report), 2) self.assertEqual(report[0][1], 8192) self.assertEqual(report[0][2], 5) def test_reporthook_8193_bytes(self): # Test on 8193 byte file. Should call reporthook only 3 times (once # when the "network connection" is established, once for the next 8192 # bytes, and once for the last byte). report = [] def hooktester(count, block_size, total_size, _report=report): _report.append((count, block_size, total_size)) srcFileName = self.createNewTempFile("x" * 8193) urllib.urlretrieve(self.constructLocalFileUrl(srcFileName), test_support.TESTFN, hooktester) self.assertEqual(len(report), 3) self.assertEqual(report[0][1], 8192) self.assertEqual(report[0][2], 8193) class urlretrieve_HttpTests(unittest.TestCase, FakeHTTPMixin): """Test urllib.urlretrieve() using fake http connections""" def test_short_content_raises_ContentTooShortError(self): self.fakehttp('''HTTP/1.1 200 OK Date: Wed, 02 Jan 2008 03:03:54 GMT Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e Connection: close Content-Length: 100 Content-Type: text/html; charset=iso-8859-1 FF ''') def _reporthook(par1, par2, par3): pass try: self.assertRaises(urllib.ContentTooShortError, urllib.urlretrieve, 'http://example.com', reporthook=_reporthook) finally: self.unfakehttp() def test_short_content_raises_ContentTooShortError_without_reporthook(self): self.fakehttp('''HTTP/1.1 200 OK Date: Wed, 02 Jan 2008 03:03:54 GMT Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e Connection: close Content-Length: 100 Content-Type: text/html; charset=iso-8859-1 FF ''') try: self.assertRaises(urllib.ContentTooShortError, urllib.urlretrieve, 'http://example.com/') finally: self.unfakehttp() class QuotingTests(unittest.TestCase): """Tests for urllib.quote() and urllib.quote_plus() According to RFC 2396 ("Uniform Resource Identifiers), to escape a character you write it as '%' + <2 character US-ASCII hex value>. The Python code of ``'%' + hex(ord(<character>))[2:]`` escapes a character properly. Case does not matter on the hex letters. The various character sets specified are: Reserved characters : ";/?:@&=+$," Have special meaning in URIs and must be escaped if not being used for their special meaning Data characters : letters, digits, and "-_.!~*'()" Unreserved and do not need to be escaped; can be, though, if desired Control characters : 0x00 - 0x1F, 0x7F Have no use in URIs so must be escaped space : 0x20 Must be escaped Delimiters : '<>#%"' Must be escaped Unwise : "{}|\^[]`" Must be escaped """ def test_never_quote(self): # Make sure quote() does not quote letters, digits, and "_,.-" do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "_.-"]) result = urllib.quote(do_not_quote) self.assertEqual(do_not_quote, result, "using quote(): %s != %s" % (do_not_quote, result)) result = urllib.quote_plus(do_not_quote) self.assertEqual(do_not_quote, result, "using quote_plus(): %s != %s" % (do_not_quote, result)) def test_default_safe(self): # Test '/' is default value for 'safe' parameter self.assertEqual(urllib.quote.func_defaults[0], '/') def test_safe(self): # Test setting 'safe' parameter does what it should do quote_by_default = "<>" result = urllib.quote(quote_by_default, safe=quote_by_default) self.assertEqual(quote_by_default, result, "using quote(): %s != %s" % (quote_by_default, result)) result = urllib.quote_plus(quote_by_default, safe=quote_by_default) self.assertEqual(quote_by_default, result, "using quote_plus(): %s != %s" % (quote_by_default, result)) def test_default_quoting(self): # Make sure all characters that should be quoted are by default sans # space (separate test for that). should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F should_quote.append('<>#%"{}|\^[]`') should_quote.append(chr(127)) # For 0x7F should_quote = ''.join(should_quote) for char in should_quote: result = urllib.quote(char) self.assertEqual(hexescape(char), result, "using quote(): %s should be escaped to %s, not %s" % (char, hexescape(char), result)) result = urllib.quote_plus(char) self.assertEqual(hexescape(char), result, "using quote_plus(): " "%s should be escapes to %s, not %s" % (char, hexescape(char), result)) del should_quote partial_quote = "ab[]cd" expected = "ab%5B%5Dcd" result = urllib.quote(partial_quote) self.assertEqual(expected, result, "using quote(): %s != %s" % (expected, result)) result = urllib.quote_plus(partial_quote) self.assertEqual(expected, result, "using quote_plus(): %s != %s" % (expected, result)) self.assertRaises(TypeError, urllib.quote, None) def test_quoting_space(self): # Make sure quote() and quote_plus() handle spaces as specified in # their unique way result = urllib.quote(' ') self.assertEqual(result, hexescape(' '), "using quote(): %s != %s" % (result, hexescape(' '))) result = urllib.quote_plus(' ') self.assertEqual(result, '+', "using quote_plus(): %s != +" % result) given = "a b cd e f" expect = given.replace(' ', hexescape(' ')) result = urllib.quote(given) self.assertEqual(expect, result, "using quote(): %s != %s" % (expect, result)) expect = given.replace(' ', '+') result = urllib.quote_plus(given) self.assertEqual(expect, result, "using quote_plus(): %s != %s" % (expect, result)) def test_quoting_plus(self): self.assertEqual(urllib.quote_plus('alpha+beta gamma'), 'alpha%2Bbeta+gamma') self.assertEqual(urllib.quote_plus('alpha+beta gamma', '+'), 'alpha+beta+gamma') class UnquotingTests(unittest.TestCase): """Tests for unquote() and unquote_plus() See the doc string for quoting_Tests for details on quoting and such. """ def test_unquoting(self): # Make sure unquoting of all ASCII values works escape_list = [] for num in range(128): given = hexescape(chr(num)) expect = chr(num) result = urllib.unquote(given) self.assertEqual(expect, result, "using unquote(): %s != %s" % (expect, result)) result = urllib.unquote_plus(given) self.assertEqual(expect, result, "using unquote_plus(): %s != %s" % (expect, result)) escape_list.append(given) escape_string = ''.join(escape_list) del escape_list result = urllib.unquote(escape_string) self.assertEqual(result.count('%'), 1, "using quote(): not all characters escaped; %s" % result) result = urllib.unquote(escape_string) self.assertEqual(result.count('%'), 1, "using unquote(): not all characters escaped: " "%s" % result) def test_unquoting_badpercent(self): # Test unquoting on bad percent-escapes given = '%xab' expect = given result = urllib.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) given = '%x' expect = given result = urllib.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) given = '%' expect = given result = urllib.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) def test_unquoting_mixed_case(self): # Test unquoting on mixed-case hex digits in the percent-escapes given = '%Ab%eA' expect = '\xab\xea' result = urllib.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) def test_unquoting_parts(self): # Make sure unquoting works when have non-quoted characters # interspersed given = 'ab%sd' % hexescape('c') expect = "abcd" result = urllib.unquote(given) self.assertEqual(expect, result, "using quote(): %s != %s" % (expect, result)) result = urllib.unquote_plus(given) self.assertEqual(expect, result, "using unquote_plus(): %s != %s" % (expect, result)) def test_unquoting_plus(self): # Test difference between unquote() and unquote_plus() given = "are+there+spaces..." expect = given result = urllib.unquote(given) self.assertEqual(expect, result, "using unquote(): %s != %s" % (expect, result)) expect = given.replace('+', ' ') result = urllib.unquote_plus(given) self.assertEqual(expect, result, "using unquote_plus(): %s != %s" % (expect, result)) def test_unquote_with_unicode(self): r = urllib.unquote(u'br%C3%BCckner_sapporo_20050930.doc') self.assertEqual(r, u'br\xc3\xbcckner_sapporo_20050930.doc') class urlencode_Tests(unittest.TestCase): """Tests for urlencode()""" def help_inputtype(self, given, test_type): """Helper method for testing different input types. 'given' must lead to only the pairs: * 1st, 1 * 2nd, 2 * 3rd, 3 Test cannot assume anything about order. Docs make no guarantee and have possible dictionary input. """ expect_somewhere = ["1st=1", "2nd=2", "3rd=3"] result = urllib.urlencode(given) for expected in expect_somewhere: self.assertIn(expected, result, "testing %s: %s not found in %s" % (test_type, expected, result)) self.assertEqual(result.count('&'), 2, "testing %s: expected 2 '&'s; got %s" % (test_type, result.count('&'))) amp_location = result.index('&') on_amp_left = result[amp_location - 1] on_amp_right = result[amp_location + 1] self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(), "testing %s: '&' not located in proper place in %s" % (test_type, result)) self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps "testing %s: " "unexpected number of characters: %s != %s" % (test_type, len(result), (5 * 3) + 2)) def test_using_mapping(self): # Test passing in a mapping object as an argument. self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'}, "using dict as input type") def test_using_sequence(self): # Test passing in a sequence of two-item sequences as an argument. self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')], "using sequence of two-item tuples as input") def test_quoting(self): # Make sure keys and values are quoted using quote_plus() given = {"&":"="} expect = "%s=%s" % (hexescape('&'), hexescape('=')) result = urllib.urlencode(given) self.assertEqual(expect, result) given = {"key name":"A bunch of pluses"} expect = "key+name=A+bunch+of+pluses" result = urllib.urlencode(given) self.assertEqual(expect, result) def test_doseq(self): # Test that passing True for 'doseq' parameter works correctly given = {'sequence':['1', '2', '3']} expect = "sequence=%s" % urllib.quote_plus(str(['1', '2', '3'])) result = urllib.urlencode(given) self.assertEqual(expect, result) result = urllib.urlencode(given, True) for value in given["sequence"]: expect = "sequence=%s" % value self.assertIn(expect, result) self.assertEqual(result.count('&'), 2, "Expected 2 '&'s, got %s" % result.count('&')) class Pathname_Tests(unittest.TestCase): """Test pathname2url() and url2pathname()""" def test_basic(self): # Make sure simple tests pass expected_path = os.path.join("parts", "of", "a", "path") expected_url = "parts/of/a/path" result = urllib.pathname2url(expected_path) self.assertEqual(expected_url, result, "pathname2url() failed; %s != %s" % (result, expected_url)) result = urllib.url2pathname(expected_url) self.assertEqual(expected_path, result, "url2pathame() failed; %s != %s" % (result, expected_path)) def test_quoting(self): # Test automatic quoting and unquoting works for pathnam2url() and # url2pathname() respectively given = os.path.join("needs", "quot=ing", "here") expect = "needs/%s/here" % urllib.quote("quot=ing") result = urllib.pathname2url(given) self.assertEqual(expect, result, "pathname2url() failed; %s != %s" % (expect, result)) expect = given result = urllib.url2pathname(result) self.assertEqual(expect, result, "url2pathname() failed; %s != %s" % (expect, result)) given = os.path.join("make sure", "using_quote") expect = "%s/using_quote" % urllib.quote("make sure") result = urllib.pathname2url(given) self.assertEqual(expect, result, "pathname2url() failed; %s != %s" % (expect, result)) given = "make+sure/using_unquote" expect = os.path.join("make+sure", "using_unquote") result = urllib.url2pathname(given) self.assertEqual(expect, result, "url2pathname() failed; %s != %s" % (expect, result)) @unittest.skipUnless(sys.platform == 'win32', 'test specific to the nturl2path library') def test_ntpath(self): given = ('/C:/', '///C:/', '/C|//') expect = 'C:\\' for url in given: result = urllib.url2pathname(url) self.assertEqual(expect, result, 'nturl2path.url2pathname() failed; %s != %s' % (expect, result)) given = '///C|/path' expect = 'C:\\path' result = urllib.url2pathname(given) self.assertEqual(expect, result, 'nturl2path.url2pathname() failed; %s != %s' % (expect, result)) class Utility_Tests(unittest.TestCase): """Testcase to test the various utility functions in the urllib.""" def test_splitpasswd(self): """Some of the password examples are not sensible, but it is added to confirming to RFC2617 and addressing issue4675. """ self.assertEqual(('user', 'ab'),urllib.splitpasswd('user:ab')) self.assertEqual(('user', 'a\nb'),urllib.splitpasswd('user:a\nb')) self.assertEqual(('user', 'a\tb'),urllib.splitpasswd('user:a\tb')) self.assertEqual(('user', 'a\rb'),urllib.splitpasswd('user:a\rb')) self.assertEqual(('user', 'a\fb'),urllib.splitpasswd('user:a\fb')) self.assertEqual(('user', 'a\vb'),urllib.splitpasswd('user:a\vb')) self.assertEqual(('user', 'a:b'),urllib.splitpasswd('user:a:b')) self.assertEqual(('user', 'a b'),urllib.splitpasswd('user:a b')) self.assertEqual(('user 2', 'ab'),urllib.splitpasswd('user 2:ab')) self.assertEqual(('user+1', 'a+b'),urllib.splitpasswd('user+1:a+b')) def test_splitport(self): splitport = urllib.splitport self.assertEqual(splitport('parrot:88'), ('parrot', '88')) self.assertEqual(splitport('parrot'), ('parrot', None)) self.assertEqual(splitport('parrot:'), ('parrot', None)) self.assertEqual(splitport('127.0.0.1'), ('127.0.0.1', None)) self.assertEqual(splitport('parrot:cheese'), ('parrot:cheese', None)) def test_splitnport(self): splitnport = urllib.splitnport self.assertEqual(splitnport('parrot:88'), ('parrot', 88)) self.assertEqual(splitnport('parrot'), ('parrot', -1)) self.assertEqual(splitnport('parrot', 55), ('parrot', 55)) self.assertEqual(splitnport('parrot:'), ('parrot', -1)) self.assertEqual(splitnport('parrot:', 55), ('parrot', 55)) self.assertEqual(splitnport('127.0.0.1'), ('127.0.0.1', -1)) self.assertEqual(splitnport('127.0.0.1', 55), ('127.0.0.1', 55)) self.assertEqual(splitnport('parrot:cheese'), ('parrot', None)) self.assertEqual(splitnport('parrot:cheese', 55), ('parrot', None)) class URLopener_Tests(unittest.TestCase): """Testcase to test the open method of URLopener class.""" def test_quoted_open(self): class DummyURLopener(urllib.URLopener): def open_spam(self, url): return url self.assertEqual(DummyURLopener().open( 'spam://example/ /'),'//example/%20/') # test the safe characters are not quoted by urlopen self.assertEqual(DummyURLopener().open( "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"), "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/") # Just commented them out. # Can't really tell why keep failing in windows and sparc. # Everywhere else they work ok, but on those machines, sometimes # fail in one of the tests, sometimes in other. I have a linux, and # the tests go ok. # If anybody has one of the problematic environments, please help! # . Facundo # # def server(evt): # import socket, time # serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # serv.settimeout(3) # serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # serv.bind(("", 9093)) # serv.listen(5) # try: # conn, addr = serv.accept() # conn.send("1 Hola mundo\n") # cantdata = 0 # while cantdata < 13: # data = conn.recv(13-cantdata) # cantdata += len(data) # time.sleep(.3) # conn.send("2 No more lines\n") # conn.close() # except socket.timeout: # pass # finally: # serv.close() # evt.set() # # class FTPWrapperTests(unittest.TestCase): # # def setUp(self): # import ftplib, time, threading # ftplib.FTP.port = 9093 # self.evt = threading.Event() # threading.Thread(target=server, args=(self.evt,)).start() # time.sleep(.1) # # def tearDown(self): # self.evt.wait() # # def testBasic(self): # # connects # ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, []) # ftp.close() # # def testTimeoutNone(self): # # global default timeout is ignored # import socket # self.assertIsNone(socket.getdefaulttimeout()) # socket.setdefaulttimeout(30) # try: # ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, []) # finally: # socket.setdefaulttimeout(None) # self.assertEqual(ftp.ftp.sock.gettimeout(), 30) # ftp.close() # # def testTimeoutDefault(self): # # global default timeout is used # import socket # self.assertIsNone(socket.getdefaulttimeout()) # socket.setdefaulttimeout(30) # try: # ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, []) # finally: # socket.setdefaulttimeout(None) # self.assertEqual(ftp.ftp.sock.gettimeout(), 30) # ftp.close() # # def testTimeoutValue(self): # ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [], # timeout=30) # self.assertEqual(ftp.ftp.sock.gettimeout(), 30) # ftp.close() def test_main(): import warnings with warnings.catch_warnings(): warnings.filterwarnings('ignore', ".*urllib\.urlopen.*Python 3.0", DeprecationWarning) test_support.run_unittest( urlopen_FileTests, urlopen_HttpTests, urlretrieve_FileTests, urlretrieve_HttpTests, ProxyTests, QuotingTests, UnquotingTests, urlencode_Tests, Pathname_Tests, Utility_Tests, URLopener_Tests, #FTPWrapperTests, ) if __name__ == '__main__': test_main()
basic.py
# -*- coding: utf-8 -*- """ flask.testsuite.basic ~~~~~~~~~~~~~~~~~~~~~ The basic functionality. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import re import flask import pickle import unittest from datetime import datetime from threading import Thread from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning from werkzeug.exceptions import BadRequest, NotFound from werkzeug.http import parse_date from werkzeug.routing import BuildError class BasicFunctionalityTestCase(FlaskTestCase): def test_options_work(self): app = flask.Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return 'Hello World' rv = app.test_client().open('/', method='OPTIONS') self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST']) self.assert_equal(rv.data, b'') def test_options_on_multiple_rules(self): app = flask.Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return 'Hello World' @app.route('/', methods=['PUT']) def index_put(): return 'Aha!' rv = app.test_client().open('/', method='OPTIONS') self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']) def test_options_handling_disabled(self): app = flask.Flask(__name__) def index(): return 'Hello World!' index.provide_automatic_options = False app.route('/')(index) rv = app.test_client().open('/', method='OPTIONS') self.assert_equal(rv.status_code, 405) app = flask.Flask(__name__) def index2(): return 'Hello World!' index2.provide_automatic_options = True app.route('/', methods=['OPTIONS'])(index2) rv = app.test_client().open('/', method='OPTIONS') self.assert_equal(sorted(rv.allow), ['OPTIONS']) def test_request_dispatching(self): app = flask.Flask(__name__) @app.route('/') def index(): return flask.request.method @app.route('/more', methods=['GET', 'POST']) def more(): return flask.request.method c = app.test_client() self.assert_equal(c.get('/').data, b'GET') rv = c.post('/') self.assert_equal(rv.status_code, 405) self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS']) rv = c.head('/') self.assert_equal(rv.status_code, 200) self.assertTrue(not rv.data) # head truncates self.assert_equal(c.post('/more').data, b'POST') self.assert_equal(c.get('/more').data, b'GET') rv = c.delete('/more') self.assert_equal(rv.status_code, 405) self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST']) def test_url_mapping(self): app = flask.Flask(__name__) def index(): return flask.request.method def more(): return flask.request.method app.add_url_rule('/', 'index', index) app.add_url_rule('/more', 'more', more, methods=['GET', 'POST']) c = app.test_client() self.assert_equal(c.get('/').data, b'GET') rv = c.post('/') self.assert_equal(rv.status_code, 405) self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS']) rv = c.head('/') self.assert_equal(rv.status_code, 200) self.assertTrue(not rv.data) # head truncates self.assert_equal(c.post('/more').data, b'POST') self.assert_equal(c.get('/more').data, b'GET') rv = c.delete('/more') self.assert_equal(rv.status_code, 405) self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST']) def test_werkzeug_routing(self): from werkzeug.routing import Submount, Rule app = flask.Flask(__name__) app.url_map.add(Submount('/foo', [ Rule('/bar', endpoint='bar'), Rule('/', endpoint='index') ])) def bar(): return 'bar' def index(): return 'index' app.view_functions['bar'] = bar app.view_functions['index'] = index c = app.test_client() self.assert_equal(c.get('/foo/').data, b'index') self.assert_equal(c.get('/foo/bar').data, b'bar') def test_endpoint_decorator(self): from werkzeug.routing import Submount, Rule app = flask.Flask(__name__) app.url_map.add(Submount('/foo', [ Rule('/bar', endpoint='bar'), Rule('/', endpoint='index') ])) @app.endpoint('bar') def bar(): return 'bar' @app.endpoint('index') def index(): return 'index' c = app.test_client() self.assert_equal(c.get('/foo/').data, b'index') self.assert_equal(c.get('/foo/bar').data, b'bar') def test_session(self): app = flask.Flask(__name__) app.secret_key = 'testkey' @app.route('/set', methods=['POST']) def set(): flask.session['value'] = flask.request.form['value'] return 'value set' @app.route('/get') def get(): return flask.session['value'] c = app.test_client() self.assert_equal(c.post('/set', data={'value': '42'}).data, b'value set') self.assert_equal(c.get('/get').data, b'42') def test_session_using_server_name(self): app = flask.Flask(__name__) app.config.update( SECRET_KEY='foo', SERVER_NAME='example.com' ) @app.route('/') def index(): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com/') self.assertTrue('domain=.example.com' in rv.headers['set-cookie'].lower()) self.assertTrue('httponly' in rv.headers['set-cookie'].lower()) def test_session_using_server_name_and_port(self): app = flask.Flask(__name__) app.config.update( SECRET_KEY='foo', SERVER_NAME='example.com:8080' ) @app.route('/') def index(): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/') self.assertTrue('domain=.example.com' in rv.headers['set-cookie'].lower()) self.assertTrue('httponly' in rv.headers['set-cookie'].lower()) def test_session_using_application_root(self): class PrefixPathMiddleware(object): def __init__(self, app, prefix): self.app = app self.prefix = prefix def __call__(self, environ, start_response): environ['SCRIPT_NAME'] = self.prefix return self.app(environ, start_response) app = flask.Flask(__name__) app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar') app.config.update( SECRET_KEY='foo', APPLICATION_ROOT='/bar' ) @app.route('/') def index(): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/') self.assertTrue('path=/bar' in rv.headers['set-cookie'].lower()) def test_session_using_session_settings(self): app = flask.Flask(__name__) app.config.update( SECRET_KEY='foo', SERVER_NAME='www.example.com:8080', APPLICATION_ROOT='/test', SESSION_COOKIE_DOMAIN='.example.com', SESSION_COOKIE_HTTPONLY=False, SESSION_COOKIE_SECURE=True, SESSION_COOKIE_PATH='/' ) @app.route('/') def index(): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://www.example.com:8080/test/') cookie = rv.headers['set-cookie'].lower() self.assertTrue('domain=.example.com' in cookie) self.assertTrue('path=/;' in cookie) self.assertTrue('secure' in cookie) self.assertTrue('httponly' not in cookie) def test_missing_session(self): app = flask.Flask(__name__) def expect_exception(f, *args, **kwargs): try: f(*args, **kwargs) except RuntimeError as e: self.assertTrue(e.args and 'session is unavailable' in e.args[0]) else: self.assertTrue(False, 'expected exception') with app.test_request_context(): self.assertTrue(flask.session.get('missing_key') is None) expect_exception(flask.session.__setitem__, 'foo', 42) expect_exception(flask.session.pop, 'foo') def test_session_expiration(self): permanent = True app = flask.Flask(__name__) app.secret_key = 'testkey' @app.route('/') def index(): flask.session['test'] = 42 flask.session.permanent = permanent return '' @app.route('/test') def test(): return str(flask.session.permanent) client = app.test_client() rv = client.get('/') self.assertTrue('set-cookie' in rv.headers) match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie']) expires = parse_date(match.group()) expected = datetime.utcnow() + app.permanent_session_lifetime self.assert_equal(expires.year, expected.year) self.assert_equal(expires.month, expected.month) self.assert_equal(expires.day, expected.day) rv = client.get('/test') self.assert_equal(rv.data, b'True') permanent = False rv = app.test_client().get('/') self.assertTrue('set-cookie' in rv.headers) match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie']) self.assertTrue(match is None) def test_session_stored_last(self): app = flask.Flask(__name__) app.secret_key = 'development-key' app.testing = True @app.after_request def modify_session(response): flask.session['foo'] = 42 return response @app.route('/') def dump_session_contents(): return repr(flask.session.get('foo')) c = app.test_client() self.assert_equal(c.get('/').data, b'None') self.assert_equal(c.get('/').data, b'42') def test_session_special_types(self): app = flask.Flask(__name__) app.secret_key = 'development-key' app.testing = True now = datetime.utcnow().replace(microsecond=0) @app.after_request def modify_session(response): flask.session['m'] = flask.Markup('Hello!') flask.session['dt'] = now flask.session['t'] = (1, 2, 3) return response @app.route('/') def dump_session_contents(): return pickle.dumps(dict(flask.session)) c = app.test_client() c.get('/') rv = pickle.loads(c.get('/').data) self.assert_equal(rv['m'], flask.Markup('Hello!')) self.assert_equal(type(rv['m']), flask.Markup) self.assert_equal(rv['dt'], now) self.assert_equal(rv['t'], (1, 2, 3)) def test_flashes(self): app = flask.Flask(__name__) app.secret_key = 'testkey' with app.test_request_context(): self.assertTrue(not flask.session.modified) flask.flash('Zap') flask.session.modified = False flask.flash('Zip') self.assertTrue(flask.session.modified) self.assert_equal(list(flask.get_flashed_messages()), ['Zap', 'Zip']) def test_extended_flashing(self): # Be sure app.testing=True below, else tests can fail silently. # # Specifically, if app.testing is not set to True, the AssertionErrors # in the view functions will cause a 500 response to the test client # instead of propagating exceptions. app = flask.Flask(__name__) app.secret_key = 'testkey' app.testing = True @app.route('/') def index(): flask.flash('Hello World') flask.flash('Hello World', 'error') flask.flash(flask.Markup('<em>Testing</em>'), 'warning') return '' @app.route('/test/') def test(): messages = flask.get_flashed_messages() self.assert_equal(len(messages), 3) self.assert_equal(messages[0], 'Hello World') self.assert_equal(messages[1], 'Hello World') self.assert_equal(messages[2], flask.Markup('<em>Testing</em>')) return '' @app.route('/test_with_categories/') def test_with_categories(): messages = flask.get_flashed_messages(with_categories=True) self.assert_equal(len(messages), 3) self.assert_equal(messages[0], ('message', 'Hello World')) self.assert_equal(messages[1], ('error', 'Hello World')) self.assert_equal(messages[2], ('warning', flask.Markup('<em>Testing</em>'))) return '' @app.route('/test_filter/') def test_filter(): messages = flask.get_flashed_messages(category_filter=['message'], with_categories=True) self.assert_equal(len(messages), 1) self.assert_equal(messages[0], ('message', 'Hello World')) return '' @app.route('/test_filters/') def test_filters(): messages = flask.get_flashed_messages(category_filter=['message', 'warning'], with_categories=True) self.assert_equal(len(messages), 2) self.assert_equal(messages[0], ('message', 'Hello World')) self.assert_equal(messages[1], ('warning', flask.Markup('<em>Testing</em>'))) return '' @app.route('/test_filters_without_returning_categories/') def test_filters2(): messages = flask.get_flashed_messages(category_filter=['message', 'warning']) self.assert_equal(len(messages), 2) self.assert_equal(messages[0], 'Hello World') self.assert_equal(messages[1], flask.Markup('<em>Testing</em>')) return '' # Create new test client on each test to clean flashed messages. c = app.test_client() c.get('/') c.get('/test/') c = app.test_client() c.get('/') c.get('/test_with_categories/') c = app.test_client() c.get('/') c.get('/test_filter/') c = app.test_client() c.get('/') c.get('/test_filters/') c = app.test_client() c.get('/') c.get('/test_filters_without_returning_categories/') def test_request_processing(self): app = flask.Flask(__name__) evts = [] @app.before_request def before_request(): evts.append('before') @app.after_request def after_request(response): response.data += b'|after' evts.append('after') return response @app.route('/') def index(): self.assertTrue('before' in evts) self.assertTrue('after' not in evts) return 'request' self.assertTrue('after' not in evts) rv = app.test_client().get('/').data self.assertTrue('after' in evts) self.assert_equal(rv, b'request|after') def test_after_request_processing(self): app = flask.Flask(__name__) app.testing = True @app.route('/') def index(): @flask.after_this_request def foo(response): response.headers['X-Foo'] = 'a header' return response return 'Test' c = app.test_client() resp = c.get('/') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.headers['X-Foo'], 'a header') def test_teardown_request_handler(self): called = [] app = flask.Flask(__name__) @app.teardown_request def teardown_request(exc): called.append(True) return "Ignored" @app.route('/') def root(): return "Response" rv = app.test_client().get('/') self.assert_equal(rv.status_code, 200) self.assertTrue(b'Response' in rv.data) self.assert_equal(len(called), 1) def test_teardown_request_handler_debug_mode(self): called = [] app = flask.Flask(__name__) app.testing = True @app.teardown_request def teardown_request(exc): called.append(True) return "Ignored" @app.route('/') def root(): return "Response" rv = app.test_client().get('/') self.assert_equal(rv.status_code, 200) self.assertTrue(b'Response' in rv.data) self.assert_equal(len(called), 1) def test_teardown_request_handler_error(self): called = [] app = flask.Flask(__name__) @app.teardown_request def teardown_request1(exc): self.assert_equal(type(exc), ZeroDivisionError) called.append(True) # This raises a new error and blows away sys.exc_info(), so we can # test that all teardown_requests get passed the same original # exception. try: raise TypeError except: pass @app.teardown_request def teardown_request2(exc): self.assert_equal(type(exc), ZeroDivisionError) called.append(True) # This raises a new error and blows away sys.exc_info(), so we can # test that all teardown_requests get passed the same original # exception. try: raise TypeError except: pass @app.route('/') def fails(): 1/0 rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) self.assertTrue(b'Internal Server Error' in rv.data) self.assert_equal(len(called), 2) def test_before_after_request_order(self): called = [] app = flask.Flask(__name__) @app.before_request def before1(): called.append(1) @app.before_request def before2(): called.append(2) @app.after_request def after1(response): called.append(4) return response @app.after_request def after2(response): called.append(3) return response @app.teardown_request def finish1(exc): called.append(6) @app.teardown_request def finish2(exc): called.append(5) @app.route('/') def index(): return '42' rv = app.test_client().get('/') self.assert_equal(rv.data, b'42') self.assert_equal(called, [1, 2, 3, 4, 5, 6]) def test_error_handling(self): app = flask.Flask(__name__) @app.errorhandler(404) def not_found(e): return 'not found', 404 @app.errorhandler(500) def internal_server_error(e): return 'internal server error', 500 @app.route('/') def index(): flask.abort(404) @app.route('/error') def error(): 1 // 0 c = app.test_client() rv = c.get('/') self.assert_equal(rv.status_code, 404) self.assert_equal(rv.data, b'not found') rv = c.get('/error') self.assert_equal(rv.status_code, 500) self.assert_equal(b'internal server error', rv.data) def test_before_request_and_routing_errors(self): app = flask.Flask(__name__) @app.before_request def attach_something(): flask.g.something = 'value' @app.errorhandler(404) def return_something(error): return flask.g.something, 404 rv = app.test_client().get('/') self.assert_equal(rv.status_code, 404) self.assert_equal(rv.data, b'value') def test_user_error_handling(self): class MyException(Exception): pass app = flask.Flask(__name__) @app.errorhandler(MyException) def handle_my_exception(e): self.assertTrue(isinstance(e, MyException)) return '42' @app.route('/') def index(): raise MyException() c = app.test_client() self.assert_equal(c.get('/').data, b'42') def test_trapping_of_bad_request_key_errors(self): app = flask.Flask(__name__) app.testing = True @app.route('/fail') def fail(): flask.request.form['missing_key'] c = app.test_client() self.assert_equal(c.get('/fail').status_code, 400) app.config['TRAP_BAD_REQUEST_ERRORS'] = True c = app.test_client() try: c.get('/fail') except KeyError as e: self.assertTrue(isinstance(e, BadRequest)) else: self.fail('Expected exception') def test_trapping_of_all_http_exceptions(self): app = flask.Flask(__name__) app.testing = True app.config['TRAP_HTTP_EXCEPTIONS'] = True @app.route('/fail') def fail(): flask.abort(404) c = app.test_client() try: c.get('/fail') except NotFound as e: pass else: self.fail('Expected exception') def test_enctype_debug_helper(self): from flask.debughelpers import DebugFilesKeyError app = flask.Flask(__name__) app.debug = True @app.route('/fail', methods=['POST']) def index(): return flask.request.files['foo'].filename # with statement is important because we leave an exception on the # stack otherwise and we want to ensure that this is not the case # to not negatively affect other tests. with app.test_client() as c: try: c.post('/fail', data={'foo': 'index.txt'}) except DebugFilesKeyError as e: self.assertTrue('no file contents were transmitted' in str(e)) self.assertTrue('This was submitted: "index.txt"' in str(e)) else: self.fail('Expected exception') def test_teardown_on_pop(self): buffer = [] app = flask.Flask(__name__) @app.teardown_request def end_of_request(exception): buffer.append(exception) ctx = app.test_request_context() ctx.push() self.assert_equal(buffer, []) ctx.pop() self.assert_equal(buffer, [None]) def test_response_creation(self): app = flask.Flask(__name__) @app.route('/unicode') def from_unicode(): return 'Hällo Wörld' @app.route('/bytes') def from_bytes(): return 'Hällo Wörld'.encode('utf-8') @app.route('/args') def from_tuple(): return 'Meh', 400, { 'X-Foo': 'Testing', 'Content-Type': 'text/plain; charset=utf-8' } c = app.test_client() self.assert_equal(c.get('/unicode').data, 'Hällo Wörld'.encode('utf-8')) self.assert_equal(c.get('/bytes').data, 'Hällo Wörld'.encode('utf-8')) rv = c.get('/args') self.assert_equal(rv.data, b'Meh') self.assert_equal(rv.headers['X-Foo'], 'Testing') self.assert_equal(rv.status_code, 400) self.assert_equal(rv.mimetype, 'text/plain') def test_make_response(self): app = flask.Flask(__name__) with app.test_request_context(): rv = flask.make_response() self.assert_equal(rv.status_code, 200) self.assert_equal(rv.data, b'') self.assert_equal(rv.mimetype, 'text/html') rv = flask.make_response('Awesome') self.assert_equal(rv.status_code, 200) self.assert_equal(rv.data, b'Awesome') self.assert_equal(rv.mimetype, 'text/html') rv = flask.make_response('W00t', 404) self.assert_equal(rv.status_code, 404) self.assert_equal(rv.data, b'W00t') self.assert_equal(rv.mimetype, 'text/html') def test_make_response_with_response_instance(self): app = flask.Flask(__name__) with app.test_request_context(): rv = flask.make_response( flask.jsonify({'msg': 'W00t'}), 400) self.assertEqual(rv.status_code, 400) self.assertEqual(rv.data, b'{\n "msg": "W00t"\n}') self.assertEqual(rv.mimetype, 'application/json') rv = flask.make_response( flask.Response(''), 400) self.assertEqual(rv.status_code, 400) self.assertEqual(rv.data, b'') self.assertEqual(rv.mimetype, 'text/html') rv = flask.make_response( flask.Response('', headers={'Content-Type': 'text/html'}), 400, [('X-Foo', 'bar')]) self.assertEqual(rv.status_code, 400) self.assertEqual(rv.headers['Content-Type'], 'text/html') self.assertEqual(rv.headers['X-Foo'], 'bar') def test_url_generation(self): app = flask.Flask(__name__) @app.route('/hello/<name>', methods=['POST']) def hello(): pass with app.test_request_context(): self.assert_equal(flask.url_for('hello', name='test x'), '/hello/test%20x') self.assert_equal(flask.url_for('hello', name='test x', _external=True), 'http://localhost/hello/test%20x') def test_build_error_handler(self): app = flask.Flask(__name__) # Test base case, a URL which results in a BuildError. with app.test_request_context(): self.assertRaises(BuildError, flask.url_for, 'spam') # Verify the error is re-raised if not the current exception. try: with app.test_request_context(): flask.url_for('spam') except BuildError as error: try: raise RuntimeError('Test case where BuildError is not current.') except RuntimeError: self.assertRaises(BuildError, app.handle_url_build_error, error, 'spam', {}) # Test a custom handler. def handler(error, endpoint, values): # Just a test. return '/test_handler/' app.url_build_error_handlers.append(handler) with app.test_request_context(): self.assert_equal(flask.url_for('spam'), '/test_handler/') def test_custom_converters(self): from werkzeug.routing import BaseConverter class ListConverter(BaseConverter): def to_python(self, value): return value.split(',') def to_url(self, value): base_to_url = super(ListConverter, self).to_url return ','.join(base_to_url(x) for x in value) app = flask.Flask(__name__) app.url_map.converters['list'] = ListConverter @app.route('/<list:args>') def index(args): return '|'.join(args) c = app.test_client() self.assert_equal(c.get('/1,2,3').data, b'1|2|3') def test_static_files(self): app = flask.Flask(__name__) rv = app.test_client().get('/static/index.html') self.assert_equal(rv.status_code, 200) self.assert_equal(rv.data.strip(), b'<h1>Hello World!</h1>') with app.test_request_context(): self.assert_equal(flask.url_for('static', filename='index.html'), '/static/index.html') def test_none_response(self): app = flask.Flask(__name__) @app.route('/') def test(): return None try: app.test_client().get('/') except ValueError as e: self.assert_equal(str(e), 'View function did not return a response') pass else: self.assertTrue("Expected ValueError") def test_request_locals(self): self.assert_equal(repr(flask.g), '<LocalProxy unbound>') self.assertFalse(flask.g) def test_proper_test_request_context(self): app = flask.Flask(__name__) app.config.update( SERVER_NAME='localhost.localdomain:5000' ) @app.route('/') def index(): return None @app.route('/', subdomain='foo') def sub(): return None with app.test_request_context('/'): self.assert_equal(flask.url_for('index', _external=True), 'http://localhost.localdomain:5000/') with app.test_request_context('/'): self.assert_equal(flask.url_for('sub', _external=True), 'http://foo.localhost.localdomain:5000/') try: with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}): pass except Exception as e: self.assertTrue(isinstance(e, ValueError)) self.assert_equal(str(e), "the server name provided " + "('localhost.localdomain:5000') does not match the " + \ "server name from the WSGI environment ('localhost')") try: app.config.update(SERVER_NAME='localhost') with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}): pass except ValueError as e: raise ValueError( "No ValueError exception should have been raised \"%s\"" % e ) try: app.config.update(SERVER_NAME='localhost:80') with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}): pass except ValueError as e: raise ValueError( "No ValueError exception should have been raised \"%s\"" % e ) def test_test_app_proper_environ(self): app = flask.Flask(__name__) app.config.update( SERVER_NAME='localhost.localdomain:5000' ) @app.route('/') def index(): return 'Foo' @app.route('/', subdomain='foo') def subdomain(): return 'Foo SubDomain' rv = app.test_client().get('/') self.assert_equal(rv.data, b'Foo') rv = app.test_client().get('/', 'http://localhost.localdomain:5000') self.assert_equal(rv.data, b'Foo') rv = app.test_client().get('/', 'https://localhost.localdomain:5000') self.assert_equal(rv.data, b'Foo') app.config.update(SERVER_NAME='localhost.localdomain') rv = app.test_client().get('/', 'https://localhost.localdomain') self.assert_equal(rv.data, b'Foo') try: app.config.update(SERVER_NAME='localhost.localdomain:443') rv = app.test_client().get('/', 'https://localhost.localdomain') # Werkzeug 0.8 self.assert_equal(rv.status_code, 404) except ValueError as e: # Werkzeug 0.7 self.assert_equal(str(e), "the server name provided " + "('localhost.localdomain:443') does not match the " + \ "server name from the WSGI environment ('localhost.localdomain')") try: app.config.update(SERVER_NAME='localhost.localdomain') rv = app.test_client().get('/', 'http://foo.localhost') # Werkzeug 0.8 self.assert_equal(rv.status_code, 404) except ValueError as e: # Werkzeug 0.7 self.assert_equal(str(e), "the server name provided " + \ "('localhost.localdomain') does not match the " + \ "server name from the WSGI environment ('foo.localhost')") rv = app.test_client().get('/', 'http://foo.localhost.localdomain') self.assert_equal(rv.data, b'Foo SubDomain') def test_exception_propagation(self): def apprunner(configkey): app = flask.Flask(__name__) @app.route('/') def index(): 1/0 c = app.test_client() if config_key is not None: app.config[config_key] = True try: resp = c.get('/') except Exception: pass else: self.fail('expected exception') else: self.assert_equal(c.get('/').status_code, 500) # we have to run this test in an isolated thread because if the # debug flag is set to true and an exception happens the context is # not torn down. This causes other tests that run after this fail # when they expect no exception on the stack. for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None: t = Thread(target=apprunner, args=(config_key,)) t.start() t.join() def test_max_content_length(self): app = flask.Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 64 @app.before_request def always_first(): flask.request.form['myfile'] self.assertTrue(False) @app.route('/accept', methods=['POST']) def accept_file(): flask.request.form['myfile'] self.assertTrue(False) @app.errorhandler(413) def catcher(error): return '42' c = app.test_client() rv = c.post('/accept', data={'myfile': 'foo' * 100}) self.assert_equal(rv.data, b'42') def test_url_processors(self): app = flask.Flask(__name__) @app.url_defaults def add_language_code(endpoint, values): if flask.g.lang_code is not None and \ app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): values.setdefault('lang_code', flask.g.lang_code) @app.url_value_preprocessor def pull_lang_code(endpoint, values): flask.g.lang_code = values.pop('lang_code', None) @app.route('/<lang_code>/') def index(): return flask.url_for('about') @app.route('/<lang_code>/about') def about(): return flask.url_for('something_else') @app.route('/foo') def something_else(): return flask.url_for('about', lang_code='en') c = app.test_client() self.assert_equal(c.get('/de/').data, b'/de/about') self.assert_equal(c.get('/de/about').data, b'/foo') self.assert_equal(c.get('/foo').data, b'/en/about') def test_inject_blueprint_url_defaults(self): app = flask.Flask(__name__) bp = flask.Blueprint('foo.bar.baz', __name__, template_folder='template') @bp.url_defaults def bp_defaults(endpoint, values): values['page'] = 'login' @bp.route('/<page>') def view(page): pass app.register_blueprint(bp) values = dict() app.inject_url_defaults('foo.bar.baz.view', values) expected = dict(page='login') self.assert_equal(values, expected) with app.test_request_context('/somepage'): url = flask.url_for('foo.bar.baz.view') expected = '/login' self.assert_equal(url, expected) def test_debug_mode_complains_after_first_request(self): app = flask.Flask(__name__) app.debug = True @app.route('/') def index(): return 'Awesome' self.assertTrue(not app.got_first_request) self.assert_equal(app.test_client().get('/').data, b'Awesome') try: @app.route('/foo') def broken(): return 'Meh' except AssertionError as e: self.assertTrue('A setup function was called' in str(e)) else: self.fail('Expected exception') app.debug = False @app.route('/foo') def working(): return 'Meh' self.assert_equal(app.test_client().get('/foo').data, b'Meh') self.assertTrue(app.got_first_request) def test_before_first_request_functions(self): got = [] app = flask.Flask(__name__) @app.before_first_request def foo(): got.append(42) c = app.test_client() c.get('/') self.assert_equal(got, [42]) c.get('/') self.assert_equal(got, [42]) self.assertTrue(app.got_first_request) def test_routing_redirect_debugging(self): app = flask.Flask(__name__) app.debug = True @app.route('/foo/', methods=['GET', 'POST']) def foo(): return 'success' with app.test_client() as c: try: c.post('/foo', data={}) except AssertionError as e: self.assertTrue('http://localhost/foo/' in str(e)) self.assertTrue('Make sure to directly send your POST-request ' 'to this URL' in str(e)) else: self.fail('Expected exception') rv = c.get('/foo', data={}, follow_redirects=True) self.assert_equal(rv.data, b'success') app.debug = False with app.test_client() as c: rv = c.post('/foo', data={}, follow_redirects=True) self.assert_equal(rv.data, b'success') def test_route_decorator_custom_endpoint(self): app = flask.Flask(__name__) app.debug = True @app.route('/foo/') def foo(): return flask.request.endpoint @app.route('/bar/', endpoint='bar') def for_bar(): return flask.request.endpoint @app.route('/bar/123', endpoint='123') def for_bar_foo(): return flask.request.endpoint with app.test_request_context(): assert flask.url_for('foo') == '/foo/' assert flask.url_for('bar') == '/bar/' assert flask.url_for('123') == '/bar/123' c = app.test_client() self.assertEqual(c.get('/foo/').data, b'foo') self.assertEqual(c.get('/bar/').data, b'bar') self.assertEqual(c.get('/bar/123').data, b'123') def test_preserve_only_once(self): app = flask.Flask(__name__) app.debug = True @app.route('/fail') def fail_func(): 1/0 c = app.test_client() for x in range(3): with self.assert_raises(ZeroDivisionError): c.get('/fail') self.assertTrue(flask._request_ctx_stack.top is not None) flask._request_ctx_stack.pop() self.assertTrue(flask._request_ctx_stack.top is None) class ContextTestCase(FlaskTestCase): def test_context_binding(self): app = flask.Flask(__name__) @app.route('/') def index(): return 'Hello %s!' % flask.request.args['name'] @app.route('/meh') def meh(): return flask.request.url with app.test_request_context('/?name=World'): self.assert_equal(index(), 'Hello World!') with app.test_request_context('/meh'): self.assert_equal(meh(), 'http://localhost/meh') self.assertTrue(flask._request_ctx_stack.top is None) def test_context_test(self): app = flask.Flask(__name__) self.assertTrue(not flask.request) self.assertTrue(not flask.has_request_context()) ctx = app.test_request_context() ctx.push() try: self.assertTrue(flask.request) self.assertTrue(flask.has_request_context()) finally: ctx.pop() def test_manual_context_binding(self): app = flask.Flask(__name__) @app.route('/') def index(): return 'Hello %s!' % flask.request.args['name'] ctx = app.test_request_context('/?name=World') ctx.push() self.assert_equal(index(), 'Hello World!') ctx.pop() try: index() except RuntimeError: pass else: self.assertTrue(0, 'expected runtime error') class SubdomainTestCase(FlaskTestCase): def test_basic_support(self): app = flask.Flask(__name__) app.config['SERVER_NAME'] = 'localhost' @app.route('/') def normal_index(): return 'normal index' @app.route('/', subdomain='test') def test_index(): return 'test index' c = app.test_client() rv = c.get('/', 'http://localhost/') self.assert_equal(rv.data, b'normal index') rv = c.get('/', 'http://test.localhost/') self.assert_equal(rv.data, b'test index') @emits_module_deprecation_warning def test_module_static_path_subdomain(self): app = flask.Flask(__name__) app.config['SERVER_NAME'] = 'example.com' from subdomaintestmodule import mod app.register_module(mod) c = app.test_client() rv = c.get('/static/hello.txt', 'http://foo.example.com/') self.assert_equal(rv.data.strip(), b'Hello Subdomain') def test_subdomain_matching(self): app = flask.Flask(__name__) app.config['SERVER_NAME'] = 'localhost' @app.route('/', subdomain='<user>') def index(user): return 'index for %s' % user c = app.test_client() rv = c.get('/', 'http://mitsuhiko.localhost/') self.assert_equal(rv.data, b'index for mitsuhiko') def test_subdomain_matching_with_ports(self): app = flask.Flask(__name__) app.config['SERVER_NAME'] = 'localhost:3000' @app.route('/', subdomain='<user>') def index(user): return 'index for %s' % user c = app.test_client() rv = c.get('/', 'http://mitsuhiko.localhost:3000/') self.assert_equal(rv.data, b'index for mitsuhiko') @emits_module_deprecation_warning def test_module_subdomain_support(self): app = flask.Flask(__name__) mod = flask.Module(__name__, 'test', subdomain='testing') app.config['SERVER_NAME'] = 'localhost' @mod.route('/test') def test(): return 'Test' @mod.route('/outside', subdomain='xtesting') def bar(): return 'Outside' app.register_module(mod) c = app.test_client() rv = c.get('/test', 'http://testing.localhost/') self.assert_equal(rv.data, b'Test') rv = c.get('/outside', 'http://xtesting.localhost/') self.assert_equal(rv.data, b'Outside') def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(BasicFunctionalityTestCase)) suite.addTest(unittest.makeSuite(ContextTestCase)) suite.addTest(unittest.makeSuite(SubdomainTestCase)) return suite
scheduler.py
# -*- coding: utf-8 -*- """ sleekxmpp.xmlstream.scheduler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module provides a task scheduler that works better with SleekXMPP's threading usage than the stock version. Part of SleekXMPP: The Sleek XMPP Library :copyright: (c) 2011 Nathanael C. Fritz :license: MIT, see LICENSE for more details """ import time import threading import logging import itertools from sleekxmpp.util import Queue, QueueEmpty log = logging.getLogger(__name__) class Task(object): """ A scheduled task that will be executed by the scheduler after a given time interval has passed. :param string name: The name of the task. :param int seconds: The number of seconds to wait before executing. :param callback: The function to execute. :param tuple args: The arguments to pass to the callback. :param dict kwargs: The keyword arguments to pass to the callback. :param bool repeat: Indicates if the task should repeat. Defaults to ``False``. :param pointer: A pointer to an event queue for queuing callback execution instead of executing immediately. """ def __init__(self, name, seconds, callback, args=None, kwargs=None, repeat=False, qpointer=None): #: The name of the task. self.name = name #: The number of seconds to wait before executing. self.seconds = seconds #: The function to execute once enough time has passed. self.callback = callback #: The arguments to pass to :attr:`callback`. self.args = args or tuple() #: The keyword arguments to pass to :attr:`callback`. self.kwargs = kwargs or {} #: Indicates if the task should repeat after executing, #: using the same :attr:`seconds` delay. self.repeat = repeat #: The time when the task should execute next. self.next = time.time() + self.seconds #: The main event queue, which allows for callbacks to #: be queued for execution instead of executing immediately. self.qpointer = qpointer def run(self): """Execute the task's callback. If an event queue was supplied, place the callback in the queue; otherwise, execute the callback immediately. """ if self.qpointer is not None: self.qpointer.put(('schedule', self.callback, self.args, self.name)) else: self.callback(*self.args, **self.kwargs) self.reset() return self.repeat def reset(self): """Reset the task's timer so that it will repeat.""" self.next = time.time() + self.seconds class Scheduler(object): """ A threaded scheduler that allows for updates mid-execution unlike the scheduler in the standard library. Based on: http://docs.python.org/library/sched.html#module-sched :param parentstop: An :class:`~threading.Event` to signal stopping the scheduler. """ def __init__(self, parentstop=None): #: A queue for storing tasks self.addq = Queue() #: A list of tasks in order of execution time. self.schedule = [] #: If running in threaded mode, this will be the thread processing #: the schedule. self.thread = None #: A flag indicating that the scheduler is running. self.run = False #: An :class:`~threading.Event` instance for signalling to stop #: the scheduler. self.stop = parentstop #: Lock for accessing the task queue. self.schedule_lock = threading.RLock() def process(self, threaded=True, daemon=False): """Begin accepting and processing scheduled tasks. :param bool threaded: Indicates if the scheduler should execute in its own thread. Defaults to ``True``. """ if threaded: self.thread = threading.Thread(name='scheduler_process', target=self._process) self.thread.daemon = daemon self.thread.start() else: self._process() def _process(self): """Process scheduled tasks.""" self.run = True try: while self.run and not self.stop.is_set(): wait = 0.1 updated = False if self.schedule: wait = self.schedule[0].next - time.time() try: if wait <= 0.0: newtask = self.addq.get(False) else: if wait >= 3.0: wait = 3.0 newtask = None elapsed = 0 while not self.stop.is_set() and \ newtask is None and \ elapsed < wait: newtask = self.addq.get(True, 0.1) elapsed += 0.1 except QueueEmpty: self.schedule_lock.acquire() # select only those tasks which are to be executed now relevant = itertools.takewhile( lambda task: time.time() >= task.next, self.schedule) # run the tasks and keep the return value in a tuple status = map(lambda task: (task, task.run()), relevant) # remove non-repeating tasks for task, doRepeat in status: if not doRepeat: try: self.schedule.remove(task) except ValueError: pass else: # only need to resort tasks if a repeated task has # been kept in the list. updated = True else: updated = True self.schedule_lock.acquire() if newtask is not None: self.schedule.append(newtask) finally: if updated: self.schedule.sort(key=lambda task: task.next) self.schedule_lock.release() except KeyboardInterrupt: self.run = False except SystemExit: self.run = False log.debug("Quitting Scheduler thread") def add(self, name, seconds, callback, args=None, kwargs=None, repeat=False, qpointer=None): """Schedule a new task. :param string name: The name of the task. :param int seconds: The number of seconds to wait before executing. :param callback: The function to execute. :param tuple args: The arguments to pass to the callback. :param dict kwargs: The keyword arguments to pass to the callback. :param bool repeat: Indicates if the task should repeat. Defaults to ``False``. :param pointer: A pointer to an event queue for queuing callback execution instead of executing immediately. """ try: self.schedule_lock.acquire() for task in self.schedule: if task.name == name: raise ValueError("Key %s already exists" % name) self.addq.put(Task(name, seconds, callback, args, kwargs, repeat, qpointer)) except: raise finally: self.schedule_lock.release() def remove(self, name): """Remove a scheduled task ahead of schedule, and without executing it. :param string name: The name of the task to remove. """ try: self.schedule_lock.acquire() the_task = None for task in self.schedule: if task.name == name: the_task = task if the_task is not None: self.schedule.remove(the_task) except: raise finally: self.schedule_lock.release() def quit(self): """Shutdown the scheduler.""" self.run = False
__init__.py
"""Hermes MQTT server for Rhasspy wakeword with pocketsphinx""" import asyncio import io import logging import queue import socket import tempfile import threading import typing import wave from dataclasses import dataclass, field from pathlib import Path import pocketsphinx from rhasspyhermes.audioserver import AudioFrame from rhasspyhermes.base import Message from rhasspyhermes.client import GeneratorType, HermesClient, TopicArgs from rhasspyhermes.wake import ( HotwordDetected, HotwordError, HotwordToggleOff, HotwordToggleOn, HotwordToggleReason, ) WAV_HEADER_BYTES = 44 _LOGGER = logging.getLogger("rhasspywake_pocketsphinx_hermes") # ----------------------------------------------------------------------------- @dataclass class SiteInfo: """Self-contained information for a single site""" site_id: str enabled: bool = True disabled_reasons: typing.Set[str] = field(default_factory=set) detection_thread: typing.Optional[threading.Thread] = None audio_buffer: bytes = bytes() first_audio: bool = True decoder: typing.Optional[pocketsphinx.Decoder] = None decoder_started: bool = False # Queue of (bytes, is_raw) wav_queue: "queue.Queue[typing.Tuple[bytes, bool]]" = field( default_factory=queue.Queue ) # ----------------------------------------------------------------------------- class WakeHermesMqtt(HermesClient): """Hermes MQTT server for Rhasspy wakeword with pocketsphinx.""" def __init__( self, client, keyphrase: str, acoustic_model: Path, dictionary_paths: typing.List[Path], wakeword_id: str = "", keyphrase_threshold: float = 1e-40, mllr_matrix: typing.Optional[Path] = None, site_ids: typing.Optional[typing.List[str]] = None, sample_rate: int = 16000, sample_width: int = 2, channels: int = 1, chunk_size: int = 960, udp_audio: typing.Optional[typing.List[typing.Tuple[str, int, str]]] = None, udp_chunk_size: int = 2048, udp_raw_audio: typing.Optional[typing.Iterable[str]] = None, udp_forward_mqtt: typing.Optional[typing.Iterable[str]] = None, debug: bool = False, lang: typing.Optional[str] = None, ): super().__init__( "rhasspywake_pocketsphinx_hermes", client, sample_rate=sample_rate, sample_width=sample_width, channels=channels, site_ids=site_ids, ) self.subscribe(AudioFrame, HotwordToggleOn, HotwordToggleOff) self.keyphrase = keyphrase self.keyphrase_threshold = keyphrase_threshold self.acoustic_model = acoustic_model self.dictionary_paths = dictionary_paths self.mllr_matrix = mllr_matrix self.wakeword_id = wakeword_id # Required audio format self.sample_rate = sample_rate self.sample_width = sample_width self.channels = channels self.chunk_size = chunk_size self.site_info: typing.Dict[str, SiteInfo] = {} # Create site information for known sites for site_id in self.site_ids: site_info = SiteInfo(site_id=site_id) # Create and start detection thread site_info.detection_thread = threading.Thread( target=self.detection_thread_proc, daemon=True, args=(site_info,) ) site_info.detection_thread.start() self.site_info[site_id] = site_info self.debug = debug self.lang = lang # Listen for raw audio on UDP too self.udp_chunk_size = udp_chunk_size # Site ids where UDP audio is raw 16Khz, 16-bit mono PCM chunks instead # of WAV chunks. self.udp_raw_audio = set(udp_raw_audio or []) # Site ids where UDP audio should be forward to MQTT after detection. self.udp_forward_mqtt = set(udp_forward_mqtt or []) if udp_audio: for udp_host, udp_port, udp_site_id in udp_audio: threading.Thread( target=self.udp_thread_proc, args=(udp_host, udp_port, udp_site_id), daemon=True, ).start() # ------------------------------------------------------------------------- def load_decoder(self, site_info: SiteInfo): """Load Pocketsphinx decoder.""" _LOGGER.debug( "Loading decoder with hmm=%s, dicts=%s", str(self.acoustic_model), self.dictionary_paths, ) words_needed = set(self.keyphrase.split()) with tempfile.NamedTemporaryFile(mode="w+", suffix=".txt") as dict_file: # Combine all dictionaries for sub_dict_path in self.dictionary_paths: if not sub_dict_path.is_file(): _LOGGER.warning("Skipping dictionary %s", str(sub_dict_path)) continue with open(sub_dict_path, "r") as sub_dict_file: for line in sub_dict_file: line = line.strip() if line: word = line.split(maxsplit=2)[0] if word in words_needed: print(line, file=dict_file) words_needed.remove(word) assert ( len(words_needed) == 0 ), f"Missing pronunciations for words: {words_needed}" dict_file.seek(0) decoder_config = pocketsphinx.Decoder.default_config() decoder_config.set_string("-hmm", str(self.acoustic_model)) decoder_config.set_string("-dict", str(dict_file.name)) decoder_config.set_string("-keyphrase", self.keyphrase) decoder_config.set_float("-kws_threshold", self.keyphrase_threshold) if not self.debug: decoder_config.set_string("-logfn", "/dev/null") if self.mllr_matrix and self.mllr_matrix.is_file(): decoder_config.set_string("-mllr", str(self.mllr_matrix)) site_info.decoder = pocketsphinx.Decoder(decoder_config) # ------------------------------------------------------------------------- def stop(self): """Stop detection threads.""" _LOGGER.debug("Stopping detection threads...") for site_info in self.site_info.values(): if site_info.detection_thread is not None: site_info.wav_queue.put((None, None)) site_info.detection_thread.join() site_info.detection_thread = None site_info.porcupine = None _LOGGER.debug("Stopped") # ------------------------------------------------------------------------- async def handle_audio_frame(self, wav_bytes: bytes, site_id: str = "default"): """Process a single audio frame""" site_info = self.site_info.get(site_id) if site_info is None: # Create information for new site site_info = SiteInfo(site_id=site_id) site_info.detection_thread = threading.Thread( target=self.detection_thread_proc, daemon=True, args=(site_info,) ) site_info.detection_thread.start() self.site_info[site_id] = site_info site_info.wav_queue.put((wav_bytes, False)) async def handle_detection( self, wakeword_id: str, site_id: str = "default" ) -> typing.AsyncIterable[ typing.Union[typing.Tuple[HotwordDetected, TopicArgs], HotwordError] ]: """Handle a successful hotword detection""" try: yield ( HotwordDetected( site_id=site_id, model_id=self.keyphrase, current_sensitivity=self.keyphrase_threshold, model_version="", model_type="personal", lang=self.lang, ), {"wakeword_id": wakeword_id}, ) except Exception as e: _LOGGER.exception("handle_detection") yield HotwordError(error=str(e), context=self.keyphrase, site_id=site_id) def detection_thread_proc(self, site_info: SiteInfo): """Handle WAV audio chunks.""" try: while True: wav_bytes, is_raw = site_info.wav_queue.get() if wav_bytes is None: # Shutdown signal break if site_info.first_audio: _LOGGER.debug("Receiving audio %s", site_info.site_id) site_info.first_audio = False if not site_info.decoder: self.load_decoder(site_info) assert site_info.decoder is not None if is_raw: # Raw audio chunks audio_data = wav_bytes else: # WAV chunks audio_data = self.maybe_convert_wav(wav_bytes) # Add to persistent buffer site_info.audio_buffer += audio_data # Process in chunks. # Any remaining audio data will be kept in buffer. while len(site_info.audio_buffer) >= self.chunk_size: chunk = site_info.audio_buffer[: self.chunk_size] site_info.audio_buffer = site_info.audio_buffer[self.chunk_size :] if not site_info.decoder_started: # Begin utterance site_info.decoder.start_utt() site_info.decoder_started = True site_info.decoder.process_raw(chunk, False, False) hyp = site_info.decoder.hyp() if hyp: if site_info.decoder_started: # End utterance site_info.decoder.end_utt() site_info.decoder_started = False wakeword_id = self.wakeword_id if not wakeword_id: wakeword_id = self.keyphrase assert self.loop is not None asyncio.run_coroutine_threadsafe( self.publish_all( self.handle_detection( wakeword_id, site_id=site_info.site_id ) ), self.loop, ) # Stop and clear buffer to avoid duplicate reports site_info.audio_buffer = bytes() break except Exception: _LOGGER.exception("detection_thread_proc") # ------------------------------------------------------------------------- def udp_thread_proc(self, host: str, port: int, site_id: str): """Handle WAV chunks from UDP socket.""" try: site_info = self.site_info[site_id] is_raw_audio = site_id in self.udp_raw_audio forward_to_mqtt = site_id in self.udp_forward_mqtt udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udp_socket.bind((host, port)) _LOGGER.debug( "Listening for audio on UDP %s:%s (siteId=%s, raw=%s)", host, port, site_id, is_raw_audio, ) chunk_size = self.udp_chunk_size if is_raw_audio: chunk_size += WAV_HEADER_BYTES while True: wav_bytes, _ = udp_socket.recvfrom(chunk_size) if site_info.enabled: site_info.wav_queue.put((wav_bytes, is_raw_audio)) elif forward_to_mqtt: # When the wake word service is disabled, ASR should be active if is_raw_audio: # Re-package as WAV chunk and publish to MQTT with io.BytesIO() as wav_buffer: wav_file: wave.Wave_write = wave.open(wav_buffer, "wb") with wav_file: wav_file.setframerate(self.sample_rate) wav_file.setsampwidth(self.sample_width) wav_file.setnchannels(self.channels) wav_file.writeframes(wav_bytes) publish_wav_bytes = wav_buffer.getvalue() else: # Use WAV chunk as-is publish_wav_bytes = wav_bytes self.publish( AudioFrame(wav_bytes=publish_wav_bytes), site_id=site_info.site_id, ) except Exception: _LOGGER.exception("udp_thread_proc") # ------------------------------------------------------------------------- async def on_message_blocking( self, message: Message, site_id: typing.Optional[str] = None, session_id: typing.Optional[str] = None, topic: typing.Optional[str] = None, ) -> GeneratorType: """Received message from MQTT broker.""" # Check enable/disable messages site_info = self.site_info.get(site_id) if site_id else None if isinstance(message, HotwordToggleOn): if site_info: if message.reason == HotwordToggleReason.UNKNOWN: # Always enable on unknown site_info.disabled_reasons.clear() else: site_info.disabled_reasons.discard(message.reason) if site_info.disabled_reasons: _LOGGER.debug("Still disabled: %s", site_info.disabled_reasons) else: site_info.enabled = True site_info.first_audio = True _LOGGER.debug("Enabled") elif isinstance(message, HotwordToggleOff): if site_info: site_info.enabled = False site_info.disabled_reasons.add(message.reason) # End utterance if site_info.decoder and site_info.decoder_started: site_info.decoder.end_utt() site_info.decoder_started = False _LOGGER.debug("Disabled") elif isinstance(message, AudioFrame): if site_info and site_info.enabled: await self.handle_audio_frame( message.wav_bytes, site_id=site_info.site_id ) else: _LOGGER.warning("Unexpected message: %s", message) # Mark as async generator yield None
threaded.py
"""QwikSwitch USB Modem threaded library for Python.""" import logging from queue import Queue import threading from time import sleep import requests from .qwikswitch import ( QSDevices, QS_CMD, CMD_UPDATE, URL_DEVICES, URL_LISTEN, URL_SET, URL_VERSION) # pylint: disable=W0614 _LOGGER = logging.getLogger(__name__) # pylint: disable=too-many-instance-attributes class QSUsb(): """Class to interface the QwikSwitch USB modem.""" def __init__(self, url, dim_adj, callback_value_changed): """Init the Qwikswitch class. url: URL for the QS class (e.g. http://localhost:8080) dim_adj: adjust dimmers values exponentially. callback_qs_to_value: set the value upon qs change """ self._url = url.strip('/') self._running = False self.devices = QSDevices( callback_value_changed, self._callback_set_qs_value, dim_adj) self._timeout = 300 self._queue = None self._callback_listen = None self._types = {} self._lock = threading.Lock() # Update internal state if not self.update_from_devices(): raise ValueError('Cannot connect to the QSUSB hub ' + url) def _thread_worker(self): """Process callbacks from the queue populated by &listen.""" while self._running: # Retrieve next cmd, or block packet = self._queue.get(True) if isinstance(packet, dict) and QS_CMD in packet: try: self._callback_listen(packet) except Exception as err: # pylint: disable=broad-except _LOGGER.error("Exception in callback\nType: %s: %s", type(err), err) self._queue.task_done() def _thread_listen(self): """The main &listen loop.""" while self._running: try: rest = requests.get(URL_LISTEN.format(self._url), timeout=self._timeout) if rest.status_code == 200: self._queue.put(rest.json()) else: _LOGGER.error('QSUSB response code %s', rest.status_code) sleep(30) # Received for "Read timed out" and "Connection refused" except requests.exceptions.ConnectionError as err: if str(err).find('timed') > 0: # "Read timedout" update self._queue.put({QS_CMD: CMD_UPDATE}) else: # "Connection refused" QSUSB down _LOGGER.error(str(err)) sleep(60) except Exception as err: # pylint: disable=broad-except _LOGGER.error("%s - %s", str(type(err)), str(err)) sleep(5) self._queue.put({}) # empty item to ensure callback thread shuts down def stop(self): """Stop listening.""" self._running = False def version(self): """Get the QS Mobile version.""" # requests.get destroys the ? import urllib with urllib.request.urlopen(URL_VERSION.format(self._url)) as response: return response.read().decode('utf-8') return False def listen(self, callback=None, timeout=(5, 300)): """Start the &listen long poll and return immediately.""" if self._running: return False # if self.devices() is False: # return False self._queue = Queue() self._running = True self._timeout = timeout self._callback_listen = callback threading.Thread(target=self._thread_listen, args=()).start() threading.Thread(target=self._thread_worker, args=()).start() return True def _callback_set_qs_value(self, key, val, success): """Push state to QSUSB, retry with backoff.""" set_url = URL_SET.format(self._url, key, val) with self._lock: for _repeat in range(1, 6): set_result = requests.get(set_url) if set_result.status_code == 200: set_result = set_result.json() if set_result.get('data', 'NO REPLY') != 'NO REPLY': # self.devices._set_qs_value(key, set_result['data']) success() return True sleep(0.01 * _repeat) _LOGGER.error("Unable to set %s", set_url) return False def update_from_devices(self): """Retrieve a list of &devices and values.""" # _LOGGER.warning("update from devices") try: rest = requests.get(URL_DEVICES.format(self._url)) if rest.status_code != 200: _LOGGER.error("Devices returned %s", rest.status_code) return False self.devices.update_devices(rest.json()) return True except requests.exceptions.ConnectionError as conn_err: _LOGGER.error("Could not connect: %s", conn_err) except Exception as err: # pylint: disable=broad-except _LOGGER.error(err)
test.py
import gzip import json import logging import os import io import random import threading import time import helpers.client import pytest from helpers.cluster import ClickHouseCluster, ClickHouseInstance, get_instances_dir MINIO_INTERNAL_PORT = 9001 SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) CONFIG_PATH = os.path.join(SCRIPT_DIR, './{}/dummy/configs/config.d/defaultS3.xml'.format(get_instances_dir())) # Creates S3 bucket for tests and allows anonymous read-write access to it. def prepare_s3_bucket(started_cluster): # Allows read-write access for bucket without authorization. bucket_read_write_policy = {"Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "s3:GetBucketLocation", "Resource": "arn:aws:s3:::root" }, { "Sid": "", "Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::root" }, { "Sid": "", "Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::root/*" }, { "Sid": "", "Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "s3:PutObject", "Resource": "arn:aws:s3:::root/*" } ]} minio_client = started_cluster.minio_client minio_client.set_bucket_policy(started_cluster.minio_bucket, json.dumps(bucket_read_write_policy)) started_cluster.minio_restricted_bucket = "{}-with-auth".format(started_cluster.minio_bucket) if minio_client.bucket_exists(started_cluster.minio_restricted_bucket): minio_client.remove_bucket(started_cluster.minio_restricted_bucket) minio_client.make_bucket(started_cluster.minio_restricted_bucket) def put_s3_file_content(started_cluster, bucket, filename, data): buf = io.BytesIO(data) started_cluster.minio_client.put_object(bucket, filename, buf, len(data)) # Returns content of given S3 file as string. def get_s3_file_content(started_cluster, bucket, filename, decode=True): # type: (ClickHouseCluster, str, str, bool) -> str data = started_cluster.minio_client.get_object(bucket, filename) data_str = b"" for chunk in data.stream(): data_str += chunk if decode: return data_str.decode() return data_str @pytest.fixture(scope="module") def started_cluster(): try: cluster = ClickHouseCluster(__file__) cluster.add_instance("restricted_dummy", main_configs=["configs/config_for_test_remote_host_filter.xml"], with_minio=True) cluster.add_instance("dummy", with_minio=True, main_configs=["configs/defaultS3.xml"]) cluster.add_instance("s3_max_redirects", with_minio=True, main_configs=["configs/defaultS3.xml"], user_configs=["configs/s3_max_redirects.xml"]) logging.info("Starting cluster...") cluster.start() logging.info("Cluster started") prepare_s3_bucket(cluster) logging.info("S3 bucket created") run_s3_mocks(cluster) yield cluster finally: cluster.shutdown() def run_query(instance, query, stdin=None, settings=None): # type: (ClickHouseInstance, str, object, dict) -> str logging.info("Running query '{}'...".format(query)) result = instance.query(query, stdin=stdin, settings=settings) logging.info("Query finished") return result # Test simple put. Also checks that wrong credentials produce an error with every compression method. @pytest.mark.parametrize("maybe_auth,positive,compression", [ pytest.param("", True, 'auto', id="positive"), pytest.param("'minio','minio123',", True, 'auto', id="auth_positive"), pytest.param("'wrongid','wrongkey',", False, 'auto', id="auto"), pytest.param("'wrongid','wrongkey',", False, 'gzip', id="gzip"), pytest.param("'wrongid','wrongkey',", False, 'deflate', id="deflate"), pytest.param("'wrongid','wrongkey',", False, 'brotli', id="brotli"), pytest.param("'wrongid','wrongkey',", False, 'xz', id="xz"), pytest.param("'wrongid','wrongkey',", False, 'zstd', id="zstd") ]) def test_put(started_cluster, maybe_auth, positive, compression): # type: (ClickHouseCluster) -> None bucket = started_cluster.minio_bucket if not maybe_auth else started_cluster.minio_restricted_bucket instance = started_cluster.instances["dummy"] # type: ClickHouseInstance table_format = "column1 UInt32, column2 UInt32, column3 UInt32" values = "(1, 2, 3), (3, 2, 1), (78, 43, 45)" values_csv = "1,2,3\n3,2,1\n78,43,45\n" filename = "test.csv" put_query = f"""insert into table function s3('http://{started_cluster.minio_ip}:{started_cluster.minio_port}/{bucket}/{filename}', {maybe_auth}'CSV', '{table_format}', {compression}) values {values}""" try: run_query(instance, put_query) except helpers.client.QueryRuntimeException: if positive: raise else: assert positive assert values_csv == get_s3_file_content(started_cluster, bucket, filename) @pytest.mark.parametrize("special", [ "space", "plus" ]) def test_get_file_with_special(started_cluster, special): symbol = {"space": " ", "plus": "+"}[special] urlsafe_symbol = {"space": "%20", "plus": "%2B"}[special] auth = "'minio','minio123'," bucket = started_cluster.minio_restricted_bucket instance = started_cluster.instances["dummy"] table_format = "column1 UInt32, column2 UInt32, column3 UInt32" values = [[12549, 2463, 19893], [64021, 38652, 66703], [81611, 39650, 83516], [11079, 59507, 61546], [51764, 69952, 6876], [41165, 90293, 29095], [40167, 78432, 48309], [81629, 81327, 11855], [55852, 21643, 98507], [6738, 54643, 41155]] values_csv = ('\n'.join((','.join(map(str, row)) for row in values)) + '\n').encode() filename = f"get_file_with_{special}_{symbol}two.csv" put_s3_file_content(started_cluster, bucket, filename, values_csv) get_query = f"SELECT * FROM s3('http://{started_cluster.minio_host}:{started_cluster.minio_port}/{bucket}/get_file_with_{special}_{urlsafe_symbol}two.csv', {auth}'CSV', '{table_format}') FORMAT TSV" assert [list(map(int, l.split())) for l in run_query(instance, get_query).splitlines()] == values get_query = f"SELECT * FROM s3('http://{started_cluster.minio_host}:{started_cluster.minio_port}/{bucket}/get_file_with_{special}*.csv', {auth}'CSV', '{table_format}') FORMAT TSV" assert [list(map(int, l.split())) for l in run_query(instance, get_query).splitlines()] == values get_query = f"SELECT * FROM s3('http://{started_cluster.minio_host}:{started_cluster.minio_port}/{bucket}/get_file_with_{special}_{urlsafe_symbol}*.csv', {auth}'CSV', '{table_format}') FORMAT TSV" assert [list(map(int, l.split())) for l in run_query(instance, get_query).splitlines()] == values @pytest.mark.parametrize("special", [ "space", "plus", "plus2" ]) def test_get_path_with_special(started_cluster, special): symbol = {"space": "%20", "plus": "%2B", "plus2": "%2B"}[special] safe_symbol = {"space": "%20", "plus": "+", "plus2": "%2B"}[special] auth = "'minio','minio123'," table_format = "column1 String" instance = started_cluster.instances["dummy"] get_query = f"SELECT * FROM s3('http://resolver:8082/get-my-path/{safe_symbol}.csv', {auth}'CSV', '{table_format}') FORMAT TSV" assert run_query(instance, get_query).splitlines() == [f"/{symbol}.csv"] # Test put no data to S3. @pytest.mark.parametrize("auth", [ pytest.param("'minio','minio123',", id="minio") ]) def test_empty_put(started_cluster, auth): # type: (ClickHouseCluster, str) -> None bucket = started_cluster.minio_bucket instance = started_cluster.instances["dummy"] # type: ClickHouseInstance table_format = "column1 UInt32, column2 UInt32, column3 UInt32" drop_empty_table_query = "DROP TABLE IF EXISTS empty_table" create_empty_table_query = """ CREATE TABLE empty_table ( {} ) ENGINE = Null() """.format(table_format) run_query(instance, drop_empty_table_query) run_query(instance, create_empty_table_query) filename = "empty_put_test.csv" put_query = "insert into table function s3('http://{}:{}/{}/{}', {}'CSV', '{}') select * from empty_table".format( started_cluster.minio_ip, MINIO_INTERNAL_PORT, bucket, filename, auth, table_format) run_query(instance, put_query) try: run_query(instance, "select count(*) from s3('http://{}:{}/{}/{}', {}'CSV', '{}')".format( started_cluster.minio_ip, MINIO_INTERNAL_PORT, bucket, filename, auth, table_format)) assert False, "Query should be failed." except helpers.client.QueryRuntimeException as e: assert str(e).find("The specified key does not exist") != 0 # Test put values in CSV format. @pytest.mark.parametrize("maybe_auth,positive", [ pytest.param("", True, id="positive"), pytest.param("'minio','minio123',", True, id="auth_positive"), pytest.param("'wrongid','wrongkey',", False, id="negative"), ]) def test_put_csv(started_cluster, maybe_auth, positive): # type: (ClickHouseCluster, bool, str) -> None bucket = started_cluster.minio_bucket if not maybe_auth else started_cluster.minio_restricted_bucket instance = started_cluster.instances["dummy"] # type: ClickHouseInstance table_format = "column1 UInt32, column2 UInt32, column3 UInt32" filename = "test.csv" put_query = "insert into table function s3('http://{}:{}/{}/{}', {}'CSV', '{}') format CSV".format( started_cluster.minio_ip, MINIO_INTERNAL_PORT, bucket, filename, maybe_auth, table_format) csv_data = "8,9,16\n11,18,13\n22,14,2\n" try: run_query(instance, put_query, stdin=csv_data) except helpers.client.QueryRuntimeException: if positive: raise else: assert positive assert csv_data == get_s3_file_content(started_cluster, bucket, filename) # Test put and get with S3 server redirect. def test_put_get_with_redirect(started_cluster): # type: (ClickHouseCluster) -> None bucket = started_cluster.minio_bucket instance = started_cluster.instances["dummy"] # type: ClickHouseInstance table_format = "column1 UInt32, column2 UInt32, column3 UInt32" values = "(1, 1, 1), (1, 1, 1), (11, 11, 11)" values_csv = "1,1,1\n1,1,1\n11,11,11\n" filename = "test.csv" query = "insert into table function s3('http://{}:{}/{}/{}', 'CSV', '{}') values {}".format( started_cluster.minio_redirect_host, started_cluster.minio_redirect_port, bucket, filename, table_format, values) run_query(instance, query) assert values_csv == get_s3_file_content(started_cluster, bucket, filename) query = "select *, column1*column2*column3 from s3('http://{}:{}/{}/{}', 'CSV', '{}')".format( started_cluster.minio_redirect_host, started_cluster.minio_redirect_port, bucket, filename, table_format) stdout = run_query(instance, query) assert list(map(str.split, stdout.splitlines())) == [ ["1", "1", "1", "1"], ["1", "1", "1", "1"], ["11", "11", "11", "1331"], ] # Test put with restricted S3 server redirect. def test_put_with_zero_redirect(started_cluster): # type: (ClickHouseCluster) -> None bucket = started_cluster.minio_bucket instance = started_cluster.instances["s3_max_redirects"] # type: ClickHouseInstance table_format = "column1 UInt32, column2 UInt32, column3 UInt32" values = "(1, 1, 1), (1, 1, 1), (11, 11, 11)" filename = "test.csv" # Should work without redirect query = "insert into table function s3('http://{}:{}/{}/{}', 'CSV', '{}') values {}".format( started_cluster.minio_ip, MINIO_INTERNAL_PORT, bucket, filename, table_format, values) run_query(instance, query) # Should not work with redirect query = "insert into table function s3('http://{}:{}/{}/{}', 'CSV', '{}') values {}".format( started_cluster.minio_redirect_host, started_cluster.minio_redirect_port, bucket, filename, table_format, values) exception_raised = False try: run_query(instance, query) except Exception as e: assert str(e).find("Too many redirects while trying to access") != -1 exception_raised = True finally: assert exception_raised def test_put_get_with_globs(started_cluster): # type: (ClickHouseCluster) -> None unique_prefix = random.randint(1,10000) bucket = started_cluster.minio_bucket instance = started_cluster.instances["dummy"] # type: ClickHouseInstance table_format = "column1 UInt32, column2 UInt32, column3 UInt32" max_path = "" for i in range(10): for j in range(10): path = "{}/{}_{}/{}.csv".format(unique_prefix, i, random.choice(['a', 'b', 'c', 'd']), j) max_path = max(path, max_path) values = "({},{},{})".format(i, j, i + j) query = "insert into table function s3('http://{}:{}/{}/{}', 'CSV', '{}') values {}".format( started_cluster.minio_ip, MINIO_INTERNAL_PORT, bucket, path, table_format, values) run_query(instance, query) query = "select sum(column1), sum(column2), sum(column3), min(_file), max(_path) from s3('http://{}:{}/{}/{}/*_{{a,b,c,d}}/%3f.csv', 'CSV', '{}')".format( started_cluster.minio_redirect_host, started_cluster.minio_redirect_port, bucket, unique_prefix, table_format) assert run_query(instance, query).splitlines() == [ "450\t450\t900\t0.csv\t{bucket}/{max_path}".format(bucket=bucket, max_path=max_path)] # Test multipart put. @pytest.mark.parametrize("maybe_auth,positive", [ pytest.param("", True, id="positive"), pytest.param("'wrongid','wrongkey'", False, id="negative"), # ("'minio','minio123',",True), Redirect with credentials not working with nginx. ]) def test_multipart_put(started_cluster, maybe_auth, positive): # type: (ClickHouseCluster) -> None bucket = started_cluster.minio_bucket if not maybe_auth else started_cluster.minio_restricted_bucket instance = started_cluster.instances["dummy"] # type: ClickHouseInstance table_format = "column1 UInt32, column2 UInt32, column3 UInt32" # Minimum size of part is 5 Mb for Minio. # See: https://github.com/minio/minio/blob/master/docs/minio-limits.md min_part_size_bytes = 5 * 1024 * 1024 csv_size_bytes = int(min_part_size_bytes * 1.5) # To have 2 parts. one_line_length = 6 # 3 digits, 2 commas, 1 line separator. # Generate data having size more than one part int_data = [[1, 2, 3] for i in range(csv_size_bytes // one_line_length)] csv_data = "".join(["{},{},{}\n".format(x, y, z) for x, y, z in int_data]) assert len(csv_data) > min_part_size_bytes filename = "test_multipart.csv" put_query = "insert into table function s3('http://{}:{}/{}/{}', {}'CSV', '{}') format CSV".format( started_cluster.minio_redirect_host, started_cluster.minio_redirect_port, bucket, filename, maybe_auth, table_format) try: run_query(instance, put_query, stdin=csv_data, settings={'s3_min_upload_part_size': min_part_size_bytes, 's3_max_single_part_upload_size': 0}) except helpers.client.QueryRuntimeException: if positive: raise else: assert positive # Use proxy access logs to count number of parts uploaded to Minio. proxy_logs = started_cluster.get_container_logs("proxy1") # type: str assert proxy_logs.count("PUT /{}/{}".format(bucket, filename)) >= 2 assert csv_data == get_s3_file_content(started_cluster, bucket, filename) def test_remote_host_filter(started_cluster): instance = started_cluster.instances["restricted_dummy"] format = "column1 UInt32, column2 UInt32, column3 UInt32" query = "select *, column1*column2*column3 from s3('http://{}:{}/{}/test.csv', 'CSV', '{}')".format( "invalid_host", MINIO_INTERNAL_PORT, started_cluster.minio_bucket, format) assert "not allowed in config.xml" in instance.query_and_get_error(query) other_values = "(1, 1, 1), (1, 1, 1), (11, 11, 11)" query = "insert into table function s3('http://{}:{}/{}/test.csv', 'CSV', '{}') values {}".format( "invalid_host", MINIO_INTERNAL_PORT, started_cluster.minio_bucket, format, other_values) assert "not allowed in config.xml" in instance.query_and_get_error(query) @pytest.mark.parametrize("s3_storage_args", [ pytest.param("''", id="1_argument"), pytest.param("'','','','','',''", id="6_arguments"), ]) def test_wrong_s3_syntax(started_cluster, s3_storage_args): instance = started_cluster.instances["dummy"] # type: ClickHouseInstance expected_err_msg = "Code: 42" # NUMBER_OF_ARGUMENTS_DOESNT_MATCH query = "create table test_table_s3_syntax (id UInt32) ENGINE = S3({})".format(s3_storage_args) assert expected_err_msg in instance.query_and_get_error(query) # https://en.wikipedia.org/wiki/One_Thousand_and_One_Nights def test_s3_glob_scheherazade(started_cluster): bucket = started_cluster.minio_bucket instance = started_cluster.instances["dummy"] # type: ClickHouseInstance table_format = "column1 UInt32, column2 UInt32, column3 UInt32" max_path = "" values = "(1, 1, 1)" nights_per_job = 1001 // 30 jobs = [] for night in range(0, 1001, nights_per_job): def add_tales(start, end): for i in range(start, end): path = "night_{}/tale.csv".format(i) query = "insert into table function s3('http://{}:{}/{}/{}', 'CSV', '{}') values {}".format( started_cluster.minio_ip, MINIO_INTERNAL_PORT, bucket, path, table_format, values) run_query(instance, query) jobs.append(threading.Thread(target=add_tales, args=(night, min(night + nights_per_job, 1001)))) jobs[-1].start() for job in jobs: job.join() query = "select count(), sum(column1), sum(column2), sum(column3) from s3('http://{}:{}/{}/night_*/tale.csv', 'CSV', '{}')".format( started_cluster.minio_redirect_host, started_cluster.minio_redirect_port, bucket, table_format) assert run_query(instance, query).splitlines() == ["1001\t1001\t1001\t1001"] def run_s3_mocks(started_cluster): logging.info("Starting s3 mocks") mocks = ( ("mock_s3.py", "resolver", "8080"), ("unstable_server.py", "resolver", "8081"), ("echo.py", "resolver", "8082"), ) for mock_filename, container, port in mocks: container_id = started_cluster.get_container_id(container) current_dir = os.path.dirname(__file__) started_cluster.copy_file_to_container(container_id, os.path.join(current_dir, "s3_mocks", mock_filename), mock_filename) started_cluster.exec_in_container(container_id, ["python", mock_filename, port], detach=True) # Wait for S3 mocks to start for mock_filename, container, port in mocks: num_attempts = 100 for attempt in range(num_attempts): ping_response = started_cluster.exec_in_container(started_cluster.get_container_id(container), ["curl", "-s", f"http://localhost:{port}/"], nothrow=True) if ping_response != 'OK': if attempt == num_attempts - 1: assert ping_response == 'OK', 'Expected "OK", but got "{}"'.format(ping_response) else: time.sleep(1) else: logging.debug(f"mock {mock_filename} ({port}) answered {ping_response} on attempt {attempt}") break logging.info("S3 mocks started") def replace_config(old, new): config = open(CONFIG_PATH, 'r') config_lines = config.readlines() config.close() config_lines = [line.replace(old, new) for line in config_lines] config = open(CONFIG_PATH, 'w') config.writelines(config_lines) config.close() def test_custom_auth_headers(started_cluster): table_format = "column1 UInt32, column2 UInt32, column3 UInt32" filename = "test.csv" get_query = "select * from s3('http://resolver:8080/{bucket}/{file}', 'CSV', '{table_format}')".format( bucket=started_cluster.minio_restricted_bucket, file=filename, table_format=table_format) instance = started_cluster.instances["dummy"] # type: ClickHouseInstance result = run_query(instance, get_query) assert result == '1\t2\t3\n' instance.query("DROP TABLE IF EXISTS test") instance.query( "CREATE TABLE test ({table_format}) ENGINE = S3('http://resolver:8080/{bucket}/{file}', 'CSV')".format( bucket=started_cluster.minio_restricted_bucket, file=filename, table_format=table_format )) assert run_query(instance, "SELECT * FROM test") == '1\t2\t3\n' replace_config("<header>Authorization: Bearer TOKEN", "<header>Authorization: Bearer INVALID_TOKEN") instance.query("SYSTEM RELOAD CONFIG") ret, err = instance.query_and_get_answer_with_error("SELECT * FROM test") assert ret == "" and err != "" replace_config("<header>Authorization: Bearer INVALID_TOKEN", "<header>Authorization: Bearer TOKEN") instance.query("SYSTEM RELOAD CONFIG") assert run_query(instance, "SELECT * FROM test") == '1\t2\t3\n' instance.query("DROP TABLE test") def test_custom_auth_headers_exclusion(started_cluster): table_format = "column1 UInt32, column2 UInt32, column3 UInt32" filename = "test.csv" get_query = f"SELECT * FROM s3('http://resolver:8080/{started_cluster.minio_restricted_bucket}/restricteddirectory/{filename}', 'CSV', '{table_format}')" instance = started_cluster.instances["dummy"] # type: ClickHouseInstance with pytest.raises(helpers.client.QueryRuntimeException) as ei: result = run_query(instance, get_query) print(result) assert ei.value.returncode == 243 assert 'Forbidden Error' in ei.value.stderr def test_infinite_redirect(started_cluster): bucket = "redirected" table_format = "column1 UInt32, column2 UInt32, column3 UInt32" filename = "test.csv" get_query = f"select * from s3('http://resolver:{started_cluster.minio_redirect_port}/{bucket}/{filename}', 'CSV', '{table_format}')" instance = started_cluster.instances["dummy"] # type: ClickHouseInstance exception_raised = False try: run_query(instance, get_query) except Exception as e: assert str(e).find("Too many redirects while trying to access") != -1 exception_raised = True finally: assert exception_raised @pytest.mark.parametrize("extension,method", [ pytest.param("bin", "gzip", id="bin"), pytest.param("gz", "auto", id="gz"), ]) def test_storage_s3_get_gzip(started_cluster, extension, method): bucket = started_cluster.minio_bucket instance = started_cluster.instances["dummy"] filename = f"test_get_gzip.{extension}" name = f"test_get_gzip_{extension}" data = [ "Sophia Intrieri,55", "Jack Taylor,71", "Christopher Silva,66", "Clifton Purser,35", "Richard Aceuedo,43", "Lisa Hensley,31", "Alice Wehrley,1", "Mary Farmer,47", "Samara Ramirez,19", "Shirley Lloyd,51", "Santos Cowger,0", "Richard Mundt,88", "Jerry Gonzalez,15", "Angela James,10", "Norman Ortega,33", "" ] run_query(instance, f"DROP TABLE IF EXISTS {name}") buf = io.BytesIO() compressed = gzip.GzipFile(fileobj=buf, mode="wb") compressed.write(("\n".join(data)).encode()) compressed.close() put_s3_file_content(started_cluster, bucket, filename, buf.getvalue()) run_query(instance, f"""CREATE TABLE {name} (name String, id UInt32) ENGINE = S3( 'http://{started_cluster.minio_ip}:{MINIO_INTERNAL_PORT}/{bucket}/{filename}', 'CSV', '{method}')""") run_query(instance, f"SELECT sum(id) FROM {name}").splitlines() == ["565"] run_query(instance, f"DROP TABLE {name}") def test_storage_s3_get_unstable(started_cluster): bucket = started_cluster.minio_bucket instance = started_cluster.instances["dummy"] table_format = "column1 Int64, column2 Int64, column3 Int64, column4 Int64" get_query = f"SELECT count(), sum(column3), sum(column4) FROM s3('http://resolver:8081/{started_cluster.minio_bucket}/test.csv', 'CSV', '{table_format}') FORMAT CSV" result = run_query(instance, get_query) assert result.splitlines() == ["500001,500000,0"] def test_storage_s3_put_uncompressed(started_cluster): bucket = started_cluster.minio_bucket instance = started_cluster.instances["dummy"] filename = "test_put_uncompressed.bin" name = "test_put_uncompressed" data = [ "'Gloria Thompson',99", "'Matthew Tang',98", "'Patsy Anderson',23", "'Nancy Badillo',93", "'Roy Hunt',5", "'Adam Kirk',51", "'Joshua Douds',28", "'Jolene Ryan',0", "'Roxanne Padilla',50", "'Howard Roberts',41", "'Ricardo Broughton',13", "'Roland Speer',83", "'Cathy Cohan',58", "'Kathie Dawson',100", "'Gregg Mcquistion',11", ] run_query(instance, "CREATE TABLE {} (name String, id UInt32) ENGINE = S3('http://{}:{}/{}/{}', 'CSV')".format( name, started_cluster.minio_ip, MINIO_INTERNAL_PORT, bucket, filename)) run_query(instance, "INSERT INTO {} VALUES ({})".format(name, "),(".join(data))) run_query(instance, "SELECT sum(id) FROM {}".format(name)).splitlines() == ["753"] uncompressed_content = get_s3_file_content(started_cluster, bucket, filename) assert sum([ int(i.split(',')[1]) for i in uncompressed_content.splitlines() ]) == 753 @pytest.mark.parametrize("extension,method", [ pytest.param("bin", "gzip", id="bin"), pytest.param("gz", "auto", id="gz") ]) def test_storage_s3_put_gzip(started_cluster, extension, method): bucket = started_cluster.minio_bucket instance = started_cluster.instances["dummy"] filename = f"test_put_gzip.{extension}" name = f"test_put_gzip_{extension}" data = [ "'Joseph Tomlinson',5", "'Earnest Essary',44", "'Matha Pannell',24", "'Michael Shavers',46", "'Elias Groce',38", "'Pamela Bramlet',50", "'Lewis Harrell',49", "'Tamara Fyall',58", "'George Dixon',38", "'Alice Walls',49", "'Paula Mais',24", "'Myrtle Pelt',93", "'Sylvia Naffziger',18", "'Amanda Cave',83", "'Yolanda Joseph',89" ] run_query(instance, f"""CREATE TABLE {name} (name String, id UInt32) ENGINE = S3( 'http://{started_cluster.minio_ip}:{MINIO_INTERNAL_PORT}/{bucket}/{filename}', 'CSV', '{method}')""") run_query(instance, f"INSERT INTO {name} VALUES ({'),('.join(data)})") run_query(instance, f"SELECT sum(id) FROM {name}").splitlines() == ["708"] buf = io.BytesIO(get_s3_file_content(started_cluster, bucket, filename, decode=False)) f = gzip.GzipFile(fileobj=buf, mode="rb") uncompressed_content = f.read().decode() assert sum([ int(i.split(',')[1]) for i in uncompressed_content.splitlines() ]) == 708 def test_truncate_table(started_cluster): bucket = started_cluster.minio_bucket instance = started_cluster.instances["dummy"] # type: ClickHouseInstance name = "truncate" instance.query("CREATE TABLE {} (id UInt32) ENGINE = S3('http://{}:{}/{}/{}', 'CSV')".format( name, started_cluster.minio_ip, MINIO_INTERNAL_PORT, bucket, name)) instance.query("INSERT INTO {} SELECT number FROM numbers(10)".format(name)) result = instance.query("SELECT * FROM {}".format(name)) assert result == instance.query("SELECT number FROM numbers(10)") instance.query("TRUNCATE TABLE {}".format(name)) minio = started_cluster.minio_client timeout = 30 while timeout > 0: if len(list(minio.list_objects(started_cluster.minio_bucket, 'truncate/'))) == 0: return timeout -= 1 time.sleep(1) assert(len(list(minio.list_objects(started_cluster.minio_bucket, 'truncate/'))) == 0) assert instance.query("SELECT * FROM {}".format(name)) == ""
imagetweet.py
# -*- coding: utf-8 -*- from collections import OrderedDict from utils import printf as print from configobj import ConfigObj from threading import Thread import pathlib import tweepy import time import sys import os sys.path.append('plugins/') account_list = OrderedDict() api_objects = OrderedDict() __version__ = '0.1.0' CHECK_UPDATE = True BASE_DIR = os.path.dirname(os.path.realpath(__file__)) if os.environ.get('DEBUG') == "travis": DEBUG = "travis" DEBUG_ACCS = os.environ.get('ACCOUNTS', '').split("||") # Download test image for folder testing from utils import download_image url = "https://www.google.co.uk/images/nav_logo231_hr.png" download_image(url) else: # Local testing. Edit this for your own testing. DEBUG = False DEBUG_ACCS = ["test"] def latest_ver(): import urllib.request url = "http://ace3df.github.io/AcePictureBot/it_ver.txt" try: site_ver = urllib.request.urlopen(url).read().strip().decode("utf-8") if site_ver != __version__: print("!WARNING! A new version is out ({0})!".format(site_ver)) print("Download it here: http://bombch.us/BWVH") print("----------------------------------------\n") except: # Just in case pass def login(bot): creds = OrderedDict(( k.lower(), v) for k, v in bot[1].items()) consumer_token = creds['credentials']['consumer key'] consumer_secret = creds['credentials']['consumer secret'] access_token = creds['credentials']['access token'] access_token_secret = creds['credentials']['access token secret'] auth = tweepy.OAuthHandler(consumer_token, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) return api def load_accounts(): accounts = sorted( [p for p in pathlib.Path( os.path.join(BASE_DIR, 'accounts')).iterdir() if p.is_file()]) account_count = 0 print(os.path.join(BASE_DIR, 'accounts')) print(accounts) for acc in accounts: bot_name = os.path.basename(str(acc)).split(".")[0] if DEBUG: if bot_name not in DEBUG_ACCS: continue elif not DEBUG: if "example" in bot_name.lower(): continue account_count += 1 account_list[bot_name] = OrderedDict() Config = ConfigObj(str(acc)) has_cred = False has_sett = False for sec in (Config.iteritems()): sec = tuple(sec) if sec[0] == "credentials": has_cred = True elif sec[0] == "settings": has_sett = True if "-thread" in sec[0]: # Start thread import setttings and creds pass account_list[bot_name][sec[0].lower()] = (sec[1].copy()) if not has_cred: print("Credentials not found for bot: {}".format(bot_name)) input("Press ENTER to close.") sys.exit(0) elif not has_sett: print("No settings are set for bot: {}".format(bot_name)) input("Press ENTER to close.") sys.exit(0) temp = OrderedDict() for k, v in account_list[bot_name].items(): for a, b in v.items(): a = a.lower() try: temp[k][a] = b except: temp[k] = {a: b} account_list[bot_name] = temp.copy() del temp print("Running {0} Accounts!\n".format(account_count)) return(account_list) def load_plugin(name): mod = __import__("%s" % name) return mod def call_plugin(name, *args, **kwargs): plugin = load_plugin(name) return plugin.main(*args, **kwargs) def post_tweet(api, msg, image): if image: image = image.replace("\\", "\\\\") if image: api.update_with_media(image, status=msg) else: # Leave this here if someone wants to # call it in their plugin or something api.update_status(status=msg) def main_bot(bot): bot_name = bot[0] bot = OrderedDict(bot[1].items()) api = bot.get('api') try: start_delay = int(bot.get('settings').get('start delay')) except: start_delay = 0 try: time_delay = int(bot.get('settings').get('time delay')) except: time_delay = 15 if not DEBUG: time.sleep(start_delay * 60) while True: for plugin in bot.items(): if "-thread" in plugin[0]: continue if plugin[0] == "settings": continue elif plugin[0] == "credentials": continue elif plugin[0] == "api": continue plugin_kwgs = OrderedDict(( k.lower(), v) for k, v in plugin[1].items()) plugin_kwgs['bot name'] = bot_name plugin_kwgs['DEBUG'] = DEBUG plugin_kwgs['support webm'] = bot.get( 'settings').get('support webm') plugin_kwgs['webm script'] = bot.get( 'settings').get('webm script') plugin_kwgs['saucenao api'] = bot.get( 'settings').get('saucenao api') p_repeat = bot.get(plugin[0]).get('p_repeat') if not p_repeat: p_repeat = 1 for x in range(0, int(p_repeat)): try: print("{0}:".format(bot_name)) print(time.strftime('%I:%M%p %Z on %b %d, %Y')) if DEBUG: print("\n" + str(plugin_kwgs) + "\n") m, i = (call_plugin(plugin[0], **OrderedDict(plugin_kwgs))) if i == "SKIP": # No need to print that it's skipping as this # should only happen when the user knows it will happen continue elif i: print("Message: {0}\nImage: {1}\n".format( m, i)) if not DEBUG: post_tweet(api, m, i) elif DEBUG == "travis": try: if not i: raise ValueError('empty image') except ValueError as e: print("Failed to get image for: {0}".format( bot_name)) else: sys.exit(0) time.sleep(time_delay * 60) else: # Push to Exeption raise Exception() except Exception as e: print("!FAILED POSTING!") print("{0}:".format(bot_name)) print(time.strftime('%I:%M%p %Z on %b %d, %Y')) if e == "" or e is None: # Custom message e = "^ Described Above! ^" print("Problem: {0}\n".format(e)) if DEBUG: raise Exception() # Make this 30 seconds to give time to read # and maybe make the owner know that something is up # for it being so late. i.e. a PM system/push note time.sleep(30) if __name__ == '__main__': if CHECK_UPDATE: latest_ver() account_list = load_accounts() for bot in account_list.items(): if not DEBUG: bot[1]['api'] = login(bot) Thread(name=bot[0], target=main_bot, args=(bot, )).start() time.sleep(3)
mtimes.py
import pathlib import queue import stat import threading from mopidy import exceptions class FindError(exceptions.MopidyException): def __init__(self, message, errno=None): super().__init__(message, errno) self.errno = errno def find_mtimes(root, follow=False): results, errors = _find(root, relative=False, follow=follow) # return the mtimes as integer milliseconds mtimes = {f: int(st.st_mtime * 1000) for f, st in results.items()} return mtimes, errors def _find(root, thread_count=10, relative=False, follow=False): """Threaded find implementation that provides stat results for files. Tries to protect against sym/hardlink loops by keeping an eye on parent (st_dev, st_ino) pairs. :param Path root: root directory to search from, may not be a file :param int thread_count: number of workers to use, mainly useful to mitigate network lag when scanning on NFS etc. :param bool relative: if results should be relative to root or absolute :param bool follow: if symlinks should be followed """ root = pathlib.Path(root).resolve() threads = [] results = {} errors = {} done = threading.Event() work = queue.Queue() work.put((root, [])) if not relative: root = None args = (root, follow, done, work, results, errors) for _ in range(thread_count): t = threading.Thread(target=_find_worker, args=args) t.daemon = True t.start() threads.append(t) work.join() done.set() for t in threads: t.join() return results, errors def _find_worker(root, follow, done, work, results, errors): """Worker thread for collecting stat() results. :param Path root: directory to make results relative to :param bool follow: if symlinks should be followed :param threading.Event done: event indicating that all work has been done :param queue.Queue work: queue of paths to process :param dict results: shared dictionary for storing all the stat() results :param dict errors: shared dictionary for storing any per path errors """ while not done.is_set(): try: entry, parents = work.get(block=False) except queue.Empty: continue if root: path = entry.relative_to(root) else: path = entry try: if follow: st = entry.stat() else: st = entry.lstat() if (st.st_dev, st.st_ino) in parents: errors[path] = FindError("Sym/hardlink loop found.") continue if stat.S_ISDIR(st.st_mode): for e in entry.iterdir(): work.put((e, parents + [(st.st_dev, st.st_ino)])) elif stat.S_ISREG(st.st_mode): results[path] = st elif stat.S_ISLNK(st.st_mode): errors[path] = FindError("Not following symlinks.") else: errors[path] = FindError("Not a file or directory.") except OSError as exc: errors[path] = FindError(exc.strerror, exc.errno) finally: work.task_done()
auto_annotation.py
from .data import * import imgui from .projects import Project from yolov5 import detect import os import threading from . import annotation from .file_selector import file_selector from custom_utils import save_img_annotations def start_inference(frame_data, exp: Experiment): predictions = detect.run(weights=exp.model_path, imgsz=[1280, 1280], conf_thres=exp.threshold_conf, iou_thres=exp.threshold_iou, save_conf=True, exist_ok=True, save_txt=True, source=exp.data_path, project=exp.data_path + "/exp", name="predictions",) frame_data["imgs_to_render"]["inference_preview"]["scale"] = 1 for _, (bboxes, img) in enumerate(predictions): frame_data["imgs_to_render"]["inference_preview"]["name"] = img name_ext = os.path.basename(img).rsplit('.') img_info = ImageInfo(name_ext[0], name_ext[1], CollectionInfo(exp.exp_name, exp.exp_name, exp.data_path )) # exp.imgs.append(img_info) for bbox in bboxes: bbox : BBox = BBox(bbox["xmin"], bbox["ymin"], bbox["xmax"], bbox["ymax"], bbox["class"], bbox["conf"]) img_info.add_bbox(bbox) frame_data["imgs_to_render"]["inference_preview"]["img_info"] = img_info exp.add_image(img_info) save_img_annotations(img_info) # print(img) # frame_data["img"] = img exp.progress += 0.1 if not exp.is_running: break frame_data["imgs_to_render"]["inference_preview"]["img_info"] = None frame_data["imgs_to_render"]["inference_preview"]["texture"] = None exp.is_running = False exp.progress = 0 frame_data["done"] = True frame_data["is_running"] = False def auto_ann_content(frame_data): _files_list(frame_data, "inference_preview") if frame_data["is_running"]: imgui.begin_child("i_progress") imgui.progress_bar( fraction=frame_data['experiment'].progress * 10 / frame_data["num_imgs"] , size=(-1, 0.0), overlay=f"{int(frame_data['experiment'].progress * 10)}/{frame_data['num_imgs']}" ) annotation._annotation_screen(frame_data, "inference_preview", allow_edit=False) imgui.end_child() else: annotation._annotation_screen(frame_data, "inference_preview", allow_edit=False) def header_auto_annotation(frame_data): project : Project = frame_data["project"] """ if frame_data["is_running"]: imgui.internal.push_item_flag(imgui.internal.ITEM_DISABLED, True) imgui.push_style_var(imgui.STYLE_ALPHA, imgui.get_style().alpha * 0.5) """ if imgui.button("New session"): imgui.open_popup("Auto-annotation session") imgui.set_next_window_size(700, 350) frame_data["is_dialog_open"] = True frame_data["experiment"] = Experiment("D:/Projects/python/pdf-toolbox/pdf_toolbox/backend/data/pdf_best_multi_nano.pt", "D:\\Projects\\python\\semantics\\project\\test_final\\imgs_exp2", "") if imgui.begin_popup_modal("Auto-annotation session", flags=imgui.WINDOW_NO_RESIZE )[0]: imgui.begin_child(label="auto_ann_content", height=250, border=False, ) imgui.columns(1, "header_2", False) model_btn_title = "Choose model path..." if imgui.button(model_btn_title): imgui.open_popup("Choose model path...") model_file = file_selector("Choose model path...", False) if model_file is not None: frame_data["experiment"].model_path = model_file if frame_data["experiment"].model_path != "": imgui.same_line() imgui.text(frame_data["experiment"].model_path) images_btn_title = "Choose images directory..." if imgui.button(images_btn_title): imgui.open_popup(images_btn_title) images_path = file_selector(images_btn_title, True) if images_path is not None: frame_data["experiment"].data_path = images_path if frame_data["experiment"].data_path != "": imgui.same_line() imgui.text(frame_data["experiment"].data_path) _, frame_data["experiment"].exp_name = imgui.input_text("Name",frame_data["experiment"].exp_name, 128) imgui.separator() imgui.push_item_width(520) _, frame_data["experiment"].threshold_conf = imgui.slider_float( label="Confidence threshold", value=frame_data["experiment"].threshold_conf, min_value=0.0, max_value=1.0, format="%.2f", ) _, frame_data["experiment"].threshold_iou = imgui.slider_float( label="IoU threshold", value=frame_data["experiment"].threshold_iou, min_value=0.0, max_value=1.0, format="%.2f", ) imgui.pop_item_width() imgui.separator() imgui.end_child() if imgui.button("Start annotation"): frame_data["experiment"].update_info() frame_data["experiment"].is_running = True frame_data["is_running"] = True frame_data["experiment"].progress = 0 frame_data["done"] = False frame_data["num_imgs"] = frame_data["experiment"].num_imgs frame_data["project"].save_experiment(frame_data["experiment"]) thread = threading.Thread(target=start_inference, args=(frame_data, frame_data["experiment"])) thread.start() imgui.close_current_popup() frame_data["is_dialog_open"] = False imgui.same_line() if imgui.button("Close"): imgui.close_current_popup() frame_data["is_dialog_open"] = False imgui.end_popup() """ if frame_data["is_running"]: imgui.internal.pop_item_flag() imgui.pop_style_var() """ imgui.columns(1) if frame_data["is_running"]: start_clicked = imgui.button("Stop analysis") if start_clicked: if frame_data["is_running"]: frame_data["is_running"] = False imgui.same_line() scale_changed, frame_data["img_scale"] = imgui.slider_float( label="Zoom", value=frame_data["img_scale"], min_value=0.5, max_value=2.0, format="%.1f", ) if scale_changed: frame_data["scale_changed"] = True def _files_list(frame_data, img_render_id): project : Project = frame_data["project"] experiments : dict[str, Experiment] = project.experiments img_data = frame_data["imgs_to_render"][img_render_id] # add 20 more (scrollbar) frame_data["x_offset"] = int(frame_data["viewport"][0] / 5) + 20 imgui.begin_child(label="files_list", width=frame_data["x_offset"] - 20, height=-1, border=False, ) for exp_id in experiments: exp = experiments[exp_id] if imgui.tree_node(exp.exp_name): for i, img_info in enumerate(exp.imgs): # img_info = project.imgs[k] name = img_info.name clicked, _ = imgui.selectable( label=name, selected=(frame_data["selected_file"]["idx"] == i and frame_data["selected_file"]["collection"] == exp_id) ) if clicked or frame_data["scale_changed"]: img_data["scale"] = frame_data["img_scale"] if clicked: frame_data["scale_changed"] = True base_p = name img_data["name"] = name img_data["img_info"] = img_info frame_data["selected_file"]["collection"] = exp_id frame_data["selected_file"]["idx"] = i frame_data["selected_file"]["name"] = base_p if frame_data["scale_changed"]: frame_data["scale_changed"] = False img_data["img_info"].change_scale(frame_data["img_scale"]) if frame_data["imgs_info"].get(frame_data["selected_file"]["name"]) is None: frame_data["imgs_info"][frame_data["selected_file"]["name"]] = {} frame_data["imgs_info"][frame_data["selected_file"]["name"]]["orig_size"] = [img_data["img_info"].w, img_data["img_info"].h] frame_data["imgs_info"][frame_data["selected_file"]["name"]]["scaled_size"] = [img_data["img_info"].scaled_w, img_data["img_info"].scaled_h] imgui.tree_pop() imgui.end_child() imgui.same_line(position=frame_data["x_offset"]) def inference_progress(frame_data): img_data = frame_data["imgs_to_render"]["inference_preview"] if frame_data["is_running"]: imgui.columns(3,"progr", False) imgui.next_column() imgui.progress_bar( fraction=frame_data['experiment'].progress * 10 / frame_data["num_imgs"] , size=(-1, 0.0), overlay=f"{int(frame_data['experiment'].progress * 10)}/{frame_data['num_imgs']}" ) imgui.columns(1) imgui.spacing() if img_data["texture"] is not None: imgui.same_line((frame_data["viewport"][0] / 2) - (img_data["width"] / 2)) imgui.image(img_data["texture"], img_data["width"], img_data["height"])
snowball_uploader_27-success-prod.py
''' status: completed version: v27 way: using multi-part uploading ref: https://gist.github.com/teasherm/bb73f21ed2f3b46bc1c2ca48ec2c1cf5 changelog: - 2022.01.19 - added no_extract variable and test to allow not setting the auto-extract metadata flag - 2021.06.10 - v27 - eliminate "renaming filename" feature - support to select storageClass - elimidating dependency of "sbe1" profile when running getlist - initial feature deriven from snowball_uploader - 2021.02.20 - save filelist_dir as filelist-currentdata.gz when executing genlist - 2021.02.20 - v26 - performance improvement of genlist; dumping file list, not each line - 2021.02.20 - replacing scandir.walk to os.walk. already os.walk module patched with scandir after python3.5 - 2021.02.10 - replacing os.walk with scandir.walk to improve performance of file listing - 2021.02.09 - python2 compatibility for "open(filename, endoding)" - 2021.02.01 - modifying to support Windows - refactoring for more accurate defining of variables - 2021.01.26 - multi processing support for parallel uploading of tar files - relevant parameter: max_process - 2021.01.25 - removing yaml feature, due for it to cause too much cpu consumtion and low performance - fixing bug which use two profiles(sbe1, default), now only use "sbe1" profile - showing progress - 2020.02.25 - changing filelist file to contain the target filename - 2020.02.24 - fixing FIFO error - adding example of real snowball configuration - 2020.02.22 - limiting multi-thread numbers - adding multi-threading to improve performance - adding fifo operation to reducing for big file which is over max_part_size - 2020.02.19 - removing tarfiles_one_time logic - spliting buffer by max_part_size - 2020.02.18: - supprt snowball limit: - max_part_size: 512mb - min_part_size: 5mb - 2020.02.14: - modifying for python3 - support korean in Windows - 2020.02.12: adding features - gen_filelist by size - 2020.02.10: changing filename from tar_to_s3_v7_multipart.py to snowball_uploader_8.py - adding features which can split tar file by size and count. - adding feature which create file list - showing help message ''' import boto3 import tarfile import io import os.path from datetime import datetime import sys import shutil import multiprocessing import time import math ###### Change below variables bucket_name = "your-own-bucket" profile_name = "sbe1" endpoint = "http://10.10.10.10:8080" #endpoint = "https://s3.ap-northeast-2.amazonaws.com" #s3 = session.client('s3', endpoint_url='http://10.10.10.10:8080') # or below #s3 = boto3.client('s3', region_name='ap-northeast-2', endpoint_url='https://s3.ap-northeast-2.amazonaws.com', aws_access_key_id=None, aws_secret_access_key=None) target_path = "/data/" ## very important!! change to your source directory if os.name == "nt": filelist_dir = "C:/tmp/fl_logdir_dkfjpoiwqjefkdjf/" #for windows else: filelist_dir = "/tmp/fl_logdir_dkfjpoiwqjefkdjf/" #for linux s3_class = "STANDARD" # ['STANDARD'|'REDUCED_REDUNDANCY'|'STANDARD_IA'|'ONEZONE_IA'|'INTELLIGENT_TIERING'|'GLACIER'|'DEEP_ARCHIVE'] ##### Optional variables max_tarfile_size = 10 * (1024 ** 3) # 10GiB, 100GiB is max limit of snowball max_part_size = 100 * (1024 ** 2) # 100MB, 500MiB is max limit of snowball max_process = 5 # max process number, set the value to less than filelist files in filelist_dir no_extract ='' # set to y to bypass setting of the auto-extract metadata tag #### don't need to modify from here min_part_size = 5 * 1024 ** 2 # 16MiB for S3, 5MiB for SnowballEdge max_part_count = int(math.ceil(max_tarfile_size / max_part_size)) current_time = datetime.now().strftime("%Y%m%d_%H%M%S") parts = [] delimiter = ', ' ## if python2, exclude encoding parameter if sys.version_info.major > 2: do_open = lambda filename, flag: open(filename, flag, encoding='utf-8') else: do_open = lambda filename, flag: open(filename, flag) def write_to_file(fl_name, subfl_list): with do_open(fl_name, 'w') as f: for line in subfl_list: f.write("%s\n" %line) #writer = csv.writer(fl_content) #writer.writerows(subfl_list) return 0 def gen_filelist(): sum_size = 0 fl_prefix = 'fl_' fl_index = 1 subfl_list = [] shutil.rmtree(filelist_dir,ignore_errors=True) try: os.makedirs(filelist_dir) except: pass print('generating file list by size %s bytes' % max_tarfile_size) for r,d,f in os.walk(target_path): for file in f: fl_name = filelist_dir + '/' + fl_prefix + str(fl_index) + ".txt" file_name = os.path.join(r,file) f_meta = os.stat(file_name) f_inode = f_meta.st_ino f_size = f_meta.st_size #For python3# f_mtime_ns = f_meta.st_mtime_ns f_mtime = f_meta.st_mtime # seconds #f_dict[f_inode] = {"fname":file_name, "fsize":f_size} sum_size = sum_size + f_size #target_file_name = rename_file(file_name) f_info = [file_name ,str(f_size), str(f_mtime)] #f_info = [file_name , target_file_name] f_info_str = delimiter.join(f_info) subfl_list.append(f_info_str) if max_tarfile_size < sum_size: write_to_file(fl_name, subfl_list) fl_index = fl_index + 1 print('%s is generated' % fl_name) sum_size = 0 subfl_list=[] ## generate file list for remaings write_to_file(fl_name, subfl_list) ## archive file list files with tar.gz fl_arc_file = "filelist-" + current_time +".gz" with tarfile.open(fl_arc_file, "w:gz") as tar: tar.add(filelist_dir, arcname=os.path.basename(filelist_dir)) print('file lists are generated!!') print('check %s' % filelist_dir) return 0 def get_org_files_list(source_file): filelist = [] with do_open(source_file, 'r') as fn: for line in fn.readlines(): #filelist.append({line.split(delimiter)[0]:line.split(delimiter)[1].replace('\n','')}) filelist.append(line.split(delimiter)[0].replace('\n','')) return filelist def log_error(error_log, org_file, str_suffix): with do_open(error_log,'a+') as err: err.write(org_file + str_suffix) def log_success(success_log, org_file, str_suffix): with do_open(success_log,'a+') as success: success.write(org_file + str_suffix) def create_mpu(key_name): if no_extract == "y": mpu = s3.create_multipart_upload(Bucket=bucket_name, Key=key_name, StorageClass=s3_class) else: mpu = s3.create_multipart_upload(Bucket=bucket_name, Key=key_name, StorageClass=s3_class, Metadata={"snowball-auto-extract": "true"}) mpu_id = mpu["UploadId"] return mpu_id def upload_mpu(key_name, mpu_id, data, index): #part = s3.upload_part(Body=data, Bucket=bucket_name, Key=key_name, UploadId=mpu_id, PartNumber=index, ContentLength=max_buf_size) part = s3.upload_part(Body=data, Bucket=bucket_name, Key=key_name, UploadId=mpu_id, PartNumber=index) parts.append({"PartNumber": index, "ETag": part["ETag"]}) #print ('parts list: %s' % str(parts)) return parts def complete_mpu(key_name, mpu_id, parts): result = s3.complete_multipart_upload( Bucket=bucket_name, Key=key_name, UploadId=mpu_id, MultipartUpload={"Parts": parts}) return result def adjusting_parts_order(mpu_parts): return sorted(mpu_parts, key=lambda item: item['PartNumber']) def buf_fifo(buf): tmp_buf = io.BytesIO() # added for FIFO operation tmp_buf.write(buf.read()) # added for FIFO operation #print ('3. before fifo, recv_buf_size: %s' % len(buf.getvalue())) #print('3.before fifo, recv_buf_pos : %s' % buf.tell()) buf.seek(0,0) buf.truncate(0) tmp_buf.seek(0,0) buf.write(tmp_buf.read()) return buf def copy_to_snowball(error_log, success_log, key_name, org_files_list): tar_file_size = 0 recv_buf = io.BytesIO() mpu_id = create_mpu(key_name) parts_index = 1 s_log = success_log e_log = error_log with tarfile.open(fileobj=recv_buf, mode="w") as tar: for org_file in org_files_list: if os.path.isfile(org_file): tar.add(org_file) #print ('1. recv_buf_size: %s' % len(recv_buf.getvalue())) log_success(s_log, org_file, " is archiving \n" ) recv_buf_size = recv_buf.tell() #print ('1. recv_buf_pos: %s' % recv_buf.tell()) if recv_buf_size > max_part_size: print('multi part uploading: %s / %s , size: %s' % (parts_index, max_part_count, recv_buf_size)) chunk_count = int(recv_buf_size / max_part_size) tar_file_size = tar_file_size + recv_buf_size print('%s is accumulating, size: %s' % (key_name, tar_file_size)) #print('chunk_count: %s ' % chunk_count) for buf_index in range(chunk_count): start_pos = buf_index * max_part_size recv_buf.seek(start_pos,0) mpu_parts = upload_mpu(key_name, mpu_id, recv_buf.read(max_part_size), parts_index) parts_index += 1 #################### buf_fifo(recv_buf) recv_buf_size = recv_buf.tell() #print('3.after fifo, recv_buf_pos : %s' % recv_buf.tell()) #print ('3. after fifo, recv_buf_size: %s' % len(recv_buf.getvalue())) else: pass #print('accumulating files...') else: log_error(e_log, org_file," does not exist\n") print (org_file + ' is not exist...............................................\n') recv_buf.seek(0,0) mpu_parts = upload_mpu(key_name, mpu_id, recv_buf.read(), parts_index) parts_index += 1 mpu_parts = adjusting_parts_order(mpu_parts) complete_mpu(key_name, mpu_id, mpu_parts) ### print metadata meta_out = s3.head_object(Bucket=bucket_name, Key=key_name) print ('\n metadata info: %s' % str(meta_out)) log_success(s_log, str(meta_out), '!!\n') print ("\n tar file: %s \n" % key_name) log_success(s_log, key_name, ' is uploaded successfully\n') def snowball_uploader_help(**args): print ("Usage: %s 'genlist | cp_snowball | help'" % sys.argv[0]) print ("use python3, not compatible with python2!!!") #print ('\n') print ('genlist: ') print ('this option will generate files which are containing target files list in %s'% (filelist_dir)) #print ('\n') print ('cp_snowball: ') print ('cp_snowball option will copy the files on server to snowball efficiently') print ('the mechanism is here:') print ('1. reads the target file name from the one filelist file in filelist directory') print ('2. accumulates files to max_part_size in memory') print ('3. if it reachs max_part_size, send it to snowball using MultiPartUpload') print ('4. tar files uploading to Snowball concurrently according to max_process') print ('5. after complete to send, tar file is generated in snowball') print ('6. then, moves to the next filelist file recursively') if __name__ == "__main__": if len(sys.argv) != 2: print ("Usage: %s genlist | cp_snowball | help" % sys.argv[0]) print ("use python3, not compatible with python2!!!") sys.exit() elif sys.argv[1] == "genlist": gen_filelist() elif sys.argv[1] == "cp_snowball": session = boto3.Session(profile_name=profile_name) s3 = session.client('s3', endpoint_url=endpoint) #source_files = [ f for f in os.listdir(filelist_dir) if os.path.isfile(f)] source_files = os.listdir(filelist_dir) max_source_files = len(source_files) source_files_count = 0 task_process = [] task_index = 0 for sf in source_files: error_log = ('error_%s_%s.log' % (sf, current_time)) success_log = ('success_%s_%s.log' % (sf, current_time)) source_file = os.path.join(filelist_dir, sf) #org_files_list = open(source_file, encoding='utf8').readlines() org_files_list = get_org_files_list(source_file) key_name = ("snowball-%s-%s.tar" % (sf[:-4], current_time)) #print ("key_name:", key_name) #print ('\n0. ###########################') #print ('0. %s is starting' % sf) #print ('0. ###########################') #copy_to_snowball(org_files_list) task_process.append(multiprocessing.Process(target = copy_to_snowball, args=(error_log, success_log, key_name, org_files_list,))) task_process[-1].start() source_files_count+=1 #print ('1. ###########################') print ('1. %s is processing, transfered tar files: %s / %s' % (sf, source_files_count, max_source_files)) #print ('1. ###########################') parts = [] if task_index >= max_process: pjoin = [ proc.join() for proc in task_process ] task_index = 0 task_process = [] task_index += 1 #print ('part progess of tar file could not reach the max, sorry for inconvenience') print ("Uploading Finished") else: snowball_uploader_help()
celeste_timer.py
#!/usr/bin/env python3 # copyright 2021 rhelmot. redistribution is permitted for any purpose provided this copyright notice is kept intact. # this program comes with absolutely no warranty including fitness for blah blah blah import struct import pickle import sys import threading import time import collections import random import pprint # 00 string Level; # 08 int Chapter; # 0c int Mode; # 10 bool TimerActive; # 11 bool ChapterStarted; # 12 bool ChapterComplete; # 18 long ChapterTime; # 20 int ChapterStrawberries; # 24 bool ChapterCassette; # 25 bool ChapterHeart; # 28 long FileTime; # 30 int FileStrawberries; # 34 int FileCassettes; # 38 int FileHearts; # 40 int CurrentChapterCheckpoints; def split_time(filetime): neg = filetime < 0 if neg: filetime = -filetime ms = filetime % 1000 se = filetime // 1000 % 60 mi = filetime // 1000 // 60 % 60 hr = filetime // 1000 // 60 // 60 return (neg, hr, mi, se, ms) def fmt_time(tup, ms_decimals=3, full_width=False, sign=False): if type(tup) is int: tup = split_time(tup) neg, hr, mi, se, ms = tup if ms_decimals > 0: if ms_decimals == 1: ms //= 100 elif ms_decimals == 2: ms //= 10 ms_str = ('.%%0%dd' % ms_decimals) % ms else: ms_str = '' if hr or mi or full_width: se_str = '%02d' % se else: se_str = '%d' % se if hr or full_width: mi_str = '%02d:' % mi else: if mi: mi_str = '%d:' % mi else: mi_str = '' if hr or full_width: hr_str = '%d:' % hr else: hr_str = '' if sign or neg: sign_str = '-' if neg else '+' else: sign_str = '' return sign_str + hr_str + mi_str + se_str + ms_str class AutoSplitterInfo: def __init__(self, filename='../autosplitterinfo'): self.all_attrs = ('chapter', 'mode', 'timer_active', 'chapter_started', 'chapter_complete', 'chapter_time', 'chapter_strawberries', 'chapter_cassette', 'chapter_heart', 'file_time', 'file_strawberries', 'file_cassettes', 'file_hearts', 'chapter_checkpoints', 'in_cutscene', 'death_count', "level_name") self.chapter = 0 self.mode = 0 self.timer_active = False self.in_cutscene = False self.death_count = 0 self.level_name = "" self.chapter_started = False self.chapter_complete = False self.chapter_time = 0 self.chapter_strawberries = 0 self.chapter_cassette = False self.chapter_heart = False self.chapter_checkpoints = 0 self.file_time = 0 self.file_strawberries = 0 self.file_cassettes = 0 self.file_hearts = 0 self.fp = open(filename, 'rb') self.live = True self.thread = threading.Thread(target=self.update_loop) self.thread.daemon = True self.thread.start() @property def chapter_name(self): if self.chapter == 0: return 'Prologue' if self.chapter == 8: return 'Epilogue' if self.chapter == 10: return '9' if self.mode == 0: side = 'a' elif self.mode == 1: side = 'b' else: side = 'c' return '%d%s' % (self.chapter, side) def __getitem__(self, k): try: return getattr(self, k) except AttributeError as e: raise KeyError(k) from e @property def dict(self): return {x: getattr(self, x) for x in self.all_attrs} def update_loop(self): fmtstring = struct.Struct('Qii???QI??QIIIxxxxI?i100s') while self.live: last_tick = time.time() self.fp.seek(0) dat = self.fp.raw.read(fmtstring.size) _, self.chapter, self.mode, self.timer_active, \ self.chapter_started, self.chapter_complete, \ chapter_time, self.chapter_strawberries, \ self.chapter_cassette, self.chapter_heart, file_time, \ self.file_strawberries, self.file_cassettes, self.file_hearts, \ self.chapter_checkpoints, self.in_cutscene, self.death_count, level_name \ = fmtstring.unpack(dat) self.chapter_time = chapter_time // 10000 self.file_time = file_time // 10000 self.level_name = level_name.split(b'\0')[0].decode() timeout = last_tick + 0.001 - time.time() if timeout > 0: time.sleep(timeout) class Trigger: def __init__(self, name, end_trigger): self.name = name self.end_trigger = end_trigger def check_trigger(self, asi): # pylint: disable=unused-argument return eval(self.end_trigger) # pylint: disable=eval-used def __repr__(self): return '<Trigger %s>' % self.name class Split: def __init__(self, names, level=0): if type(names) == str: names = [names] if len(names) == 0: raise ValueError("Need at least one name") self.names = names self.level = level self.identity = random.randrange(2**64) def level_name(self, level): if level < self.level: raise ValueError("Why are you trying to render %s at level %d?" % (self, level)) try: return self.names[level - self.level] except IndexError: return self.names[-1] def __eq__(self, other): return hasattr(other, 'identity') and self.identity == other.identity def __hash__(self): return hash(self.identity) def __repr__(self): return '<Split %s>' % self.names[0] def __getstate__(self): return self.__dict__ def __setstate__(self, state): # migration if 'name' in state: state['names'] = [state.pop('name')] self.__dict__.update(state) class StartTimer: def __repr__(self): return '<StartTimer>' notpassed = object() class SplitsRecord(collections.OrderedDict): def segment_time(self, split, level=0, fallback=notpassed): found_prev = None for cur in self: if cur == split: break if cur.level <= level: found_prev = cur else: if fallback is not notpassed: return fallback raise KeyError(split) if found_prev is None: return self[split] elif self[split] is None or self[found_prev] is None: return None else: return self[split] - self[found_prev] class Route(collections.UserList): def __init__(self, name, time_field, pieces, level_names, reset_trigger): if type(pieces[-1]) is not Split or pieces[-1].level != 0: raise TypeError("Last piece of route must be top-level Split") super().__init__(pieces) self.name = name self.time_field = time_field self.levels = max(piece.level for piece in pieces if type(piece) is Split) + 1 self.splits = [x for x in self if type(x) is Split] self.level_names = level_names self.reset_trigger = reset_trigger def __getstate__(self): return (list(self), self.name, self.time_field, self.level_names, self.reset_trigger) def __setstate__(self, state): if type(state) is dict: self.__dict__.update(state) elif len(state) == 3: self.__init__(state[1], state[2], state[0], ['Segment', 'Subsegment'], None) else: self.__init__(state[1], state[2], state[0], state[3], state[4]) def split_idx(self, i, level=0): while type(self[i]) is not Split or self[i].level > level: i += 1 if i >= len(self): return None return self.splits.index(self[i]) @property def all_subsegments(self): prev = None for split in self.splits: if prev is not None: for level in range(prev.level, split.level, -1): yield (split, level) yield (split, split.level) prev = split class SplitsManager: def __init__(self, asi, route, compare_pb=None, compare_best=None): self.asi = asi self.route = route self.compare_pb = compare_pb if compare_pb is not None else SplitsRecord() self.compare_best = compare_best if compare_best is not None else {} self.current_times = SplitsRecord() self.current_piece_idx = 0 self.start_time = 0 self.started = False # migration parents = {} for split in self.route.splits: parents[split.level] = split if split not in self.compare_pb: self.compare_pb[split] = None else: self.compare_pb.move_to_end(split) for level in range(split.level, self.route.levels): key = (split, level) if key not in self.compare_best: self.compare_best[key] = None @property def done(self): return self.current_piece_idx >= len(self.route) @property def current_piece(self): if self.done: return None return self.route[self.current_piece_idx] def _current_split_idx(self, level=0): idx = self.route.split_idx(self.current_piece_idx, level) if idx is None: return None while self.route.splits[idx].level > level: idx += 1 return idx def _forward_split(self, idx, level=0): idx += 1 if idx >= len(self.route.splits): return None while self.route.splits[idx].level > level: idx += 1 if idx >= len(self.route.splits): return None return idx def _backwards_split(self, idx, level=0): idx -= 1 if idx < 0: return None while self.route.splits[idx].level > level: idx -= 1 if idx < 0: return None return idx def current_split(self, level=0): if self.done: return None idx = self._current_split_idx(level) return self.route.splits[idx] def previous_split(self, level=0): idx = self._current_split_idx(level) idx = self._backwards_split(idx, level) if idx is None: return None return self.route.splits[idx] def is_segment_done(self, split): return self.current_piece_idx > self.route.index(split) @property def current_time(self): return self.asi[self.route.time_field] - self.start_time def current_segment_time(self, level=0): if self.done: return None prev_split = self.previous_split(level) if prev_split is None: return self.current_time split_start = self.current_times[prev_split] if split_start is None: return None return self.current_time - split_start def best_possible_time(self): return None def split(self, split): self.current_times[split] = self.current_time def commit(self): if self.route.splits[-1] in self.current_times: cur_time = self.current_times[self.route.splits[-1]] pb_time = self.compare_pb[self.route.splits[-1]] if pb_time is None or cur_time < pb_time: self.compare_pb = self.current_times # TODO: do we care about not mutating this reference? self.compare_best = dict(self.compare_best) for key in self.route.all_subsegments: split, level = key seg = self.current_times.segment_time(split, level, None) best = self.compare_best[key] if seg is not None and (best is None or seg < best): self.compare_best[key] = seg def reset(self): self.current_piece_idx = 0 self.current_times = SplitsRecord() self.started = False self.start_time = 0 def skip(self, n=1): while not self.done: if type(self.current_piece) is Split: self.current_times[self.current_piece] = None self.current_piece_idx += 1 elif type(self.current_piece) is StartTimer: self.start_time = self.asi[self.route.time_field] self.current_piece_idx += 1 else: if n: self.started = True self.current_piece_idx += 1 n -= 1 else: break def rewind(self, n=1): while self.current_piece_idx: if type(self.current_piece) is Split: del self.current_times[self.current_piece] self.current_piece_idx -= 1 elif type(self.current_piece) is StartTimer: self.current_piece_idx -= 1 self.started = False else: if n: self.current_piece_idx -= 1 n -= 1 else: if self.current_piece.check_trigger(self.asi): self.current_piece_idx -= 1 else: break def update(self): if type(self.route.reset_trigger) is Trigger and self.route.reset_trigger.check_trigger(self.asi): self.commit() self.reset() if self.done: return while not self.done: if type(self.current_piece) is Split: self.split(self.current_piece) self.current_piece_idx += 1 elif type(self.current_piece) is StartTimer: self.start_time = self.asi[self.route.time_field] self.current_piece_idx += 1 else: if self.current_piece.check_trigger(self.asi): self.started = True self.current_piece_idx += 1 else: break def parse_mapname(line): if line.lower() == 'farewell': return 10, 0 if line.lower() == 'prologue': return 0, 0 if line.isdigit(): side = 'a' else: line, side = line[:-1], line[-1] side = side.lower() assert side in ('a', 'b', 'c') mode = ord(side) - ord('a') chapter = int(line) if chapter >= 8: chapter += 1 return chapter, mode def _main(): asi = AutoSplitterInfo() max_width = max(len(attr) for attr in asi.all_attrs) while True: data = '\x1b\x5b\x48\x1b\x5b\x4a' time.sleep(0.01) for attr in asi.all_attrs: val = asi.dict[attr] if attr.endswith('_time'): val = fmt_time(val) data += attr.ljust(max_width) + ': ' + str(val) + '\n' print(data) if __name__ == '__main__': _main()
run_dispatcher.py
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. import os import logging from multiprocessing import Process from django.conf import settings from django.core.cache import cache as django_cache from django.core.management.base import BaseCommand from django.db import connection as django_connection, connections from kombu import Connection, Exchange, Queue from awx.main.dispatch import get_local_queuename, reaper from awx.main.dispatch.control import Control from awx.main.dispatch.pool import AutoscalePool from awx.main.dispatch.worker import AWXConsumer, TaskWorker logger = logging.getLogger('awx.main.dispatch') def construct_bcast_queue_name(common_name): return common_name.encode('utf8') + '_' + settings.CLUSTER_HOST_ID class Command(BaseCommand): help = 'Launch the task dispatcher' def add_arguments(self, parser): parser.add_argument('--status', dest='status', action='store_true', help='print the internal state of any running dispatchers') parser.add_argument('--running', dest='running', action='store_true', help='print the UUIDs of any tasked managed by this dispatcher') parser.add_argument('--reload', dest='reload', action='store_true', help=('cause the dispatcher to recycle all of its worker processes;' 'running jobs will run to completion first')) def beat(self): from celery import Celery from celery.beat import PersistentScheduler from celery.apps import beat class AWXScheduler(PersistentScheduler): def __init__(self, *args, **kwargs): self.ppid = os.getppid() super(AWXScheduler, self).__init__(*args, **kwargs) def setup_schedule(self): super(AWXScheduler, self).setup_schedule() self.update_from_dict(settings.CELERYBEAT_SCHEDULE) def tick(self, *args, **kwargs): if os.getppid() != self.ppid: # if the parent PID changes, this process has been orphaned # via e.g., segfault or sigkill, we should exit too raise SystemExit() return super(AWXScheduler, self).tick(*args, **kwargs) def apply_async(self, entry, producer=None, advance=True, **kwargs): for conn in connections.all(): # If the database connection has a hiccup, re-establish a new # connection conn.close_if_unusable_or_obsolete() task = TaskWorker.resolve_callable(entry.task) result, queue = task.apply_async() class TaskResult(object): id = result['uuid'] return TaskResult() app = Celery() app.conf.BROKER_URL = settings.BROKER_URL app.conf.CELERY_TASK_RESULT_EXPIRES = False beat.Beat( 30, app, schedule='/var/lib/awx/beat.db', scheduler_cls=AWXScheduler ).run() def handle(self, *arg, **options): if options.get('status'): print Control('dispatcher').status() return if options.get('running'): print Control('dispatcher').running() return if options.get('reload'): return Control('dispatcher').control({'control': 'reload'}) # It's important to close these because we're _about_ to fork, and we # don't want the forked processes to inherit the open sockets # for the DB and memcached connections (that way lies race conditions) django_connection.close() django_cache.close() beat = Process(target=self.beat) beat.daemon = True beat.start() reaper.reap() consumer = None with Connection(settings.BROKER_URL) as conn: try: bcast = 'tower_broadcast_all' queues = [ Queue(q, Exchange(q), routing_key=q) for q in (settings.AWX_CELERY_QUEUES_STATIC + [get_local_queuename()]) ] queues.append( Queue( construct_bcast_queue_name(bcast), exchange=Exchange(bcast, type='fanout'), routing_key=bcast, reply=True ) ) consumer = AWXConsumer( 'dispatcher', conn, TaskWorker(), queues, AutoscalePool(min_workers=4) ) consumer.run() except KeyboardInterrupt: logger.debug('Terminating Task Dispatcher') if consumer: consumer.stop()
send.py
#!/usr/bin/env python3 """ @summary: submit many contract.set(arg) transactions to the example contract @version: v06 (24/April/2018) @since: 17/April/2018 @author: https://github.com/drandreaskrueger """ from config import RPCaddress, ROUTE, PRIVATE_FOR, ABI ################ ## Dependencies: from web3 import Web3, HTTPProvider # pip3 install web3 from web3.utils.abi import filter_by_name, abi_to_signature from web3.utils.encoding import pad_hex import sys, time, random from threading import Thread from queue import Queue from pprint import pprint import requests # pip3 install requests ################ ## basic tasks: def unlockAccount(address=None, password="", duration=3600): """ unlock once, then leave open, to not loose time for unlocking """ if not address: address = w3.eth.coinbase return w3.personal.unlockAccount(address, password, duration) def initialize(contractTx_blockNumber=1, contractTx_transactionIndex=0): """ use example contract from 7 nodes example if called without arguments, it assumes that the very first transaction was done by ./runscript.sh script1.js """ abi = ABI print ("Getting the address of the example contract that was deployed") block = w3.eth.getBlock(contractTx_blockNumber) transaction0=block["transactions"][contractTx_transactionIndex] print ("transaction hash = ", w3.toHex(transaction0)) address=w3.eth.getTransactionReceipt(transaction0)["contractAddress"] print ("contract address = ", address) contract = w3.eth.contract(address=address, abi=abi) print (contract) print("unlock account:", unlockAccount()) # pprint (dir(contract)) return contract def contract_set_via_web3(contract, arg, privateFor=PRIVATE_FOR, gas=90000): """ call the .set(arg) method, possibly with 'privateFor' tx-property using the web3 method """ txParameters = {'from': w3.eth.coinbase, 'gas' : gas} if privateFor: txParameters['privateFor'] = privateFor # untested # pprint (txParameters) tx = contract.functions.set( x=arg ).transact(txParameters) print ("[sent via web3]", end=" ") tx = w3.toHex(tx) return tx def test_contract_set_via_web3(contract): """ test the above """ tx = contract_set_via_web3(contract, arg=2) print (tx) storedData = contract.functions.get().call() print (storedData) ## Manually build & submit transaction, i.e. not going though web3 ## (the hope of @jpmsam was that this would speed it up) ## ## Later I realized that data compilation steps are already implemented as ## myContract.functions.myMethod(*args, **kwargs).buildTransaction(transaction) def contract_method_ID(methodname, abi): """ build the 4 byte ID, from abi & methodname """ method_abi = filter_by_name(methodname, abi) assert(len(method_abi)==1) method_abi = method_abi[0] method_signature = abi_to_signature(method_abi) method_signature_hash_bytes = w3.sha3(text=method_signature) method_signature_hash_hex = w3.toHex(method_signature_hash_bytes) method_signature_hash_4bytes = method_signature_hash_hex[0:10] return method_signature_hash_4bytes def argument_encoding(contract_method_ID, arg): """ concatenate method ID + padded parameter """ arg_hex = w3.toHex(arg) arg_hex_padded = pad_hex ( arg_hex, bit_size=256) data = contract_method_ID + arg_hex_padded [2:] return data def test_argument_encoding(): """ test the above: 'Doing that 10000 times ... took 0.45 seconds' """ timer = time.clock() reps = 10000 for i in range(reps): method_ID = contract_method_ID("set", ABI) data = argument_encoding(method_ID, 7) timer = time.clock() - timer print (data) # no need to precalculate, it takes near to no time: print ("Doing that %d times ... took %.2f seconds" % (reps, timer) ) def contract_set_via_RPC(contract, arg, privateFor=PRIVATE_FOR, gas=90000): """ call the .set(arg) method not going through web3 but directly via RPC suggestion by @jpmsam https://github.com/jpmorganchase/quorum/issues/346#issuecomment-382216968 """ method_ID = contract_method_ID("set", contract.abi) data = argument_encoding(method_ID, arg) txParameters = {'from': w3.eth.coinbase, 'to' : contract.address, 'gas' : w3.toHex(gas), 'data' : data} if privateFor: txParameters['privateFor'] = privateFor # untested method = 'eth_sendTransaction' payload= {"jsonrpc" : "2.0", "method" : method, "params" : [txParameters], "id" : 1} headers = {'Content-type' : 'application/json'} response = requests.post(RPCaddress, json=payload, headers=headers) # print('raw json response: {}'.format(response.json())) tx = response.json()['result'] print ("[sent directly via RPC]", end=" ") return tx def test_contract_set_via_RPC(contract, steps=3): """ test the above, write 3 transactions, and check the storedData """ rand = random.randint(1, 100) for number in range(rand, rand+steps): tx = contract_set_via_RPC(contract, number) print ("after set(%d) tx" % number, tx, " the storedData now is", end=" ") storedData = contract.functions.get().call() print (storedData) # CHOOSE which route to choose (web3 / RPC) depending on constant ROUTE contract_set = contract_set_via_web3 if ROUTE=="web3" else contract_set_via_RPC ################################################################ ### ### benchmarking routines ### ### 0 blocking ### 1 async ### 2 async, queue, can give number of workers ### 3 async, batched (obsolete) ### ################################################################ def many_transactions(contract, howMany): """ naive approach, blocking --> 15 TPS """ print ("send %d transactions, non-async, one after the other:\n" % (howMany)) for i in range(howMany): tx = contract_set(contract, i) print ("set() transaction submitted: ", tx) # Web3.toHex(tx)) # new web3 def many_transactions_threaded(contract, howMany): """ submit many transactions multi-threaded. """ print ("send %d transactions, multi-threaded, one thread per tx:\n" % (howMany)) threads = [] for i in range(howMany): t = Thread(target = contract_set, args = (contract, 7)) threads.append(t) print (".", end="") print ("%d transaction threads created." % len(threads)) for t in threads: t.start() print (".", end="") sys.stdout.flush() print ("all threads started.") for t in threads: t.join() print ("all threads ended.") def many_transactions_threaded_Queue(contract, howMany, num_worker_threads=100): """ submit many transactions multi-threaded, with size limited threading Queue """ print ("send %d transactions, via multi-threading queue with %d workers:\n" % (howMany, num_worker_threads)) q = Queue() def worker(): while True: item = q.get() contract_set(contract, item) print (".", end=""); sys.stdout.flush() q.task_done() for i in range(num_worker_threads): t = Thread(target=worker) t.daemon = True t.start() print (".", end=""); sys.stdout.flush() print ("%d worker threads created." % num_worker_threads) for i in range(howMany): q.put (7) print (".", end=""); sys.stdout.flush() print ("%d items queued." % howMany) q.join() print ("\nall items - done.") def many_transactions_threaded_in_batches(contract, howMany, batchSize=25): """ submit many transactions multi-threaded; But in batches of rather small numbers. Does not give an advantage --> OBSOLETE, probably. """ print ("send %d transactions, multi-threaded, one thread per tx, in batches of %d parallel threads:\n" % (howMany, batchSize)) howManyLeft=howMany while howManyLeft>0: print ("Next batch of %d transactions ... %d left to do" % (batchSize, howManyLeft)) threads = [] for i in range(batchSize): t = Thread(target = contract_set, args = (contract, 7)) threads.append(t) print (".", end="") print ("%d transaction threads created." % len(threads)) for t in threads: t.start() print (".", end="") sys.stdout.flush() print ("all threads started.") for t in threads: t.join() print ("all threads ended.") howManyLeft -= batchSize ########################################################### ### ### choose, depending on CLI parameter ### ########################################################### def benchmark(): print("\nBlockNumber = ", w3.eth.blockNumber) if len(sys.argv)>1: if sys.argv[1]=="threaded1": many_transactions_threaded(contract, 1000) elif sys.argv[1]=="threaded2": num_workers = 100 if len(sys.argv)>2: try: num_workers = int(sys.argv[2]) except: pass numTx = 1000 many_transactions_threaded_Queue(contract, numTx, num_worker_threads=num_workers) elif sys.argv[1]=="threaded3": batchSize=25 many_transactions_threaded_in_batches(contract, howMany=1000, batchSize=batchSize) else: print ("Nope. Choice '%s'" % sys.argv[1], "not recognized.") else: many_transactions(contract, 1000) # blocking, non-async if __name__ == '__main__': # HTTP provider # (TODO: try IPC provider, when quorum-outside-vagrant starts working) global w3 w3 = Web3(HTTPProvider(RPCaddress, request_kwargs={'timeout': 120})) # test_argument_encoding(); exit() contract = initialize() # test_contract_set_via_web3(contract); exit() # test_contract_set_via_RPC(contract); exit() benchmark()
activity.py
#!/usr/bin/python # coding: utf8 import pigpio import time import kdate import logging import threading import os import ctypes #import docopt #import sys #import subprocess log = logging.getLogger("Foosball") class Activity: def __init__(self, pi, gpio, power=False, config=False, onVacant=None, onOccupied=None): self.pi=pi self.gpio=gpio self.gpio_power=power # Setup self.pi.set_mode(self.gpio, pigpio.INPUT) self.pi.set_pull_up_down(self.gpio, pigpio.PUD_DOWN) if self.gpio_power: # If power-gpio supplied, then set it up and turn off self.pi.set_mode(self.gpio_power, pigpio.OUTPUT) self.pi.write(self.gpio_power, 0) # Callback functions on table status change self.onVacant=onVacant self.onOccupied=onOccupied # Configuration variables self.activity_num_to_occupied = 3 self.activity_time_debounce = .5 self.activity_time_unoccupied = 20 self.activity_time_reset = 4 self.activity_time_reoccupied = None # Pins which mirrors sensor output and table status self.outputSensor=False self.outputStatus=False # Variables to set heartbeat of this thread and recieve heartbeat of main thread self.hearttime = time.time() self.heartmain = 0 # Status variables self.allwaysOn = 0 self.allwaysOff = 0 self.singleOn = 0 self.table_occupied = False self.move_time = 0 self.move_num = 0 self.lastactivity = 0 self.lastchange = time.time() self.buttontime = 0 # This function is called once to start the monitoring of the vibration sensor # Just runs an infinite loop, where it either waits for activity og vacancy # Runs external callback function when table status changes def run(self): self.tid=ctypes.CDLL('libc.so.6').syscall(224) log.info("Starting activity sensoring program (tid: %d)" % self.tid) # If sensor power is a gpio, then turn on sensor if self.gpio_power: log.debug("Turning on power to sensor") self.pi.write(self.gpio_power,1) # Main loop of activity thread while True: if self.table_occupied: log.debug("Waiting for vacant") self.wait_for_vacant() # Did we recieve a stop signal while we were wating? if self.stopsignal: break; # OK: Table is now vacant. Call onVacant callback, if it exists if self.onVacant: self.onVacant() else: log.debug("Waiting for occupied") self.wait_for_occupied() # Did we recieve a stop signal while we were wating? if self.stopsignal: break; # OK: Table is now occupied. Call onOccupied callback, if it exists if self.onOccupied: self.onOccupied() # We only get down here when activity thread is asked to quit # If power is configured. Turn off when exiting if self.gpio_power: log.debug("Turning off power to sensor") self.pi.write(self.gpio_power,0) self.pi.set_mode(self.gpio_power, pigpio.INPUT) def setAllwaysOn(self, state=False): log.info("Setting allwaysOn: %r" % state) self.allwaysOn=state self.allwaysOff=False def setAllwaysOff(self, state=False): log.info("Setting allwaysOff: %r" % state) self.allwaysOff=state self.allwaysOn=False def turnOn(self): self.singleOn = True def start(self): self.thread=threading.Thread(target=self.run, name="Activity") self.thread.start() self.stopsignal=False def stop(self): self.stopsignal=True def click(self): self.buttontime=time.time() def heartbeat(self): self.hearttime=time.time() # If we haven't heard from main thread in 2 minutes. Exit. if self.hearttime-self.heartmain > 120: log.debug("Main thread heartbeat too faint. Stoppong activity thread") self.stop() # Table is vacant # Wait for enough vibration triggers. Log each full hour with no activity # When ever a vibration is measured, check to see how long time passed # since last vibration. def wait_for_occupied(self): waitbeat=0 while True: self.heartbeat() if self.stopsignal: log.debug("Stop signal - Breaking out of occupied wait") break if self.allwaysOff: time.sleep(3) continue # Wait for activity for a few seconds # Needs to be short (during devel), so we can break out fast on program exit if self.singleOn or self.allwaysOn or self.pi.wait_for_edge(self.gpio, pigpio.RISING_EDGE, 3): self.output("sensor",1) log.debug("Activity detected...") newtime=time.time() self.lastactivity=newtime waitbeat=0 # Too long since last move - reset movements if newtime-self.move_time > self.activity_time_reset: log.debug(" long time since motion. Move_num reset...") self.move_num=0 # This was an extra movement, so increase movement count self.move_num+=1 log.debug(" Move_num new set to %d" % self.move_num) # Record time of latest movement self.move_time=newtime # If that was move_num movements in a row without "large" breaks, # ... then set table occupied and return from this function if self.move_num >= self.activity_num_to_occupied or self.singleOn or self.allwaysOn: if self.singleOn: log.info("Table turned on manually") self.singleOn=False if self.allwaysOn: log.info("Table turned on permanently") log.info("Table occupied - (vacant for %d seconds)" % (newtime-self.lastchange)) self.lastchange=newtime self.table_occupied=True # Set output pin to high to indicate table occupied self.output("status",1) return(True) # We need more movements before we think the table is occupied. # But first sleep a little, tó ignore fast vibrations within a short time else: time.sleep(self.activity_time_debounce) # No vibration detected for 3600 seconds. Let the log file know else: waitbeat+=1 if waitbeat%10==0: if waitbeat==10: log.info("No activity for 30 seconds") elif waitbeat==100: log.info("No activity for 5 minutes") elif waitbeat%1200==0: log.info("No activity last hour") def wait_for_vacant(self): while True: self.heartbeat() if self.stopsignal: log.debug("Stop signal - Breaking out of occupied wait") break if self.allwaysOn: time.sleep(3) continue # Wait a few seconds for activity if self.allwaysOff==0 and self.pi.wait_for_edge(self.gpio, pigpio.RISING_EDGE, 3): log.debug("Activity detected... Still occupied") self.lastactivity=time.time() self.buttontime=0 self.output("sensor",1) self.move_num+=1 # Add 1 movement counter - people are still playing # Sleep a little, to ignore fast vibrations within a short time - no need to run this loop 1000 times/s time.sleep(3) else: # 3 seconds passed with no activity. Check if enough time has passed, if not listen again # Check time since last activity or last button. If larger than limit, go to vacant newtime=time.time() if min(newtime-self.buttontime, newtime-self.lastactivity)<self.activity_time_unoccupied: continue # OK: Long activity break. Change table status to unoccupied self.output("status",0) log.info("Table vacant - (occupied for %d seconds, %d movements detected)" % (newtime-self.lastchange, self.move_num)) self.lastchange=newtime self.table_occupied=False return(True) # Define or undefine output GPIOs which mirrors the sensor reading and/or table status # May be used for instance for LED indicators def setOutput(self, sensorGPIO, statusGPIO): if sensorGPIO: self.outputSensor=sensorGPIO self.pi.set_mode(self.outputSensor, pigpio.OUTPUT) self.pi.write(self.outputSensor, 0) # Don't mirror sensor. If one is defined, remove it. elif self.outputSensor: self.pi.set_mode(self.outputSensor, pigpio.INPUT) self.outputSensor=False self.sensorcb = None if statusGPIO: self.outputStatus=statusGPIO self.pi.set_mode(self.outputStatus, pigpio.OUTPUT) self.pi.write(self.outputStatus, self.table_occupied) # Don't mirror status. If one is defined, remove it. elif self.outputStatus: self.pi.set_mode(self.outputStatus, pigpio.INPUT) self.outputStatus=False def output(self, sensor, level): if sensor=="sensor" and self.outputSensor: log.debug("Sensor output set to %d " % level) self.pi.write(self.outputSensor,level) threading.Timer(1.0, self.outputOff).start() elif sensor=="status" and self.outputStatus: log.debug("Status output set to %d " % level) self.pi.write(self.outputStatus,level) # Trigger function for vibration-sensor going low again. # Only used if sensor outputs are mirrored to another GPIO def outputOff(self): if self.outputSensor: log.debug("Sensor turned off") self.pi.write(self.outputSensor,0) def sensorOn(): if self.gpio_power: self.pi.write(self.gpio_power,1) def sensorOff(): if self.gpio_power: self.pi.write(self.gpio_power,0)
tello.py
import threading import socket import time import datetime import struct import sys import os from scapy.all import * from . import crc from . import logger from . import event from . import state from . import error from . import video_stream from . utils import * from . protocol import * from . import dispatcher log = logger.Logger('Tello') class Tello(object): EVENT_CONNECTED = event.Event('connected') EVENT_WIFI = event.Event('wifi') EVENT_LIGHT = event.Event('light') EVENT_FLIGHT_DATA = event.Event('fligt_data') EVENT_LOG_HEADER = event.Event('log_header') EVENT_LOG = EVENT_LOG_HEADER EVENT_LOG_RAWDATA = event.Event('log_rawdata') EVENT_LOG_DATA = event.Event('log_data') EVENT_LOG_CONFIG = event.Event('log_config') EVENT_TIME = event.Event('time') EVENT_VIDEO_FRAME = event.Event('video frame') EVENT_VIDEO_DATA = event.Event('video data') EVENT_DISCONNECTED = event.Event('disconnected') EVENT_FILE_RECEIVED = event.Event('file received') # internal events __EVENT_CONN_REQ = event.Event('conn_req') __EVENT_CONN_ACK = event.Event('conn_ack') __EVENT_TIMEOUT = event.Event('timeout') __EVENT_QUIT_REQ = event.Event('quit_req') # for backward comaptibility CONNECTED_EVENT = EVENT_CONNECTED WIFI_EVENT = EVENT_WIFI LIGHT_EVENT = EVENT_LIGHT FLIGHT_EVENT = EVENT_FLIGHT_DATA LOG_EVENT = EVENT_LOG TIME_EVENT = EVENT_TIME VIDEO_FRAME_EVENT = EVENT_VIDEO_FRAME STATE_DISCONNECTED = state.State('disconnected') STATE_CONNECTING = state.State('connecting') STATE_CONNECTED = state.State('connected') STATE_QUIT = state.State('quit') LOG_ERROR = logger.LOG_ERROR LOG_WARN = logger.LOG_WARN LOG_INFO = logger.LOG_INFO LOG_DEBUG = logger.LOG_DEBUG LOG_ALL = logger.LOG_ALL def __init__(self, port=9000, spoof_addr='192.168.0.2'): self.tello_addr = ('192.168.10.1', 8889) self.spoof_addr = spoof_addr self.base_pkt = IP(src=self.spoof_addr, dst=self.tello_addr[0]) / UDP(sport=port, dport=self.tello_addr[1]) self.debug = False self.pkt_seq_num = 0x01e4 self.port = port self.udpsize = 2000 self.left_x = 0.0 self.left_y = 0.0 self.right_x = 0.0 self.right_y = 0.0 self.sock = None self.state = self.STATE_DISCONNECTED self.lock = threading.Lock() self.connected = threading.Event() self.video_enabled = False self.prev_video_data_time = None self.video_data_size = 0 self.video_data_loss = 0 self.log = log self.exposure = 0 self.video_encoder_rate = 4 self.video_stream = None self.wifi_strength = 0 self.log_data = LogData(log) self.log_data_file = None self.log_data_header_recorded = False # video zoom state self.zoom = False # File recieve state. self.file_recv = {} # Map filenum -> protocol.DownloadedFile # Create a UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('', self.port)) self.sock.settimeout(2.0) dispatcher.connect(self.__state_machine, dispatcher.signal.All) threading.Thread(target=self.__recv_thread).start() threading.Thread(target=self.__video_thread).start() def set_loglevel(self, level): """ Set_loglevel controls the output messages. Valid levels are LOG_ERROR, LOG_WARN, LOG_INFO, LOG_DEBUG and LOG_ALL. """ log.set_level(level) def get_video_stream(self): """ Get_video_stream is used to prepare buffer object which receive video data from the drone. """ newly_created = False self.lock.acquire() log.info('get video stream') try: if self.video_stream is None: self.video_stream = video_stream.VideoStream(self) newly_created = True res = self.video_stream finally: self.lock.release() if newly_created: self.__send_exposure() self.__send_video_encoder_rate() self.start_video() return res def connect(self): """Connect is used to send the initial connection request to the drone.""" self.__publish(event=self.__EVENT_CONN_REQ) def wait_for_connection(self, timeout=None): """Wait_for_connection will block until the connection is established.""" if not self.connected.wait(timeout): raise error.TelloError('timeout') def __send_conn_req(self): port = 9617 port0 = (int(port/1000) % 10) << 4 | (int(port/100) % 10) port1 = (int(port/10) % 10) << 4 | (int(port/1) % 10) buf = 'conn_req:%c%c' % (chr(port0), chr(port1)) log.info('send connection request (cmd="%s%02x%02x")' % (str(buf[:-2]), port0, port1)) return self.send_packet(Packet(buf)) def subscribe(self, signal, handler): """Subscribe a event such as EVENT_CONNECTED, EVENT_FLIGHT_DATA, EVENT_VIDEO_FRAME and so on.""" dispatcher.connect(handler, signal) def __publish(self, event, data=None, **args): args.update({'data': data}) if 'signal' in args: del args['signal'] if 'sender' in args: del args['sender'] log.debug('publish signal=%s, args=%s' % (event, args)) dispatcher.send(event, sender=self, **args) def takeoff(self): """Takeoff tells the drones to liftoff and start flying.""" log.info('set altitude limit 30m') pkt = Packet(SET_ALT_LIMIT_CMD) pkt.add_byte(0x1e) # 30m pkt.add_byte(0x00) self.send_packet(pkt) log.info('takeoff (cmd=0x%02x seq=0x%04x)' % (TAKEOFF_CMD, self.pkt_seq_num)) pkt = Packet(TAKEOFF_CMD) pkt.fixup() return self.send_packet(pkt) def throw_and_go(self): """Throw_and_go starts a throw and go sequence""" log.info('throw_and_go (cmd=0x%02x seq=0x%04x)' % (THROW_AND_GO_CMD, self.pkt_seq_num)) pkt = Packet(THROW_AND_GO_CMD, 0x48) pkt.add_byte(0x00) pkt.fixup() return self.send_packet(pkt) def land(self): """Land tells the drone to come in for landing.""" log.info('land (cmd=0x%02x seq=0x%04x)' % (LAND_CMD, self.pkt_seq_num)) pkt = Packet(LAND_CMD) pkt.add_byte(0x00) pkt.fixup() return self.send_packet(pkt) def palm_land(self): """Tells the drone to wait for a hand underneath it and then land.""" log.info('palmland (cmd=0x%02x seq=0x%04x)' % (PALM_LAND_CMD, self.pkt_seq_num)) pkt = Packet(PALM_LAND_CMD) pkt.add_byte(0x00) pkt.fixup() return self.send_packet(pkt) def quit(self): """Quit stops the internal threads.""" log.info('quit') self.__publish(event=self.__EVENT_QUIT_REQ) def __send_time_command(self): log.info('send_time (cmd=0x%02x seq=0x%04x)' % (TIME_CMD, self.pkt_seq_num)) pkt = Packet(TIME_CMD, 0x50) pkt.add_byte(0) pkt.add_time() pkt.fixup() return self.send_packet(pkt) def __send_start_video(self): pkt = Packet(VIDEO_START_CMD, 0x60) pkt.fixup() return self.send_packet(pkt) def __send_video_mode(self, mode): pkt = Packet(VIDEO_MODE_CMD) pkt.add_byte(mode) pkt.fixup() return self.send_packet(pkt) def set_video_mode(self, zoom=False): """Tell the drone whether to capture 960x720 4:3 video, or 1280x720 16:9 zoomed video. 4:3 has a wider field of view (both vertically and horizontally), 16:9 is crisper.""" log.info('set video mode zoom=%s (cmd=0x%02x seq=0x%04x)' % ( zoom, VIDEO_START_CMD, self.pkt_seq_num)) self.zoom = zoom return self.__send_video_mode(int(zoom)) def start_video(self): """Start_video tells the drone to send start info (SPS/PPS) for video stream.""" log.info('start video (cmd=0x%02x seq=0x%04x)' % (VIDEO_START_CMD, self.pkt_seq_num)) self.video_enabled = True self.__send_exposure() self.__send_video_encoder_rate() return self.__send_start_video() def set_exposure(self, level): """Set_exposure sets the drone camera exposure level. Valid levels are 0, 1, and 2.""" if level < 0 or 2 < level: raise error.TelloError('Invalid exposure level') log.info('set exposure (cmd=0x%02x seq=0x%04x)' % (EXPOSURE_CMD, self.pkt_seq_num)) self.exposure = level return self.__send_exposure() def __send_exposure(self): pkt = Packet(EXPOSURE_CMD, 0x48) pkt.add_byte(self.exposure) pkt.fixup() return self.send_packet(pkt) def set_video_encoder_rate(self, rate): """Set_video_encoder_rate sets the drone video encoder rate.""" log.info('set video encoder rate (cmd=0x%02x seq=%04x)' % (VIDEO_ENCODER_RATE_CMD, self.pkt_seq_num)) self.video_encoder_rate = rate return self.__send_video_encoder_rate() def __send_video_encoder_rate(self): pkt = Packet(VIDEO_ENCODER_RATE_CMD, 0x68) pkt.add_byte(self.video_encoder_rate) pkt.fixup() return self.send_packet(pkt) def take_picture(self): log.info('take picture') return self.send_packet_data(TAKE_PICTURE_COMMAND, type=0x68) def up(self, val): """Up tells the drone to ascend. Pass in an int from 0-100.""" log.info('up(val=%d)' % val) self.left_y = val / 100.0 def down(self, val): """Down tells the drone to descend. Pass in an int from 0-100.""" log.info('down(val=%d)' % val) self.left_y = val / 100.0 * -1 def forward(self, val): """Forward tells the drone to go forward. Pass in an int from 0-100.""" log.info('forward(val=%d)' % val) self.right_y = val / 100.0 def backward(self, val): """Backward tells the drone to go in reverse. Pass in an int from 0-100.""" log.info('backward(val=%d)' % val) self.right_y = val / 100.0 * -1 def right(self, val): """Right tells the drone to go right. Pass in an int from 0-100.""" log.info('right(val=%d)' % val) self.right_x = val / 100.0 def left(self, val): """Left tells the drone to go left. Pass in an int from 0-100.""" log.info('left(val=%d)' % val) self.right_x = val / 100.0 * -1 def clockwise(self, val): """ Clockwise tells the drone to rotate in a clockwise direction. Pass in an int from 0-100. """ log.info('clockwise(val=%d)' % val) self.left_x = val / 100.0 def counter_clockwise(self, val): """ CounterClockwise tells the drone to rotate in a counter-clockwise direction. Pass in an int from 0-100. """ log.info('counter_clockwise(val=%d)' % val) self.left_x = val / 100.0 * -1 def flip_forward(self): """flip_forward tells the drone to perform a forwards flip""" log.info('flip_forward (cmd=0x%02x seq=0x%04x)' % (FLIP_CMD, self.pkt_seq_num)) pkt = Packet(FLIP_CMD, 0x70) pkt.add_byte(FlipFront) pkt.fixup() return self.send_packet(pkt) def flip_back(self): """flip_back tells the drone to perform a backwards flip""" log.info('flip_back (cmd=0x%02x seq=0x%04x)' % (FLIP_CMD, self.pkt_seq_num)) pkt = Packet(FLIP_CMD, 0x70) pkt.add_byte(FlipBack) pkt.fixup() return self.send_packet(pkt) def flip_right(self): """flip_right tells the drone to perform a right flip""" log.info('flip_right (cmd=0x%02x seq=0x%04x)' % (FLIP_CMD, self.pkt_seq_num)) pkt = Packet(FLIP_CMD, 0x70) pkt.add_byte(FlipRight) pkt.fixup() return self.send_packet(pkt) def flip_left(self): """flip_left tells the drone to perform a left flip""" log.info('flip_left (cmd=0x%02x seq=0x%04x)' % (FLIP_CMD, self.pkt_seq_num)) pkt = Packet(FLIP_CMD, 0x70) pkt.add_byte(FlipLeft) pkt.fixup() return self.send_packet(pkt) def flip_forwardleft(self): """flip_forwardleft tells the drone to perform a forwards left flip""" log.info('flip_forwardleft (cmd=0x%02x seq=0x%04x)' % (FLIP_CMD, self.pkt_seq_num)) pkt = Packet(FLIP_CMD, 0x70) pkt.add_byte(FlipForwardLeft) pkt.fixup() return self.send_packet(pkt) def flip_backleft(self): """flip_backleft tells the drone to perform a backwards left flip""" log.info('flip_backleft (cmd=0x%02x seq=0x%04x)' % (FLIP_CMD, self.pkt_seq_num)) pkt = Packet(FLIP_CMD, 0x70) pkt.add_byte(FlipBackLeft) pkt.fixup() return self.send_packet(pkt) def flip_forwardright(self): """flip_forwardright tells the drone to perform a forwards right flip""" log.info('flip_forwardright (cmd=0x%02x seq=0x%04x)' % (FLIP_CMD, self.pkt_seq_num)) pkt = Packet(FLIP_CMD, 0x70) pkt.add_byte(FlipForwardRight) pkt.fixup() return self.send_packet(pkt) def flip_backright(self): """flip_backleft tells the drone to perform a backwards right flip""" log.info('flip_backright (cmd=0x%02x seq=0x%04x)' % (FLIP_CMD, self.pkt_seq_num)) pkt = Packet(FLIP_CMD, 0x70) pkt.add_byte(FlipBackRight) pkt.fixup() return self.send_packet(pkt) def __fix_range(self, val, min=-1.0, max=1.0): if val < min: val = min elif val > max: val = max return val def set_throttle(self, throttle): """ Set_throttle controls the vertical up and down motion of the drone. Pass in an int from -1.0 ~ 1.0. (positive value means upward) """ if self.left_y != self.__fix_range(throttle): log.info('set_throttle(val=%4.2f)' % throttle) self.left_y = self.__fix_range(throttle) def set_yaw(self, yaw): """ Set_yaw controls the left and right rotation of the drone. Pass in an int from -1.0 ~ 1.0. (positive value will make the drone turn to the right) """ if self.left_x != self.__fix_range(yaw): log.info('set_yaw(val=%4.2f)' % yaw) self.left_x = self.__fix_range(yaw) def set_pitch(self, pitch): """ Set_pitch controls the forward and backward tilt of the drone. Pass in an int from -1.0 ~ 1.0. (positive value will make the drone move forward) """ if self.right_y != self.__fix_range(pitch): log.info('set_pitch(val=%4.2f)' % pitch) self.right_y = self.__fix_range(pitch) def set_roll(self, roll): """ Set_roll controls the the side to side tilt of the drone. Pass in an int from -1.0 ~ 1.0. (positive value will make the drone move to the right) """ if self.right_x != self.__fix_range(roll): log.info('set_roll(val=%4.2f)' % roll) self.right_x = self.__fix_range(roll) def __send_stick_command(self): pkt = Packet(STICK_CMD, 0x60) axis1 = int(1024 + 660.0 * self.right_x) & 0x7ff axis2 = int(1024 + 660.0 * self.right_y) & 0x7ff axis3 = int(1024 + 660.0 * self.left_y) & 0x7ff axis4 = int(1024 + 660.0 * self.left_x) & 0x7ff ''' 11 bits (-1024 ~ +1023) x 4 axis = 44 bits 44 bits will be packed in to 6 bytes (48 bits) axis4 axis3 axis2 axis1 | | | | | 4 3 2 1 0 98765432109876543210987654321098765432109876543210 | | | | | | | byte5 byte4 byte3 byte2 byte1 byte0 ''' log.debug("stick command: yaw=%4d thr=%4d pit=%4d rol=%4d" % (axis4, axis3, axis2, axis1)) log.debug("stick command: yaw=%04x thr=%04x pit=%04x rol=%04x" % (axis4, axis3, axis2, axis1)) pkt.add_byte(((axis2 << 11 | axis1) >> 0) & 0xff) pkt.add_byte(((axis2 << 11 | axis1) >> 8) & 0xff) pkt.add_byte(((axis3 << 11 | axis2) >> 5) & 0xff) pkt.add_byte(((axis4 << 11 | axis3) >> 2) & 0xff) pkt.add_byte(((axis4 << 11 | axis3) >> 10) & 0xff) pkt.add_byte(((axis4 << 11 | axis3) >> 18) & 0xff) pkt.add_time() pkt.fixup() log.debug("stick command: %s" % byte_to_hexstring(pkt.get_buffer())) return self.send_packet(pkt) def __send_ack_log(self, id): pkt = Packet(LOG_HEADER_MSG, 0x50) pkt.add_byte(0x00) b0, b1 = le16(id) pkt.add_byte(b0) pkt.add_byte(b1) pkt.fixup() return self.send_packet(pkt) def send_packet(self, pkt): """Send_packet is used to send a command packet to the drone.""" try: cmd = pkt.get_buffer() send(self.base_pkt / Raw(load=cmd)) #self.sock.sendto(cmd, self.tello_addr) log.debug("send_packet: %s" % byte_to_hexstring(cmd)) except socket.error as err: if self.state == self.STATE_CONNECTED: log.error("send_packet: %s" % str(err)) else: log.info("send_packet: %s" % str(err)) return False return True def send_packet_data(self, command, type=0x68, payload=[]): pkt = Packet(command, type, payload) pkt.fixup() return self.send_packet(pkt) def __process_packet(self, data): if isinstance(data, str): data = bytearray([x for x in data]) if str(data[0:9]) == 'conn_ack:' or data[0:9] == b'conn_ack:': log.info('connected. (port=%2x%2x)' % (data[9], data[10])) log.debug(' %s' % byte_to_hexstring(data)) if self.video_enabled: self.__send_exposure() self.__send_video_encoder_rate() self.__send_start_video() self.__publish(self.__EVENT_CONN_ACK, data) return True if data[0] != START_OF_PACKET: log.info('start of packet != %02x (%02x) (ignored)' % (START_OF_PACKET, data[0])) log.info(' %s' % byte_to_hexstring(data)) log.info(' %s' % str(map(chr, data))[1:-1]) return False pkt = Packet(data) cmd = uint16(data[5], data[6]) if cmd == LOG_HEADER_MSG: id = uint16(data[9], data[10]) log.info("recv: log_header: id=%04x, '%s'" % (id, str(data[28:54]))) log.debug("recv: log_header: %s" % byte_to_hexstring(data[9:])) self.__send_ack_log(id) self.__publish(event=self.EVENT_LOG_HEADER, data=data[9:]) if self.log_data_file and not self.log_data_header_recorded: self.log_data_file.write(data[12:-2]) self.log_data_header_recorded = True elif cmd == LOG_DATA_MSG: log.debug("recv: log_data: length=%d, %s" % (len(data[9:]), byte_to_hexstring(data[9:]))) self.__publish(event=self.EVENT_LOG_RAWDATA, data=data[9:]) try: self.log_data.update(data[10:]) if self.log_data_file: self.log_data_file.write(data[10:-2]) except Exception as ex: log.error('%s' % str(ex)) self.__publish(event=self.EVENT_LOG_DATA, data=self.log_data) elif cmd == LOG_CONFIG_MSG: log.debug("recv: log_config: length=%d, %s" % (len(data[9:]), byte_to_hexstring(data[9:]))) self.__publish(event=self.EVENT_LOG_CONFIG, data=data[9:]) elif cmd == WIFI_MSG: log.debug("recv: wifi: %s" % byte_to_hexstring(data[9:])) self.wifi_strength = data[9] self.__publish(event=self.EVENT_WIFI, data=data[9:]) elif cmd == LIGHT_MSG: log.debug("recv: light: %s" % byte_to_hexstring(data[9:])) self.__publish(event=self.EVENT_LIGHT, data=data[9:]) elif cmd == FLIGHT_MSG: flight_data = FlightData(data[9:]) flight_data.wifi_strength = self.wifi_strength log.debug("recv: flight data: %s" % str(flight_data)) self.__publish(event=self.EVENT_FLIGHT_DATA, data=flight_data) elif cmd == TIME_CMD: log.debug("recv: time data: %s" % byte_to_hexstring(data)) self.__publish(event=self.EVENT_TIME, data=data[7:9]) elif cmd in (TAKEOFF_CMD, LAND_CMD, VIDEO_START_CMD, VIDEO_ENCODER_RATE_CMD, PALM_LAND_CMD, EXPOSURE_CMD, THROW_AND_GO_CMD): log.info("recv: ack: cmd=0x%02x seq=0x%04x %s" % (uint16(data[5], data[6]), uint16(data[7], data[8]), byte_to_hexstring(data))) elif cmd == TELLO_CMD_FILE_SIZE: # Drone is about to send us a file. Get ready. # N.b. one of the fields in the packet is a file ID; by demuxing # based on file ID we can receive multiple files at once. This # code doesn't support that yet, though, so don't take one photo # while another is still being received. log.info("recv: file size: %s" % byte_to_hexstring(data)) if len(pkt.get_data()) >= 7: (size, filenum) = struct.unpack('<xLH', pkt.get_data()) log.info(' file size: num=%d bytes=%d' % (filenum, size)) # Initialize file download state. self.file_recv[filenum] = DownloadedFile(filenum, size) else: # We always seem to get two files, one with most of the payload missing. # Not sure what the second one is for. log.warn(' file size: payload too small: %s' % byte_to_hexstring(pkt.get_data())) # Ack the packet. self.send_packet(pkt) elif cmd == TELLO_CMD_FILE_DATA: # log.info("recv: file data: %s" % byte_to_hexstring(data[9:21])) # Drone is sending us a fragment of a file it told us to prepare # for earlier. self.recv_file_data(pkt.get_data()) else: log.info('unknown packet: %04x %s' % (cmd, byte_to_hexstring(data))) return False return True def recv_file_data(self, data): (filenum,chunk,fragment,size) = struct.unpack('<HLLH', data[0:12]) file = self.file_recv.get(filenum, None) # Preconditions. if file is None: return if file.recvFragment(chunk, fragment, size, data[12:12+size]): # Did this complete a chunk? Ack the chunk so the drone won't # re-send it. self.send_packet_data(TELLO_CMD_FILE_DATA, type=0x50, payload=struct.pack('<BHL', 0, filenum, chunk)) if file.done(): # We have the whole file! First, send a normal ack with the first # byte set to 1 to indicate file completion. self.send_packet_data(TELLO_CMD_FILE_DATA, type=0x50, payload=struct.pack('<BHL', 1, filenum, chunk)) # Then send the FILE_COMPLETE packed separately telling it how # large we thought the file was. self.send_packet_data(TELLO_CMD_FILE_COMPLETE, type=0x48, payload=struct.pack('<HL', filenum, file.size)) # Inform subscribers that we have a file and clean up. self.__publish(event=self.EVENT_FILE_RECEIVED, data=file.data()) del self.file_recv[filenum] def record_log_data(self, path = None): if path == None: path = '%s/Documents/tello-%s.dat' % ( os.getenv('HOME'), datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S')) log.info('record log data in %s' % path) self.log_data_file = open(path, 'wb') def __state_machine(self, event, sender, data, **args): self.lock.acquire() cur_state = self.state event_connected = False event_disconnected = False log.debug('event %s in state %s' % (str(event), str(self.state))) if self.state == self.STATE_DISCONNECTED: if event == self.__EVENT_CONN_REQ: self.__send_conn_req() self.state = self.STATE_CONNECTING elif event == self.__EVENT_QUIT_REQ: self.state = self.STATE_QUIT event_disconnected = True self.video_enabled = False elif self.state == self.STATE_CONNECTING: if event == self.__EVENT_CONN_ACK: self.state = self.STATE_CONNECTED event_connected = True # send time self.__send_time_command() elif event == self.__EVENT_TIMEOUT: self.__send_conn_req() elif event == self.__EVENT_QUIT_REQ: self.state = self.STATE_QUIT elif self.state == self.STATE_CONNECTED: if event == self.__EVENT_TIMEOUT: self.__send_conn_req() self.state = self.STATE_CONNECTING event_disconnected = True self.video_enabled = False elif event == self.__EVENT_QUIT_REQ: self.state = self.STATE_QUIT event_disconnected = True self.video_enabled = False elif self.state == self.STATE_QUIT: pass if cur_state != self.state: log.info('state transit %s -> %s' % (cur_state, self.state)) self.lock.release() if event_connected: self.__publish(event=self.EVENT_CONNECTED, **args) self.connected.set() if event_disconnected: self.__publish(event=self.EVENT_DISCONNECTED, **args) self.connected.clear() def __recv_thread(self): sock = self.sock while self.state != self.STATE_QUIT: if self.state == self.STATE_CONNECTED: self.__send_stick_command() # ignore errors try: data, server = sock.recvfrom(self.udpsize) log.debug("recv: %s" % byte_to_hexstring(data)) self.__process_packet(data) except socket.timeout as ex: if self.state == self.STATE_CONNECTED: log.error('recv: timeout') self.__publish(event=self.__EVENT_TIMEOUT) except Exception as ex: log.error('recv: %s' % str(ex)) show_exception(ex) log.info('exit from the recv thread.') def __video_thread(self): log.info('start video thread') # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = 6038 sock.bind(('', port)) sock.settimeout(1.0) sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 512 * 1024) log.info('video receive buffer size = %d' % sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)) prev_video_data = None prev_ts = None history = [] while self.state != self.STATE_QUIT: if not self.video_enabled: time.sleep(1.0) continue try: data, server = sock.recvfrom(self.udpsize) now = datetime.datetime.now() log.debug("video recv: %s %d bytes" % (byte_to_hexstring(data[0:2]), len(data))) show_history = False # check video data loss video_data = VideoData(data) loss = video_data.gap(prev_video_data) if loss != 0: self.video_data_loss += loss # enable this line to see packet history # show_history = True prev_video_data = video_data # check video data interval if prev_ts is not None and 0.1 < (now - prev_ts).total_seconds(): log.info('video recv: %d bytes %02x%02x +%03d' % (len(data), byte(data[0]), byte(data[1]), (now - prev_ts).total_seconds() * 1000)) prev_ts = now # save video data history history.append([now, len(data), byte(data[0])*256 + byte(data[1])]) if 100 < len(history): history = history[1:] # show video data history if show_history: prev_ts = history[0][0] for i in range(1, len(history)): [ ts, sz, sn ] = history[i] print(' %02d:%02d:%02d.%03d %4d bytes %04x +%03d%s' % (ts.hour, ts.minute, ts.second, ts.microsecond/1000, sz, sn, (ts - prev_ts).total_seconds()*1000, (' *' if i == len(history) - 1 else ''))) prev_ts = ts history = history[-1:] # deliver video frame to subscribers self.__publish(event=self.EVENT_VIDEO_FRAME, data=data[2:]) self.__publish(event=self.EVENT_VIDEO_DATA, data=data) # show video frame statistics if self.prev_video_data_time is None: self.prev_video_data_time = now self.video_data_size += len(data) dur = (now - self.prev_video_data_time).total_seconds() if 2.0 < dur: log.info(('video data %d bytes %5.1fKB/sec' % (self.video_data_size, self.video_data_size / dur / 1024)) + ((' loss=%d' % self.video_data_loss) if self.video_data_loss != 0 else '')) self.video_data_size = 0 self.prev_video_data_time = now self.video_data_loss = 0 # keep sending start video command self.__send_start_video() except socket.timeout as ex: log.error('video recv: timeout') self.start_video() data = None except Exception as ex: log.error('video recv: %s' % str(ex)) show_exception(ex) log.info('exit from the video thread.') if __name__ == '__main__': print('You can use test.py for testing.')
subconsole.py
# special import os, datetime import threading import subprocess import platform from .salesforce.myconsole import MyConsole from . import logging IS_WINDOWS = platform.system() == "Windows" IS_MAC = platform.system() == "Darwin" IS_Linux = platform.system() == "Linux" def xstr(s): if s is None: return '' else: return str(s) class SublConsole(MyConsole): def __init__(self): pass def info(self, obj): logging.info(obj) def error(self, obj): logging.error(obj) def debug(self, obj): logging.debug(obj) def log(self, msg): logging.info(msg) def showlog(self, obj, type='info', show_time=True): panel_name = "salesforcexytools-log-" if show_time: now = datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S]") now = now + "[" + type + "] " msg = now + str(obj) else: msg = str(obj) logging.info(msg) def show_in_dialog(self, message_str): logging.info(xstr(message_str)) def status(self, msg, thread=False): if not thread: logging.debug(msg) else: self.status(msg) def handle_thread(self, thread, msg=None, counter=0, direction=1, width=8): if thread.is_alive(): next = counter + direction if next > width: direction = -1 elif next < 0: direction = 1 bar = [' '] * (width + 1) bar[counter] = '=' counter += direction self.status('%s [%s]' % (msg, ''.join(bar))) # sublime.set_timeout( # lambda: self.handle_thread(thread, msg, counter, direction, # width), 100) else: self.status(' ok ') def save_and_open_in_panel(self, message_str, save_dir, save_file_name, is_open=True): save_path = os.path.join(save_dir, save_file_name) self.debug("save file : " + save_path) # delete old file if os.path.isfile(save_path): os.remove(save_path) # save file self.save_file(save_path, message_str) return save_path def save_file(self, full_path, content, encoding='utf-8'): if not os.path.exists(os.path.dirname(full_path)): self.debug("mkdir: " + os.path.dirname(full_path)) os.makedirs(os.path.dirname(full_path)) try: fp = open(full_path, "w", newline='\n', encoding=encoding) fp.write(content) except Exception as e: self.error('save file error! ' + full_path) self.error(e) finally: fp.close() def show_in_new_tab(self, message_str, name=None): view = self.window.new_file() view.settings().set('word_wrap', 'false') view.set_syntax_file('Packages/Java/Java.tmLanguage') if name: view.set_name(name) view.run_command("insert_snippet", {"contents": xstr(message_str)}) def open_project(self, open_path): # executable_path = sublime.executable_path() executable_path = "" if IS_MAC: app_path = executable_path[:executable_path.rfind(".app/") + 5] executable_path = app_path + "Contents/SharedSupport/bin/subl" if IS_WINDOWS: subprocess.Popen('"{0}" --project "{1}"'.format( executable_path, open_path), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) else: process = subprocess.Popen( [executable_path, '--project', open_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() self.debug(stdout) self.showlog(stderr) def open_in_new_tab(self, message, tab_name): view = self.window.new_file() view.run_command("new_view", {"name": tab_name, "input": message}) def insert_str(self, message_str): self.window.run_command("insert_snippet", {"contents": xstr(message_str)}) def thread_run(self, group=None, target=None, name=None, args=()): thread = threading.Thread(target=target, args=args, name=name) thread.start() self.handle_thread(thread) return thread def close_views(self, main_path): for _view in self.window.views(): file_name = _view.file_name() if file_name and main_path in file_name: _view.close()
athenad.py
#!/usr/bin/env python3 import base64 import hashlib import io import json import os import sys import queue import random import select import socket import threading import time from collections import namedtuple from functools import partial from typing import Any import requests from jsonrpc import JSONRPCResponseManager, dispatcher from websocket import ABNF, WebSocketTimeoutException, WebSocketException, create_connection import cereal.messaging as messaging from cereal.services import service_list from common.api import Api from common.basedir import PERSIST from common.params import Params from common.realtime import sec_since_boot from selfdrive.hardware import HARDWARE, PC, TICI from selfdrive.loggerd.config import ROOT from selfdrive.loggerd.xattr_cache import getxattr, setxattr from selfdrive.swaglog import cloudlog, SWAGLOG_DIR from selfdrive.version import get_version, get_git_remote, get_git_branch, get_git_commit ATHENA_HOST = os.getenv('ATHENA_HOST', 'wss://api.retropilot.org:4040') HANDLER_THREADS = int(os.getenv('HANDLER_THREADS', "4")) LOCAL_PORT_WHITELIST = set([8022]) LOG_ATTR_NAME = 'user.upload' LOG_ATTR_VALUE_MAX_UNIX_TIME = int.to_bytes(2147483647, 4, sys.byteorder) RECONNECT_TIMEOUT_S = 70 dispatcher["echo"] = lambda s: s recv_queue: Any = queue.Queue() send_queue: Any = queue.Queue() upload_queue: Any = queue.Queue() log_send_queue: Any = queue.Queue() log_recv_queue: Any = queue.Queue() cancelled_uploads: Any = set() UploadItem = namedtuple('UploadItem', ['path', 'url', 'headers', 'created_at', 'id']) def handle_long_poll(ws): end_event = threading.Event() threads = [ threading.Thread(target=ws_recv, args=(ws, end_event), name='ws_recv'), threading.Thread(target=ws_send, args=(ws, end_event), name='ws_send'), threading.Thread(target=upload_handler, args=(end_event,), name='upload_handler'), threading.Thread(target=log_handler, args=(end_event,), name='log_handler'), ] + [ threading.Thread(target=jsonrpc_handler, args=(end_event,), name=f'worker_{x}') for x in range(HANDLER_THREADS) ] for thread in threads: thread.start() try: while not end_event.is_set(): time.sleep(0.1) except (KeyboardInterrupt, SystemExit): end_event.set() raise finally: for thread in threads: cloudlog.debug(f"athena.joining {thread.name}") thread.join() def jsonrpc_handler(end_event): dispatcher["startLocalProxy"] = partial(startLocalProxy, end_event) while not end_event.is_set(): try: data = recv_queue.get(timeout=1) if "method" in data: cloudlog.debug(f"athena.jsonrpc_handler.call_method {data}") response = JSONRPCResponseManager.handle(data, dispatcher) send_queue.put_nowait(response.json) elif "id" in data and ("result" in data or "error" in data): log_recv_queue.put_nowait(data) else: raise Exception("not a valid request or response") except queue.Empty: pass except Exception as e: cloudlog.exception("athena jsonrpc handler failed") send_queue.put_nowait(json.dumps({"error": str(e)})) def upload_handler(end_event): while not end_event.is_set(): try: item = upload_queue.get(timeout=1) if item.id in cancelled_uploads: cancelled_uploads.remove(item.id) continue _do_upload(item) except queue.Empty: pass except Exception: cloudlog.exception("athena.upload_handler.exception") def _do_upload(upload_item): with open(upload_item.path, "rb") as f: size = os.fstat(f.fileno()).st_size return requests.put(upload_item.url, data=f, headers={**upload_item.headers, 'Content-Length': str(size)}, timeout=30) # security: user should be able to request any message from their car @dispatcher.add_method def getMessage(service=None, timeout=1000): if service is None or service not in service_list: raise Exception("invalid service") socket = messaging.sub_sock(service, timeout=timeout) ret = messaging.recv_one(socket) if ret is None: raise TimeoutError return ret.to_dict() @dispatcher.add_method def getVersion(): return { "version": get_version(), "remote": get_git_remote(), "branch": get_git_branch(), "commit": get_git_commit(), } @dispatcher.add_method def setNavDestination(latitude=0, longitude=0): destination = { "latitude": latitude, "longitude": longitude, } Params().put("NavDestination", json.dumps(destination)) return {"success": 1} @dispatcher.add_method def listDataDirectory(): files = [os.path.relpath(os.path.join(dp, f), ROOT) for dp, dn, fn in os.walk(ROOT) for f in fn] return files @dispatcher.add_method def reboot(): sock = messaging.sub_sock("deviceState", timeout=1000) ret = messaging.recv_one(sock) if ret is None or ret.deviceState.started: raise Exception("Reboot unavailable") def do_reboot(): time.sleep(2) HARDWARE.reboot() threading.Thread(target=do_reboot).start() return {"success": 1} @dispatcher.add_method def uploadFileToUrl(fn, url, headers): if len(fn) == 0 or fn[0] == '/' or '..' in fn: return 500 path = os.path.join(ROOT, fn) if not os.path.exists(path): return 404 item = UploadItem(path=path, url=url, headers=headers, created_at=int(time.time() * 1000), id=None) upload_id = hashlib.sha1(str(item).encode()).hexdigest() item = item._replace(id=upload_id) upload_queue.put_nowait(item) return {"enqueued": 1, "item": item._asdict()} @dispatcher.add_method def listUploadQueue(): return [item._asdict() for item in list(upload_queue.queue)] @dispatcher.add_method def cancelUpload(upload_id): upload_ids = set(item.id for item in list(upload_queue.queue)) if upload_id not in upload_ids: return 404 cancelled_uploads.add(upload_id) return {"success": 1} @dispatcher.add_method def primeActivated(active): dongle_id = Params().get("DongleId", encoding='utf-8') api = Api(dongle_id) manage_tokens(api) def startLocalProxy(global_end_event, remote_ws_uri, local_port): try: if local_port not in LOCAL_PORT_WHITELIST: raise Exception("Requested local port not whitelisted") cloudlog.debug("athena.startLocalProxy.starting") params = Params() dongle_id = params.get("DongleId").decode('utf8') identity_token = Api(dongle_id).get_token() ws = create_connection(remote_ws_uri, cookie="jwt=" + identity_token, enable_multithread=True) ssock, csock = socket.socketpair() local_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) local_sock.connect(('127.0.0.1', local_port)) local_sock.setblocking(0) proxy_end_event = threading.Event() threads = [ threading.Thread(target=ws_proxy_recv, args=(ws, local_sock, ssock, proxy_end_event, global_end_event)), threading.Thread(target=ws_proxy_send, args=(ws, local_sock, csock, proxy_end_event)) ] for thread in threads: thread.start() cloudlog.debug("athena.startLocalProxy.started") return {"success": 1} except Exception as e: cloudlog.exception("athenad.startLocalProxy.exception") raise e @dispatcher.add_method def getPublicKey(): if not os.path.isfile(PERSIST + '/comma/id_rsa.pub'): return None with open(PERSIST + '/comma/id_rsa.pub', 'r') as f: return f.read() @dispatcher.add_method def getSshAuthorizedKeys(): return Params().get("GithubSshKeys", encoding='utf8') or '' @dispatcher.add_method def getSimInfo(): return HARDWARE.get_sim_info() @dispatcher.add_method def getNetworkType(): return HARDWARE.get_network_type() @dispatcher.add_method def getNetworks(): return HARDWARE.get_networks() @dispatcher.add_method def takeSnapshot(): from selfdrive.camerad.snapshot.snapshot import snapshot, jpeg_write ret = snapshot() if ret is not None: def b64jpeg(x): if x is not None: f = io.BytesIO() jpeg_write(f, x) return base64.b64encode(f.getvalue()).decode("utf-8") else: return None return {'jpegBack': b64jpeg(ret[0]), 'jpegFront': b64jpeg(ret[1])} else: raise Exception("not available while camerad is started") def get_logs_to_send_sorted(): # TODO: scan once then use inotify to detect file creation/deletion curr_time = int(time.time()) logs = [] for log_entry in os.listdir(SWAGLOG_DIR): log_path = os.path.join(SWAGLOG_DIR, log_entry) try: time_sent = int.from_bytes(getxattr(log_path, LOG_ATTR_NAME), sys.byteorder) except (ValueError, TypeError): time_sent = 0 # assume send failed and we lost the response if sent more than one hour ago if not time_sent or curr_time - time_sent > 3600: logs.append(log_entry) # return logs in order they should be sent # excluding most recent (active) log file return sorted(logs[:-1]) def log_handler(end_event): if PC: return log_files = [] last_scan = 0 while not end_event.is_set(): try: curr_scan = sec_since_boot() if curr_scan - last_scan > 10: log_files = get_logs_to_send_sorted() last_scan = curr_scan # send one log curr_log = None if len(log_files) > 0: log_entry = log_files.pop() cloudlog.debug(f"athena.log_handler.forward_request {log_entry}") try: curr_time = int(time.time()) log_path = os.path.join(SWAGLOG_DIR, log_entry) setxattr(log_path, LOG_ATTR_NAME, int.to_bytes(curr_time, 4, sys.byteorder)) with open(log_path, "r") as f: jsonrpc = { "method": "forwardLogs", "params": { "logs": f.read() }, "jsonrpc": "2.0", "id": log_entry } log_send_queue.put_nowait(json.dumps(jsonrpc)) curr_log = log_entry except OSError: pass # file could be deleted by log rotation # wait for response up to ~100 seconds # always read queue at least once to process any old responses that arrive for _ in range(100): if end_event.is_set(): break try: log_resp = json.loads(log_recv_queue.get(timeout=1)) log_entry = log_resp.get("id") log_success = "result" in log_resp and log_resp["result"].get("success") cloudlog.debug(f"athena.log_handler.forward_response {log_entry} {log_success}") if log_entry and log_success: log_path = os.path.join(SWAGLOG_DIR, log_entry) try: setxattr(log_path, LOG_ATTR_NAME, LOG_ATTR_VALUE_MAX_UNIX_TIME) except OSError: pass # file could be deleted by log rotation if curr_log == log_entry: break except queue.Empty: if curr_log is None: break except Exception: cloudlog.exception("athena.log_handler.exception") def ws_proxy_recv(ws, local_sock, ssock, end_event, global_end_event): while not (end_event.is_set() or global_end_event.is_set()): try: data = ws.recv() local_sock.sendall(data) except WebSocketTimeoutException: pass except Exception: cloudlog.exception("athenad.ws_proxy_recv.exception") break cloudlog.debug("athena.ws_proxy_recv closing sockets") ssock.close() local_sock.close() cloudlog.debug("athena.ws_proxy_recv done closing sockets") end_event.set() def ws_proxy_send(ws, local_sock, signal_sock, end_event): while not end_event.is_set(): try: r, _, _ = select.select((local_sock, signal_sock), (), ()) if r: if r[0].fileno() == signal_sock.fileno(): # got end signal from ws_proxy_recv end_event.set() break data = local_sock.recv(4096) if not data: # local_sock is dead end_event.set() break ws.send(data, ABNF.OPCODE_BINARY) except Exception: cloudlog.exception("athenad.ws_proxy_send.exception") end_event.set() cloudlog.debug("athena.ws_proxy_send closing sockets") signal_sock.close() cloudlog.debug("athena.ws_proxy_send done closing sockets") def ws_recv(ws, end_event): last_ping = int(sec_since_boot() * 1e9) while not end_event.is_set(): try: opcode, data = ws.recv_data(control_frame=True) if opcode in (ABNF.OPCODE_TEXT, ABNF.OPCODE_BINARY): if opcode == ABNF.OPCODE_TEXT: data = data.decode("utf-8") recv_queue.put_nowait(data) elif opcode == ABNF.OPCODE_PING: last_ping = int(sec_since_boot() * 1e9) Params().put("LastAthenaPingTime", str(last_ping)) except WebSocketTimeoutException: ns_since_last_ping = int(sec_since_boot() * 1e9) - last_ping if ns_since_last_ping > RECONNECT_TIMEOUT_S * 1e9: cloudlog.exception("athenad.ws_recv.timeout") end_event.set() except Exception: cloudlog.exception("athenad.ws_recv.exception") end_event.set() def ws_send(ws, end_event): while not end_event.is_set(): try: try: data = send_queue.get_nowait() except queue.Empty: data = log_send_queue.get(timeout=1) ws.send(data) except queue.Empty: pass except Exception: cloudlog.exception("athenad.ws_send.exception") end_event.set() def backoff(retries): return random.randrange(0, min(128, int(2 ** retries))) def manage_tokens(api): if not TICI: return try: params = Params() mapbox = api.get(f"/v1/tokens/mapbox/{api.dongle_id}/", timeout=5.0, access_token=api.get_token()) if mapbox.status_code == 200: params.put("MapboxToken", mapbox.json()["token"]) else: params.delete("MapboxToken") except Exception: cloudlog.exception("Failed to update tokens") def main(): params = Params() dongle_id = params.get("DongleId", encoding='utf-8') ws_uri = ATHENA_HOST + "/ws/v2/" + dongle_id api = Api(dongle_id) conn_retries = 0 while 1: try: cloudlog.event("athenad.main.connecting_ws", ws_uri=ws_uri) ws = create_connection(ws_uri, cookie="jwt=" + api.get_token(), enable_multithread=True, timeout=30.0) cloudlog.event("athenad.main.connected_ws", ws_uri=ws_uri) manage_tokens(api) conn_retries = 0 handle_long_poll(ws) except (KeyboardInterrupt, SystemExit): break except (ConnectionError, TimeoutError, WebSocketException): conn_retries += 1 params.delete("LastAthenaPingTime") if TICI: cloudlog.exception("athenad.main.exception2") except Exception: cloudlog.exception("athenad.main.exception") conn_retries += 1 params.delete("LastAthenaPingTime") time.sleep(backoff(conn_retries)) if __name__ == "__main__": main()
skype_connector.py
import configparser import os import queue import uuid import logging from threading import Thread, Timer from datetime import datetime from time import sleep from skpy import ( Skype, SkypeAuthException, SkypeEventLoop) from hub import outgoing_sk_msg_queue from common import incoming_msg_queue, is_image from skype_parser import parse_incoming_msg, parse_incoming_event TOKEN_FILE="skype_token" config = configparser.ConfigParser() config.read('config.ini') msg_to_skype_queue = queue.Queue() class MySkype(SkypeEventLoop): def onEvent(self, event): if event.type == 'NewMessage' and type(event).__name__ == 'SkypeNewMessageEvent': if event.msg.user: # ignore self if event.msg.user.id != self.user.id: #event.msg.chat.sendMsg(event.msg.content) msg = parse_incoming_msg(event.msg) incoming_msg_queue.put(msg) if event.type == 'ThreadUpdate': msg = parse_incoming_event(event) incoming_msg_queue.put(msg) def check_token_loop(conn): Timer(300, check_token_loop, [conn]).start() token_t = conn.tokenExpiry['skype'].timestamp() now_t = datetime.now().timestamp() if token_t - now_t < 600: print("Trying to refresh skype token...") try: conn.refreshSkypeToken() except SkypeAuthException as e: logging.error("Can't refresh skype token. Login request is rejected", repr(e)) except SkypeApiException as e: logging.error("Can't refresh skype token. Login form can't be processed", repr(e)) else: print("Skype token has been refreshed successfully") def outgoing_handler(sk): while True: try: outgoing = outgoing_sk_msg_queue.get() if outgoing == None: break chat_id = None if not outgoing['bridge']: # direct message chat_id = outgoing['msg'].chat_id elif outgoing['msg'].is_telegram: # forwarded message from telegram to skype chat_id = outgoing['bridge'].skype_id if chat_id: chat = sk.chats.chat(chat_id) if outgoing['msg'].content_full: chat.sendMsg(outgoing['msg'].content_full) if outgoing['msg'].file_obj['obj']: if is_image(outgoing['msg'].file_obj['name']): outgoing['msg'].file_obj['obj'].seek(0) chat.sendFile( outgoing['msg'].file_obj['obj'], outgoing['msg'].file_obj['name'], image = True) else: chat.sendFile( outgoing['msg'].file_obj['obj'], outgoing['msg'].file_obj['name'], image = False) set_status('ok') except Exception as e: logging.error("Skype outgoing handler error:", repr(e)) set_status('error') sleep(2) def set_status(status): f = open('skype_status.txt', 'w') f.write(status) f.close() def status_checker(sk): while True: mood = uuid.uuid4().hex.upper()[0:6] status = 'error' try: sk.setMood(mood) status = 'ok' except: pass set_status(status) sleep(15) def loop(sk): sk.loop() def run(): print("Skype connector is running") sk = Skype(connect=False) sk.conn.setTokenFile(TOKEN_FILE) try: sk.conn.readToken() #token file has expired or doesn't exist or not readable except SkypeAuthException: sk.conn.setUserPwd(config['main']['skype_login'], config['main']['skype_password']) sk.conn.getSkypeToken() sk = MySkype(tokenFile = TOKEN_FILE, autoAck = True) loop_thread = Thread(target = loop, args=(sk,)).start() outgoing_thread = Thread(target = outgoing_handler, args=(sk,)).start() status_thread = Thread(target = status_checker, args=(sk,)).start() check_token_loop(sk.conn)
wsdump.py
#!/Users/Lavender/Desktop/accel.ai/flask-aws/bin/python import argparse import code import sys import threading import time import six from six.moves.urllib.parse import urlparse import websocket try: import readline except ImportError: pass def get_encoding(): encoding = getattr(sys.stdin, "encoding", "") if not encoding: return "utf-8" else: return encoding.lower() OPCODE_DATA = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY) ENCODING = get_encoding() class VAction(argparse.Action): def __call__(self, parser, args, values, option_string=None): if values is None: values = "1" try: values = int(values) except ValueError: values = values.count("v") + 1 setattr(args, self.dest, values) def parse_args(): parser = argparse.ArgumentParser(description="WebSocket Simple Dump Tool") parser.add_argument("url", metavar="ws_url", help="websocket url. ex. ws://echo.websocket.org/") parser.add_argument("-p", "--proxy", help="proxy url. ex. http://127.0.0.1:8080") parser.add_argument("-v", "--verbose", default=0, nargs='?', action=VAction, dest="verbose", help="set verbose mode. If set to 1, show opcode. " "If set to 2, enable to trace websocket module") parser.add_argument("-n", "--nocert", action='store_true', help="Ignore invalid SSL cert") parser.add_argument("-r", "--raw", action="store_true", help="raw output") parser.add_argument("-s", "--subprotocols", nargs='*', help="Set subprotocols") parser.add_argument("-o", "--origin", help="Set origin") parser.add_argument("--eof-wait", default=0, type=int, help="wait time(second) after 'EOF' received.") parser.add_argument("-t", "--text", help="Send initial text") parser.add_argument("--timings", action="store_true", help="Print timings in seconds") parser.add_argument("--headers", help="Set custom headers. Use ',' as separator") return parser.parse_args() class RawInput: def raw_input(self, prompt): if six.PY3: line = input(prompt) else: line = raw_input(prompt) if ENCODING and ENCODING != "utf-8" and not isinstance(line, six.text_type): line = line.decode(ENCODING).encode("utf-8") elif isinstance(line, six.text_type): line = line.encode("utf-8") return line class InteractiveConsole(RawInput, code.InteractiveConsole): def write(self, data): sys.stdout.write("\033[2K\033[E") # sys.stdout.write("\n") sys.stdout.write("\033[34m< " + data + "\033[39m") sys.stdout.write("\n> ") sys.stdout.flush() def read(self): return self.raw_input("> ") class NonInteractive(RawInput): def write(self, data): sys.stdout.write(data) sys.stdout.write("\n") sys.stdout.flush() def read(self): return self.raw_input("") def main(): start_time = time.time() args = parse_args() if args.verbose > 1: websocket.enableTrace(True) options = {} if args.proxy: p = urlparse(args.proxy) options["http_proxy_host"] = p.hostname options["http_proxy_port"] = p.port if args.origin: options["origin"] = args.origin if args.subprotocols: options["subprotocols"] = args.subprotocols opts = {} if args.nocert: opts = {"cert_reqs": websocket.ssl.CERT_NONE, "check_hostname": False} if args.headers: options['header'] = map(str.strip, args.headers.split(',')) ws = websocket.create_connection(args.url, sslopt=opts, **options) if args.raw: console = NonInteractive() else: console = InteractiveConsole() print("Press Ctrl+C to quit") def recv(): try: frame = ws.recv_frame() except websocket.WebSocketException: return websocket.ABNF.OPCODE_CLOSE, None if not frame: raise websocket.WebSocketException("Not a valid frame %s" % frame) elif frame.opcode in OPCODE_DATA: return frame.opcode, frame.data elif frame.opcode == websocket.ABNF.OPCODE_CLOSE: ws.send_close() return frame.opcode, None elif frame.opcode == websocket.ABNF.OPCODE_PING: ws.pong(frame.data) return frame.opcode, frame.data return frame.opcode, frame.data def recv_ws(): while True: opcode, data = recv() msg = None if six.PY3 and opcode == websocket.ABNF.OPCODE_TEXT and isinstance(data, bytes): data = str(data, "utf-8") if not args.verbose and opcode in OPCODE_DATA: msg = data elif args.verbose: msg = "%s: %s" % (websocket.ABNF.OPCODE_MAP.get(opcode), data) if msg is not None: if args.timings: console.write(str(time.time() - start_time) + ": " + msg) else: console.write(msg) if opcode == websocket.ABNF.OPCODE_CLOSE: break thread = threading.Thread(target=recv_ws) thread.daemon = True thread.start() if args.text: ws.send(args.text) while True: try: message = console.read() ws.send(message) except KeyboardInterrupt: return except EOFError: time.sleep(args.eof_wait) return if __name__ == "__main__": try: main() except Exception as e: print(e)
test_client.py
import asyncio import gc import inspect import logging import os import pickle import random import subprocess import sys import threading import traceback import warnings import weakref import zipfile from collections import deque from contextlib import suppress from functools import partial from operator import add from threading import Semaphore from time import sleep import psutil import pytest from tlz import concat, first, identity, isdistinct, merge, pluck, valmap import dask import dask.bag as db from dask import delayed from dask.optimization import SubgraphCallable from dask.utils import stringify from distributed import ( CancelledError, Executor, LocalCluster, Nanny, TimeoutError, Worker, fire_and_forget, get_client, get_worker, performance_report, profile, secede, ) from distributed.client import ( Client, Future, _get_global_client, as_completed, default_client, futures_of, get_task_metadata, temp_default_client, tokenize, wait, ) from distributed.comm import CommClosedError from distributed.compatibility import LINUX, WINDOWS from distributed.core import Status from distributed.metrics import time from distributed.objects import HasWhat, WhoHas from distributed.scheduler import ( COMPILED, CollectTaskMetaDataPlugin, KilledWorker, Scheduler, ) from distributed.sizeof import sizeof from distributed.utils import is_valid_xml, mp_context, sync, tmp_text, tmpfile from distributed.utils_test import ( TaskStateMetadataPlugin, _UnhashableCallable, async_wait_for, asyncinc, captured_logger, cluster, dec, div, double, gen_cluster, gen_test, geninc, inc, map_varying, nodebug, popen, pristine_loop, randominc, save_sys_modules, slowadd, slowdec, slowinc, throws, varying, wait_for, ) pytestmark = pytest.mark.ci1 @gen_cluster(client=True) async def test_submit(c, s, a, b): x = c.submit(inc, 10) assert not x.done() assert isinstance(x, Future) assert x.client is c result = await x assert result == 11 assert x.done() y = c.submit(inc, 20) z = c.submit(add, x, y) result = await z assert result == 11 + 21 s.validate_state() @gen_cluster(client=True) async def test_map(c, s, a, b): L1 = c.map(inc, range(5)) assert len(L1) == 5 assert isdistinct(x.key for x in L1) assert all(isinstance(x, Future) for x in L1) result = await L1[0] assert result == inc(0) assert len(s.tasks) == 5 L2 = c.map(inc, L1) result = await L2[1] assert result == inc(inc(1)) assert len(s.tasks) == 10 # assert L1[0].key in s.tasks[L2[0].key] total = c.submit(sum, L2) result = await total assert result == sum(map(inc, map(inc, range(5)))) L3 = c.map(add, L1, L2) result = await L3[1] assert result == inc(1) + inc(inc(1)) L4 = c.map(add, range(3), range(4)) results = await c.gather(L4) assert results == list(map(add, range(3), range(4))) def f(x, y=10): return x + y L5 = c.map(f, range(5), y=5) results = await c.gather(L5) assert results == list(range(5, 10)) y = c.submit(f, 10) L6 = c.map(f, range(5), y=y) results = await c.gather(L6) assert results == list(range(20, 25)) s.validate_state() @gen_cluster(client=True) async def test_map_empty(c, s, a, b): L1 = c.map(inc, [], pure=False) assert len(L1) == 0 results = await c.gather(L1) assert results == [] @gen_cluster(client=True) async def test_map_keynames(c, s, a, b): futures = c.map(inc, range(4), key="INC") assert all(f.key.startswith("INC") for f in futures) assert isdistinct(f.key for f in futures) futures2 = c.map(inc, [5, 6, 7, 8], key="INC") assert [f.key for f in futures] != [f.key for f in futures2] keys = ["inc-1", "inc-2", "inc-3", "inc-4"] futures = c.map(inc, range(4), key=keys) assert [f.key for f in futures] == keys @gen_cluster(client=True) async def test_map_retries(c, s, a, b): args = [ [ZeroDivisionError("one"), 2, 3], [4, 5, 6], [ZeroDivisionError("seven"), ZeroDivisionError("eight"), 9], ] x, y, z = c.map(*map_varying(args), retries=2) assert await x == 2 assert await y == 4 assert await z == 9 x, y, z = c.map(*map_varying(args), retries=1, pure=False) assert await x == 2 assert await y == 4 with pytest.raises(ZeroDivisionError, match="eight"): await z x, y, z = c.map(*map_varying(args), retries=0, pure=False) with pytest.raises(ZeroDivisionError, match="one"): await x assert await y == 4 with pytest.raises(ZeroDivisionError, match="seven"): await z @gen_cluster(client=True) async def test_map_batch_size(c, s, a, b): result = c.map(inc, range(100), batch_size=10) result = await c.gather(result) assert result == list(range(1, 101)) result = c.map(add, range(100), range(100), batch_size=10) result = await c.gather(result) assert result == list(range(0, 200, 2)) # mismatch shape result = c.map(add, range(100, 200), range(10), batch_size=2) result = await c.gather(result) assert result == list(range(100, 120, 2)) @gen_cluster(client=True) async def test_custom_key_with_batches(c, s, a, b): """Test of <https://github.com/dask/distributed/issues/4588>""" futs = c.map( lambda x: x ** 2, range(10), batch_size=5, key=[str(x) for x in range(10)], ) assert len(futs) == 10 await wait(futs) @gen_cluster(client=True) async def test_compute_retries(c, s, a, b): args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] # Sanity check for varying() use x = c.compute(delayed(varying(args))()) with pytest.raises(ZeroDivisionError, match="one"): await x # Same retries for all x = c.compute(delayed(varying(args))(), retries=1) with pytest.raises(ZeroDivisionError, match="two"): await x x = c.compute(delayed(varying(args))(), retries=2) assert await x == 3 args.append(4) x = c.compute(delayed(varying(args))(), retries=2) assert await x == 3 @gen_cluster(client=True) async def test_compute_retries_annotations(c, s, a, b): # Per-future retries xargs = [ZeroDivisionError("one"), ZeroDivisionError("two"), 30, 40] yargs = [ZeroDivisionError("five"), ZeroDivisionError("six"), 70] zargs = [80, 90, 100] with dask.annotate(retries=2): x = delayed(varying(xargs))() y = delayed(varying(yargs))() x, y = c.compute([x, y], optimize_graph=False) gc.collect() assert await x == 30 with pytest.raises(ZeroDivisionError, match="five"): await y x = delayed(varying(xargs))() with dask.annotate(retries=2): y = delayed(varying(yargs))() z = delayed(varying(zargs))() x, y, z = c.compute([x, y, z], optimize_graph=False) with pytest.raises(ZeroDivisionError, match="one"): await x assert await y == 70 assert await z == 80 def test_retries_get(c): args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] x = delayed(varying(args))() assert x.compute(retries=5) == 3 args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] x = delayed(varying(args))() with pytest.raises(ZeroDivisionError): x.compute() @gen_cluster(client=True) async def test_compute_persisted_retries(c, s, a, b): args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] # Sanity check x = c.persist(delayed(varying(args))()) fut = c.compute(x) with pytest.raises(ZeroDivisionError, match="one"): await fut x = c.persist(delayed(varying(args))()) fut = c.compute(x, retries=1) with pytest.raises(ZeroDivisionError, match="two"): await fut x = c.persist(delayed(varying(args))()) fut = c.compute(x, retries=2) assert await fut == 3 args.append(4) x = c.persist(delayed(varying(args))()) fut = c.compute(x, retries=3) assert await fut == 3 @gen_cluster(client=True) async def test_persist_retries(c, s, a, b): # Same retries for all args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] x = c.persist(delayed(varying(args))(), retries=1) x = c.compute(x) with pytest.raises(ZeroDivisionError, match="two"): await x x = c.persist(delayed(varying(args))(), retries=2) x = c.compute(x) assert await x == 3 @gen_cluster(client=True) async def test_persist_retries_annotations(c, s, a, b): # Per-key retries xargs = [ZeroDivisionError("one"), ZeroDivisionError("two"), 30, 40] yargs = [ZeroDivisionError("five"), ZeroDivisionError("six"), 70] zargs = [80, 90, 100] x = delayed(varying(xargs))() with dask.annotate(retries=2): y = delayed(varying(yargs))() z = delayed(varying(zargs))() x, y, z = c.persist([x, y, z], optimize_graph=False) x, y, z = c.compute([x, y, z]) with pytest.raises(ZeroDivisionError, match="one"): await x assert await y == 70 assert await z == 80 @gen_cluster(client=True) async def test_retries_dask_array(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones((10, 10), chunks=(3, 3)) future = c.compute(x.sum(), retries=2) y = await future assert y == 100 @gen_cluster(client=True) async def test_future_repr(c, s, a, b): pd = pytest.importorskip("pandas") x = c.submit(inc, 10) y = c.submit(pd.DataFrame, {"x": [1, 2, 3]}) await x await y for func in [repr, lambda x: x._repr_html_()]: assert str(x.key) in func(x) assert str(x.status) in func(x) assert str(x.status) in repr(c.futures[x.key]) assert "int" in func(x) assert "pandas" in func(y) assert "DataFrame" in func(y) @gen_cluster(client=True) async def test_future_tuple_repr(c, s, a, b): da = pytest.importorskip("dask.array") y = da.arange(10, chunks=(5,)).persist() f = futures_of(y)[0] for func in [repr, lambda x: x._repr_html_()]: for k in f.key: assert str(k) in func(f) @gen_cluster(client=True) async def test_Future_exception(c, s, a, b): x = c.submit(div, 1, 0) result = await x.exception() assert isinstance(result, ZeroDivisionError) x = c.submit(div, 1, 1) result = await x.exception() assert result is None def test_Future_exception_sync(c): x = c.submit(div, 1, 0) assert isinstance(x.exception(), ZeroDivisionError) x = c.submit(div, 1, 1) assert x.exception() is None @gen_cluster(client=True) async def test_Future_release(c, s, a, b): # Released Futures should be removed timely from the Client x = c.submit(div, 1, 1) await x x.release() await asyncio.sleep(0) assert not c.futures x = c.submit(slowinc, 1, delay=0.5) x.release() await asyncio.sleep(0) assert not c.futures x = c.submit(div, 1, 0) await x.exception() x.release() await asyncio.sleep(0) assert not c.futures def test_Future_release_sync(c): # Released Futures should be removed timely from the Client x = c.submit(div, 1, 1) x.result() x.release() wait_for(lambda: not c.futures, timeout=0.3) x = c.submit(slowinc, 1, delay=0.8) x.release() wait_for(lambda: not c.futures, timeout=0.3) x = c.submit(div, 1, 0) x.exception() x.release() wait_for(lambda: not c.futures, timeout=0.3) def test_short_tracebacks(loop, c): tblib = pytest.importorskip("tblib") future = c.submit(div, 1, 0) try: future.result() except Exception: _, _, tb = sys.exc_info() tb = tblib.Traceback(tb).to_dict() n = 0 while tb is not None: n += 1 tb = tb["tb_next"] assert n < 5 @gen_cluster(client=True) async def test_map_naming(c, s, a, b): L1 = c.map(inc, range(5)) L2 = c.map(inc, range(5)) assert [x.key for x in L1] == [x.key for x in L2] L3 = c.map(inc, [1, 1, 1, 1]) assert len({x._state for x in L3}) == 1 L4 = c.map(inc, [1, 1, 1, 1], pure=False) assert len({x._state for x in L4}) == 4 @gen_cluster(client=True) async def test_submit_naming(c, s, a, b): a = c.submit(inc, 1) b = c.submit(inc, 1) assert a._state is b._state c = c.submit(inc, 1, pure=False) assert c.key != a.key @gen_cluster(client=True) async def test_exceptions(c, s, a, b): x = c.submit(div, 1, 2) result = await x assert result == 1 / 2 x = c.submit(div, 1, 0) with pytest.raises(ZeroDivisionError): await x x = c.submit(div, 10, 2) # continues to operate result = await x assert result == 10 / 2 @gen_cluster() async def test_gc(s, a, b): c = await Client(s.address, asynchronous=True) x = c.submit(inc, 10) await x assert s.tasks[x.key].who_has x.__del__() await async_wait_for( lambda: x.key not in s.tasks or not s.tasks[x.key].who_has, timeout=0.3 ) await c.close() def test_thread(c): x = c.submit(inc, 1) assert x.result() == 2 x = c.submit(slowinc, 1, delay=0.3) with pytest.raises(TimeoutError): x.result(timeout="10 ms") assert x.result() == 2 def test_sync_exceptions(c): x = c.submit(div, 10, 2) assert x.result() == 5 y = c.submit(div, 10, 0) try: y.result() assert False except ZeroDivisionError: pass z = c.submit(div, 10, 5) assert z.result() == 2 @gen_cluster(client=True) async def test_gather(c, s, a, b): x = c.submit(inc, 10) y = c.submit(inc, x) result = await c.gather(x) assert result == 11 result = await c.gather([x]) assert result == [11] result = await c.gather({"x": x, "y": [y]}) assert result == {"x": 11, "y": [12]} @gen_cluster(client=True) async def test_gather_lost(c, s, a, b): [x] = await c.scatter([1], workers=a.address) y = c.submit(inc, 1, workers=b.address) await a.close() with pytest.raises(Exception): await c.gather([x, y]) def test_gather_sync(c): x = c.submit(inc, 1) assert c.gather(x) == 2 y = c.submit(div, 1, 0) with pytest.raises(ZeroDivisionError): c.gather([x, y]) [xx] = c.gather([x, y], errors="skip") assert xx == 2 @gen_cluster(client=True) async def test_gather_strict(c, s, a, b): x = c.submit(div, 2, 1) y = c.submit(div, 1, 0) with pytest.raises(ZeroDivisionError): await c.gather([x, y]) [xx] = await c.gather([x, y], errors="skip") assert xx == 2 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)]) async def test_gather_skip(c, s, a): x = c.submit(div, 1, 0, priority=10) y = c.submit(slowinc, 1, delay=0.5) with captured_logger(logging.getLogger("distributed.scheduler")) as sched: with captured_logger(logging.getLogger("distributed.client")) as client: L = await c.gather([x, y], errors="skip") assert L == [2] assert not client.getvalue() assert not sched.getvalue() @gen_cluster(client=True) async def test_limit_concurrent_gathering(c, s, a, b): futures = c.map(inc, range(100)) await c.gather(futures) assert len(a.outgoing_transfer_log) + len(b.outgoing_transfer_log) < 100 @gen_cluster(client=True) async def test_get(c, s, a, b): future = c.get({"x": (inc, 1)}, "x", sync=False) assert isinstance(future, Future) result = await future assert result == 2 futures = c.get({"x": (inc, 1)}, ["x"], sync=False) assert isinstance(futures[0], Future) result = await c.gather(futures) assert result == [2] futures = c.get({}, [], sync=False) result = await c.gather(futures) assert result == [] result = await c.get( {("x", 1): (inc, 1), ("x", 2): (inc, ("x", 1))}, ("x", 2), sync=False ) assert result == 3 def test_get_sync(c): assert c.get({"x": (inc, 1)}, "x") == 2 def test_no_future_references(c): from weakref import WeakSet ws = WeakSet() futures = c.map(inc, range(10)) ws.update(futures) del futures import gc gc.collect() start = time() while list(ws): sleep(0.01) assert time() < start + 30 def test_get_sync_optimize_graph_passes_through(c): bag = db.range(10, npartitions=3).map(inc) dask.compute(bag.sum(), optimize_graph=False) @gen_cluster(client=True) async def test_gather_errors(c, s, a, b): def f(a, b): raise TypeError def g(a, b): raise AttributeError future_f = c.submit(f, 1, 2) future_g = c.submit(g, 1, 2) with pytest.raises(TypeError): await c.gather(future_f) with pytest.raises(AttributeError): await c.gather(future_g) await a.close() @gen_cluster(client=True) async def test_wait(c, s, a, b): x = c.submit(inc, 1) y = c.submit(inc, 1) z = c.submit(inc, 2) done, not_done = await wait([x, y, z]) assert done == {x, y, z} assert not_done == set() assert x.status == y.status == "finished" @gen_cluster(client=True) async def test_wait_first_completed(c, s, a, b): x = c.submit(slowinc, 1) y = c.submit(slowinc, 1) z = c.submit(inc, 2) done, not_done = await wait([x, y, z], return_when="FIRST_COMPLETED") assert done == {z} assert not_done == {x, y} assert z.status == "finished" assert x.status == "pending" assert y.status == "pending" @gen_cluster(client=True) async def test_wait_timeout(c, s, a, b): future = c.submit(sleep, 0.3) with pytest.raises(TimeoutError): await wait(future, timeout=0.01) def test_wait_sync(c): x = c.submit(inc, 1) y = c.submit(inc, 2) done, not_done = wait([x, y]) assert done == {x, y} assert not_done == set() assert x.status == y.status == "finished" future = c.submit(sleep, 0.3) with pytest.raises(TimeoutError): wait(future, timeout=0.01) def test_wait_informative_error_for_timeouts(c): x = c.submit(inc, 1) y = c.submit(inc, 2) try: wait(x, y) except Exception as e: assert "timeout" in str(e) assert "list" in str(e) @gen_cluster(client=True) async def test_garbage_collection(c, s, a, b): x = c.submit(inc, 1) y = c.submit(inc, 1) assert c.refcount[x.key] == 2 x.__del__() await asyncio.sleep(0) assert c.refcount[x.key] == 1 z = c.submit(inc, y) y.__del__() await asyncio.sleep(0) result = await z assert result == 3 ykey = y.key y.__del__() await asyncio.sleep(0) assert ykey not in c.futures @gen_cluster(client=True) async def test_garbage_collection_with_scatter(c, s, a, b): [future] = await c.scatter([1]) assert future.key in c.futures assert future.status == "finished" assert s.who_wants[future.key] == {c.id} key = future.key assert c.refcount[key] == 1 future.__del__() await asyncio.sleep(0) assert c.refcount[key] == 0 while key in s.tasks and s.tasks[key].who_has: await asyncio.sleep(0.1) @gen_cluster(client=True) async def test_recompute_released_key(c, s, a, b): x = c.submit(inc, 100) result1 = await x xkey = x.key del x import gc gc.collect() await asyncio.sleep(0) assert c.refcount[xkey] == 0 # 1 second batching needs a second action to trigger while xkey in s.tasks and s.tasks[xkey].who_has or xkey in a.data or xkey in b.data: await asyncio.sleep(0.1) x = c.submit(inc, 100) assert x.key in c.futures result2 = await x assert result1 == result2 @pytest.mark.slow @gen_cluster(client=True) async def test_long_tasks_dont_trigger_timeout(c, s, a, b): from time import sleep x = c.submit(sleep, 3) await x @pytest.mark.skip @gen_cluster(client=True) async def test_missing_data_heals(c, s, a, b): a.validate = False b.validate = False x = c.submit(inc, 1) y = c.submit(inc, x) z = c.submit(inc, y) await wait([x, y, z]) # Secretly delete y's key if y.key in a.data: del a.data[y.key] a.release_key(y.key) if y.key in b.data: del b.data[y.key] b.release_key(y.key) await asyncio.sleep(0) w = c.submit(add, y, z) result = await w assert result == 3 + 4 @pytest.mark.skip @gen_cluster(client=True) async def test_gather_robust_to_missing_data(c, s, a, b): a.validate = False b.validate = False x, y, z = c.map(inc, range(3)) await wait([x, y, z]) # everything computed for f in [x, y]: for w in [a, b]: if f.key in w.data: del w.data[f.key] await asyncio.sleep(0) w.release_key(f.key) xx, yy, zz = await c.gather([x, y, z]) assert (xx, yy, zz) == (1, 2, 3) @pytest.mark.skip @gen_cluster(client=True) async def test_gather_robust_to_nested_missing_data(c, s, a, b): a.validate = False b.validate = False w = c.submit(inc, 1) x = c.submit(inc, w) y = c.submit(inc, x) z = c.submit(inc, y) await wait([z]) for worker in [a, b]: for datum in [y, z]: if datum.key in worker.data: del worker.data[datum.key] await asyncio.sleep(0) worker.release_key(datum.key) result = await c.gather([z]) assert result == [inc(inc(inc(inc(1))))] @gen_cluster(client=True) async def test_tokenize_on_futures(c, s, a, b): x = c.submit(inc, 1) y = c.submit(inc, 1) tok = tokenize(x) assert tokenize(x) == tokenize(x) assert tokenize(x) == tokenize(y) c.futures[x.key].finish() assert tok == tokenize(y) @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_restrictions_submit(c, s, a, b): x = c.submit(inc, 1, workers={a.ip}) y = c.submit(inc, x, workers={b.ip}) await wait([x, y]) assert s.host_restrictions[x.key] == {a.ip} assert x.key in a.data assert s.host_restrictions[y.key] == {b.ip} assert y.key in b.data @gen_cluster(client=True) async def test_restrictions_ip_port(c, s, a, b): x = c.submit(inc, 1, workers={a.address}) y = c.submit(inc, x, workers={b.address}) await wait([x, y]) assert s.worker_restrictions[x.key] == {a.address} assert x.key in a.data assert s.worker_restrictions[y.key] == {b.address} assert y.key in b.data @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_restrictions_map(c, s, a, b): L = c.map(inc, range(5), workers={a.ip}) await wait(L) assert set(a.data) == {x.key for x in L} assert not b.data for x in L: assert s.host_restrictions[x.key] == {a.ip} @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_restrictions_get(c, s, a, b): dsk = {"x": 1, "y": (inc, "x"), "z": (inc, "y")} futures = c.get(dsk, ["y", "z"], workers=a.ip, sync=False) result = await c.gather(futures) assert result == [2, 3] assert "y" in a.data assert "z" in a.data assert len(b.data) == 0 @gen_cluster(client=True) async def test_restrictions_get_annotate(c, s, a, b): x = 1 with dask.annotate(workers=a.address): y = delayed(inc)(x) with dask.annotate(workers=b.address): z = delayed(inc)(y) futures = c.get(z.__dask_graph__(), [y.key, z.key], sync=False) result = await c.gather(futures) assert result == [2, 3] assert y.key in a.data assert z.key in b.data @gen_cluster(client=True) async def dont_test_bad_restrictions_raise_exception(c, s, a, b): z = c.submit(inc, 2, workers={"bad-address"}) try: await z assert False except ValueError as e: assert "bad-address" in str(e) assert z.key in str(e) @gen_cluster(client=True) async def test_remove_worker(c, s, a, b): L = c.map(inc, range(20)) await wait(L) await b.close() assert b.address not in s.workers result = await c.gather(L) assert result == list(map(inc, range(20))) @gen_cluster(nthreads=[("127.0.0.1", 1)], client=True) async def test_errors_dont_block(c, s, w): L = [c.submit(inc, 1), c.submit(throws, 1), c.submit(inc, 2), c.submit(throws, 2)] while not (L[0].status == L[2].status == "finished"): await asyncio.sleep(0.01) result = await c.gather([L[0], L[2]]) assert result == [2, 3] @gen_cluster(client=True) async def test_submit_quotes(c, s, a, b): def assert_list(x, z=[]): return isinstance(x, list) and isinstance(z, list) x = c.submit(assert_list, [1, 2, 3]) result = await x assert result x = c.submit(assert_list, [1, 2, 3], z=[4, 5, 6]) result = await x assert result x = c.submit(inc, 1) y = c.submit(inc, 2) z = c.submit(assert_list, [x, y]) result = await z assert result @gen_cluster(client=True) async def test_map_quotes(c, s, a, b): def assert_list(x, z=[]): return isinstance(x, list) and isinstance(z, list) L = c.map(assert_list, [[1, 2, 3], [4]]) result = await c.gather(L) assert all(result) L = c.map(assert_list, [[1, 2, 3], [4]], z=[10]) result = await c.gather(L) assert all(result) L = c.map(assert_list, [[1, 2, 3], [4]], [[]] * 3) result = await c.gather(L) assert all(result) @gen_cluster() async def test_two_consecutive_clients_share_results(s, a, b): c = await Client(s.address, asynchronous=True) x = c.submit(random.randint, 0, 1000, pure=True) xx = await x f = await Client(s.address, asynchronous=True) y = f.submit(random.randint, 0, 1000, pure=True) yy = await y assert xx == yy await c.close() await f.close() @gen_cluster(client=True) async def test_submit_then_get_with_Future(c, s, a, b): x = c.submit(slowinc, 1) dsk = {"y": (inc, x)} result = await c.get(dsk, "y", sync=False) assert result == 3 @gen_cluster(client=True) async def test_aliases(c, s, a, b): x = c.submit(inc, 1) dsk = {"y": x} result = await c.get(dsk, "y", sync=False) assert result == 2 @gen_cluster(client=True) async def test_aliases_2(c, s, a, b): dsk_keys = [ ({"x": (inc, 1), "y": "x", "z": "x", "w": (add, "y", "z")}, ["y", "w"]), ({"x": "y", "y": 1}, ["x"]), ({"x": 1, "y": "x", "z": "y", "w": (inc, "z")}, ["w"]), ] for dsk, keys in dsk_keys: result = await c.gather(c.get(dsk, keys, sync=False)) assert list(result) == list(dask.get(dsk, keys)) await asyncio.sleep(0) @gen_cluster(client=True) async def test_scatter(c, s, a, b): d = await c.scatter({"y": 20}) assert isinstance(d["y"], Future) assert a.data.get("y") == 20 or b.data.get("y") == 20 y_who_has = s.get_who_has(keys=["y"])["y"] assert a.address in y_who_has or b.address in y_who_has assert s.get_nbytes(summary=False) == {"y": sizeof(20)} yy = await c.gather([d["y"]]) assert yy == [20] [x] = await c.scatter([10]) assert isinstance(x, Future) assert a.data.get(x.key) == 10 or b.data.get(x.key) == 10 xx = await c.gather([x]) x_who_has = s.get_who_has(keys=[x.key])[x.key] assert s.tasks[x.key].who_has assert ( s.workers[a.address] in s.tasks[x.key].who_has or s.workers[b.address] in s.tasks[x.key].who_has ) assert s.get_nbytes(summary=False) == {"y": sizeof(20), x.key: sizeof(10)} assert xx == [10] z = c.submit(add, x, d["y"]) # submit works on Future result = await z assert result == 10 + 20 result = await c.gather([z, x]) assert result == [30, 10] @gen_cluster(client=True) async def test_scatter_types(c, s, a, b): d = await c.scatter({"x": 1}) assert isinstance(d, dict) assert list(d) == ["x"] for seq in [[1], (1,), {1}, frozenset([1])]: L = await c.scatter(seq) assert isinstance(L, type(seq)) assert len(L) == 1 s.validate_state() seq = await c.scatter(range(5)) assert isinstance(seq, list) assert len(seq) == 5 s.validate_state() @gen_cluster(client=True) async def test_scatter_non_list(c, s, a, b): x = await c.scatter(1) assert isinstance(x, Future) result = await x assert result == 1 @gen_cluster(client=True) async def test_scatter_tokenize_local(c, s, a, b): from dask.base import normalize_token class MyObj: pass L = [] @normalize_token.register(MyObj) def f(x): L.append(x) return "x" obj = MyObj() future = await c.scatter(obj) assert L and L[0] is obj @gen_cluster(client=True) async def test_scatter_singletons(c, s, a, b): np = pytest.importorskip("numpy") pd = pytest.importorskip("pandas") for x in [1, np.ones(5), pd.DataFrame({"x": [1, 2, 3]})]: future = await c.scatter(x) result = await future assert str(result) == str(x) @gen_cluster(client=True) async def test_scatter_typename(c, s, a, b): future = await c.scatter(123) assert future.key.startswith("int") @gen_cluster(client=True) async def test_scatter_hash(c, s, a, b): x = await c.scatter(123) y = await c.scatter(123) assert x.key == y.key z = await c.scatter(123, hash=False) assert z.key != y.key @gen_cluster(client=True) async def test_scatter_hash_2(c, s, a, b): [a] = await c.scatter([1]) [b] = await c.scatter([1]) assert a.key == b.key s.validate_state() @gen_cluster(client=True) async def test_get_releases_data(c, s, a, b): await c.gather(c.get({"x": (inc, 1)}, ["x"], sync=False)) import gc gc.collect() while c.refcount["x"]: await asyncio.sleep(0.01) def test_current(s, a, b): with Client(s["address"]) as c: assert Client.current() is c with pytest.raises(ValueError): Client.current() with Client(s["address"]) as c: assert Client.current() is c def test_global_clients(loop): assert _get_global_client() is None with pytest.raises(ValueError): default_client() with cluster() as (s, [a, b]): with Client(s["address"], loop=loop) as c: assert _get_global_client() is c assert default_client() is c with Client(s["address"], loop=loop) as f: assert _get_global_client() is f assert default_client() is f assert default_client(c) is c assert default_client(f) is f assert _get_global_client() is None @gen_cluster(client=True) async def test_exception_on_exception(c, s, a, b): x = c.submit(lambda: 1 / 0) y = c.submit(inc, x) with pytest.raises(ZeroDivisionError): await y z = c.submit(inc, y) with pytest.raises(ZeroDivisionError): await z @gen_cluster(client=True) async def test_get_nbytes(c, s, a, b): [x] = await c.scatter([1]) assert s.get_nbytes(summary=False) == {x.key: sizeof(1)} y = c.submit(inc, x) await y assert s.get_nbytes(summary=False) == {x.key: sizeof(1), y.key: sizeof(2)} @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_nbytes_determines_worker(c, s, a, b): x = c.submit(identity, 1, workers=[a.ip]) y = c.submit(identity, tuple(range(100)), workers=[b.ip]) await c.gather([x, y]) z = c.submit(lambda x, y: None, x, y) await z assert s.tasks[z.key].who_has == {s.workers[b.address]} @gen_cluster(client=True) async def test_if_intermediates_clear_on_error(c, s, a, b): x = delayed(div, pure=True)(1, 0) y = delayed(div, pure=True)(1, 2) z = delayed(add, pure=True)(x, y) f = c.compute(z) with pytest.raises(ZeroDivisionError): await f s.validate_state() assert not any(ts.who_has for ts in s.tasks.values()) @gen_cluster( client=True, config={"distributed.scheduler.default-task-durations": {"f": "1ms"}} ) async def test_pragmatic_move_small_data_to_large_data(c, s, a, b): np = pytest.importorskip("numpy") lists = c.map(np.ones, [10000] * 10, pure=False) sums = c.map(np.sum, lists) total = c.submit(sum, sums) def f(x, y): return None results = c.map(f, lists, [total] * 10) await wait([total]) await wait(results) assert ( sum( s.tasks[r.key].who_has.issubset(s.tasks[l.key].who_has) for l, r in zip(lists, results) ) >= 9 ) @gen_cluster(client=True) async def test_get_with_non_list_key(c, s, a, b): dsk = {("x", 0): (inc, 1), 5: (inc, 2)} x = await c.get(dsk, ("x", 0), sync=False) y = await c.get(dsk, 5, sync=False) assert x == 2 assert y == 3 @gen_cluster(client=True) async def test_get_with_error(c, s, a, b): dsk = {"x": (div, 1, 0), "y": (inc, "x")} with pytest.raises(ZeroDivisionError): await c.get(dsk, "y", sync=False) def test_get_with_error_sync(c): dsk = {"x": (div, 1, 0), "y": (inc, "x")} with pytest.raises(ZeroDivisionError): c.get(dsk, "y") @gen_cluster(client=True) async def test_directed_scatter(c, s, a, b): await c.scatter([1, 2, 3], workers=[a.address]) assert len(a.data) == 3 assert not b.data await c.scatter([4, 5], workers=[b.name]) assert len(b.data) == 2 def test_directed_scatter_sync(c, s, a, b, loop): futures = c.scatter([1, 2, 3], workers=[b["address"]]) has_what = sync(loop, c.scheduler.has_what) assert len(has_what[b["address"]]) == len(futures) assert len(has_what[a["address"]]) == 0 @gen_cluster(client=True) async def test_scatter_direct(c, s, a, b): future = await c.scatter(123, direct=True) assert future.key in a.data or future.key in b.data assert s.tasks[future.key].who_has assert future.status == "finished" result = await future assert result == 123 assert not s.counters["op"].components[0]["scatter"] result = await future assert not s.counters["op"].components[0]["gather"] result = await c.gather(future) assert not s.counters["op"].components[0]["gather"] @gen_cluster() async def test_scatter_direct_2(s, a, b): c = await Client(s.address, asynchronous=True, heartbeat_interval=10) last = s.clients[c.id].last_seen while s.clients[c.id].last_seen == last: await asyncio.sleep(0.10) await c.close() @gen_cluster(client=True) async def test_scatter_direct_numpy(c, s, a, b): np = pytest.importorskip("numpy") x = np.ones(5) future = await c.scatter(x, direct=True) result = await future assert np.allclose(x, result) assert not s.counters["op"].components[0]["scatter"] @gen_cluster(client=True) async def test_scatter_direct_broadcast(c, s, a, b): future2 = await c.scatter(456, direct=True, broadcast=True) assert future2.key in a.data assert future2.key in b.data assert s.tasks[future2.key].who_has == {s.workers[a.address], s.workers[b.address]} result = await future2 assert result == 456 assert not s.counters["op"].components[0]["scatter"] @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_scatter_direct_balanced(c, s, *workers): futures = await c.scatter([1, 2, 3], direct=True) assert sorted(len(w.data) for w in workers) == [0, 1, 1, 1] @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_scatter_direct_broadcast_target(c, s, *workers): futures = await c.scatter([123, 456], direct=True, workers=workers[0].address) assert futures[0].key in workers[0].data assert futures[1].key in workers[0].data futures = await c.scatter( [123, 456], direct=True, broadcast=True, workers=[w.address for w in workers[:3]], ) assert ( f.key in w.data and w.address in s.tasks[f.key].who_has for f in futures for w in workers[:3] ) @gen_cluster(client=True, nthreads=[]) async def test_scatter_direct_empty(c, s): with pytest.raises((ValueError, TimeoutError)): await c.scatter(123, direct=True, timeout=0.1) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 5) async def test_scatter_direct_spread_evenly(c, s, *workers): futures = [] for i in range(10): future = await c.scatter(i, direct=True) futures.append(future) assert all(w.data for w in workers) @pytest.mark.parametrize("direct", [True, False]) @pytest.mark.parametrize("broadcast", [True, False]) def test_scatter_gather_sync(c, direct, broadcast): futures = c.scatter([1, 2, 3], direct=direct, broadcast=broadcast) results = c.gather(futures, direct=direct) assert results == [1, 2, 3] delayed(inc)(1).compute(direct=direct) @gen_cluster(client=True) async def test_gather_direct(c, s, a, b): futures = await c.scatter([1, 2, 3]) data = await c.gather(futures, direct=True) assert data == [1, 2, 3] @gen_cluster(client=True) async def test_many_submits_spread_evenly(c, s, a, b): L = [c.submit(inc, i) for i in range(10)] await wait(L) assert a.data and b.data @gen_cluster(client=True) async def test_traceback(c, s, a, b): x = c.submit(div, 1, 0) tb = await x.traceback() assert any("x / y" in line for line in pluck(3, traceback.extract_tb(tb))) @gen_cluster(client=True) async def test_get_traceback(c, s, a, b): try: await c.get({"x": (div, 1, 0)}, "x", sync=False) except ZeroDivisionError: exc_type, exc_value, exc_traceback = sys.exc_info() L = traceback.format_tb(exc_traceback) assert any("x / y" in line for line in L) @gen_cluster(client=True) async def test_gather_traceback(c, s, a, b): x = c.submit(div, 1, 0) try: await c.gather(x) except ZeroDivisionError: exc_type, exc_value, exc_traceback = sys.exc_info() L = traceback.format_tb(exc_traceback) assert any("x / y" in line for line in L) def test_traceback_sync(c): x = c.submit(div, 1, 0) tb = x.traceback() assert any( "x / y" in line for line in concat(traceback.extract_tb(tb)) if isinstance(line, str) ) y = c.submit(inc, x) tb2 = y.traceback() assert set(pluck(3, traceback.extract_tb(tb2))).issuperset( set(pluck(3, traceback.extract_tb(tb))) ) z = c.submit(div, 1, 2) tb = z.traceback() assert tb is None @gen_cluster(client=True) async def test_upload_file(c, s, a, b): def g(): import myfile return myfile.f() with save_sys_modules(): for value in [123, 456]: with tmp_text("myfile.py", f"def f():\n return {value}") as fn: await c.upload_file(fn) x = c.submit(g, pure=False) result = await x assert result == value @gen_cluster(client=True) async def test_upload_file_refresh_delayed(c, s, a, b): with save_sys_modules(): for value in [123, 456]: with tmp_text("myfile.py", f"def f():\n return {value}") as fn: await c.upload_file(fn) sys.path.append(os.path.dirname(fn)) from myfile import f b = delayed(f)() bb = c.compute(b, sync=False) result = await c.gather(bb) assert result == value @gen_cluster(client=True) async def test_upload_file_no_extension(c, s, a, b): with tmp_text("myfile", "") as fn: await c.upload_file(fn) @gen_cluster(client=True) async def test_upload_file_zip(c, s, a, b): def g(): import myfile return myfile.f() with save_sys_modules(): try: for value in [123, 456]: with tmp_text( "myfile.py", f"def f():\n return {value}" ) as fn_my_file: with zipfile.ZipFile("myfile.zip", "w") as z: z.write(fn_my_file, arcname=os.path.basename(fn_my_file)) await c.upload_file("myfile.zip") x = c.submit(g, pure=False) result = await x assert result == value finally: if os.path.exists("myfile.zip"): os.remove("myfile.zip") @gen_cluster(client=True) async def test_upload_file_egg(c, s, a, b): def g(): import package_1 import package_2 return package_1.a, package_2.b # c.upload_file tells each worker to # - put this file in their local_directory # - modify their sys.path to include it # we don't care about the local_directory # but we do care about restoring the path with save_sys_modules(): for value in [123, 456]: with tmpfile() as dirname: os.mkdir(dirname) with open(os.path.join(dirname, "setup.py"), "w") as f: f.write("from setuptools import setup, find_packages\n") f.write( 'setup(name="my_package", packages=find_packages(), version="{}")\n'.format( value ) ) # test a package with an underscore in the name package_1 = os.path.join(dirname, "package_1") os.mkdir(package_1) with open(os.path.join(package_1, "__init__.py"), "w") as f: f.write(f"a = {value}\n") # test multiple top-level packages package_2 = os.path.join(dirname, "package_2") os.mkdir(package_2) with open(os.path.join(package_2, "__init__.py"), "w") as f: f.write(f"b = {value}\n") # compile these into an egg subprocess.check_call( [sys.executable, "setup.py", "bdist_egg"], cwd=dirname ) egg_root = os.path.join(dirname, "dist") # first file ending with '.egg' egg_name = [ fname for fname in os.listdir(egg_root) if fname.endswith(".egg") ][0] egg_path = os.path.join(egg_root, egg_name) await c.upload_file(egg_path) os.remove(egg_path) x = c.submit(g, pure=False) result = await x assert result == (value, value) @gen_cluster(client=True) async def test_upload_large_file(c, s, a, b): assert a.local_directory assert b.local_directory with tmp_text("myfile", "abc") as fn: with tmp_text("myfile2", "def") as fn2: await c._upload_large_file(fn, remote_filename="x") await c._upload_large_file(fn2) for w in [a, b]: assert os.path.exists(os.path.join(w.local_directory, "x")) assert os.path.exists(os.path.join(w.local_directory, "myfile2")) with open(os.path.join(w.local_directory, "x")) as f: assert f.read() == "abc" with open(os.path.join(w.local_directory, "myfile2")) as f: assert f.read() == "def" def test_upload_file_sync(c): def g(): import myfile return myfile.x with tmp_text("myfile.py", "x = 123") as fn: c.upload_file(fn) x = c.submit(g) assert x.result() == 123 @gen_cluster(client=True) async def test_upload_file_exception(c, s, a, b): with tmp_text("myfile.py", "syntax-error!") as fn: with pytest.raises(SyntaxError): await c.upload_file(fn) def test_upload_file_exception_sync(c): with tmp_text("myfile.py", "syntax-error!") as fn: with pytest.raises(SyntaxError): c.upload_file(fn) @gen_cluster(client=True, nthreads=[]) async def test_upload_file_new_worker(c, s): def g(): import myfile return myfile.x with tmp_text("myfile.py", "x = 123") as fn: await c.upload_file(fn) async with Worker(s.address): x = await c.submit(g) assert x == 123 @pytest.mark.skip @gen_cluster() async def test_multiple_clients(s, a, b): a = await Client(s.address, asynchronous=True) b = await Client(s.address, asynchronous=True) x = a.submit(inc, 1) y = b.submit(inc, 2) assert x.client is a assert y.client is b xx = await x yy = await y assert xx == 2 assert yy == 3 z = a.submit(add, x, y) assert z.client is a zz = await z assert zz == 5 await a.close() await b.close() @gen_cluster(client=True) async def test_async_compute(c, s, a, b): from dask.delayed import delayed x = delayed(1) y = delayed(inc)(x) z = delayed(dec)(x) [yy, zz, aa] = c.compute([y, z, 3], sync=False) assert isinstance(yy, Future) assert isinstance(zz, Future) assert aa == 3 result = await c.gather([yy, zz]) assert result == [2, 0] assert isinstance(c.compute(y), Future) assert isinstance(c.compute([y]), (tuple, list)) @gen_cluster(client=True) async def test_async_compute_with_scatter(c, s, a, b): d = await c.scatter({("x", 1): 1, ("y", 1): 2}) x, y = d[("x", 1)], d[("y", 1)] from dask.delayed import delayed z = delayed(add)(delayed(inc)(x), delayed(inc)(y)) zz = c.compute(z) [result] = await c.gather([zz]) assert result == 2 + 3 def test_sync_compute(c): x = delayed(1) y = delayed(inc)(x) z = delayed(dec)(x) yy, zz = c.compute([y, z], sync=True) assert (yy, zz) == (2, 0) @gen_cluster(client=True) async def test_remote_scatter_gather(c, s, a, b): x, y, z = await c.scatter([1, 2, 3]) assert x.key in a.data or x.key in b.data assert y.key in a.data or y.key in b.data assert z.key in a.data or z.key in b.data xx, yy, zz = await c.gather([x, y, z]) assert (xx, yy, zz) == (1, 2, 3) @gen_cluster(client=True) async def test_remote_submit_on_Future(c, s, a, b): x = c.submit(lambda x: x + 1, 1) y = c.submit(lambda x: x + 1, x) result = await y assert result == 3 def test_start_is_idempotent(c): c.start() c.start() c.start() x = c.submit(inc, 1) assert x.result() == 2 @gen_cluster(client=True) async def test_client_with_scheduler(c, s, a, b): assert s.nthreads == {a.address: a.nthreads, b.address: b.nthreads} x = c.submit(inc, 1) y = c.submit(inc, 2) z = c.submit(add, x, y) result = await x assert result == 1 + 1 result = await z assert result == 1 + 1 + 1 + 2 A, B, C = await c.scatter([1, 2, 3]) AA, BB, xx = await c.gather([A, B, x]) assert (AA, BB, xx) == (1, 2, 2) result = await c.get({"x": (inc, 1), "y": (add, "x", 10)}, "y", sync=False) assert result == 12 @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_allow_restrictions(c, s, a, b): aws = s.workers[a.address] bws = s.workers[a.address] x = c.submit(inc, 1, workers=a.ip) await x assert s.tasks[x.key].who_has == {aws} assert not s.loose_restrictions x = c.submit(inc, 2, workers=a.ip, allow_other_workers=True) await x assert s.tasks[x.key].who_has == {aws} assert x.key in s.loose_restrictions L = c.map(inc, range(3, 13), workers=a.ip, allow_other_workers=True) await wait(L) assert all(s.tasks[f.key].who_has == {aws} for f in L) assert {f.key for f in L}.issubset(s.loose_restrictions) x = c.submit(inc, 15, workers="127.0.0.3", allow_other_workers=True) await x assert s.tasks[x.key].who_has assert x.key in s.loose_restrictions L = c.map(inc, range(15, 25), workers="127.0.0.3", allow_other_workers=True) await wait(L) assert all(s.tasks[f.key].who_has for f in L) assert {f.key for f in L}.issubset(s.loose_restrictions) with pytest.raises(ValueError): c.submit(inc, 1, allow_other_workers=True) with pytest.raises(ValueError): c.map(inc, [1], allow_other_workers=True) with pytest.raises(TypeError): c.submit(inc, 20, workers="127.0.0.1", allow_other_workers="Hello!") with pytest.raises(TypeError): c.map(inc, [20], workers="127.0.0.1", allow_other_workers="Hello!") def test_bad_address(): with pytest.raises(OSError, match="connect"): Client("123.123.123.123:1234", timeout=0.1) with pytest.raises(OSError, match="connect"): Client("127.0.0.1:1234", timeout=0.1) def test_informative_error_on_cluster_type(): with pytest.raises(TypeError) as exc_info: Client(LocalCluster) assert "Scheduler address must be a string or a Cluster instance" in str( exc_info.value ) @gen_cluster(client=True) async def test_long_error(c, s, a, b): def bad(x): raise ValueError("a" * 100000) x = c.submit(bad, 10) try: await x except ValueError as e: assert len(str(e)) < 100000 tb = await x.traceback() assert all( len(line) < 100000 for line in concat(traceback.extract_tb(tb)) if isinstance(line, str) ) @gen_cluster(client=True) async def test_map_on_futures_with_kwargs(c, s, a, b): def f(x, y=10): return x + y futures = c.map(inc, range(10)) futures2 = c.map(f, futures, y=20) results = await c.gather(futures2) assert results == [i + 1 + 20 for i in range(10)] future = c.submit(inc, 100) future2 = c.submit(f, future, y=200) result = await future2 assert result == 100 + 1 + 200 class BadlySerializedObject: def __getstate__(self): return 1 def __setstate__(self, state): raise TypeError("hello!") class FatallySerializedObject: def __getstate__(self): return 1 def __setstate__(self, state): print("This should never have been deserialized, closing") import sys sys.exit(0) @gen_cluster(client=True) async def test_badly_serialized_input(c, s, a, b): o = BadlySerializedObject() future = c.submit(inc, o) futures = c.map(inc, range(10)) L = await c.gather(futures) assert list(L) == list(map(inc, range(10))) assert future.status == "error" with pytest.raises(Exception) as info: await future assert "hello!" in str(info.value) @pytest.mark.skip @gen_test() async def test_badly_serialized_input_stderr(capsys, c): o = BadlySerializedObject() future = c.submit(inc, o) while True: sleep(0.01) out, err = capsys.readouterr() if "hello!" in err: break assert future.status == "error" def test_repr(loop): funcs = [str, repr, lambda x: x._repr_html_()] with cluster(nworkers=3, worker_kwargs={"memory_limit": "2 GiB"}) as (s, [a, b, c]): with Client(s["address"], loop=loop) as c: for func in funcs: text = func(c) assert c.scheduler.address in text assert "threads=3" in text or "Total threads: </strong>" in text assert "6.00 GiB" in text if "<table" not in text: assert len(text) < 80 for func in funcs: text = func(c) assert "No scheduler connected" in text @gen_cluster(client=True) async def test_repr_async(c, s, a, b): c._repr_html_() @gen_cluster(client=True, worker_kwargs={"memory_limit": None}) async def test_repr_no_memory_limit(c, s, a, b): c._repr_html_() @gen_test() async def test_repr_localcluster(): cluster = await LocalCluster( processes=False, dashboard_address=":0", asynchronous=True ) client = await Client(cluster, asynchronous=True) try: text = client._repr_html_() assert cluster.scheduler.address in text assert is_valid_xml(client._repr_html_()) finally: await client.close() await cluster.close() @gen_cluster(client=True) async def test_forget_simple(c, s, a, b): x = c.submit(inc, 1, retries=2) y = c.submit(inc, 2) z = c.submit(add, x, y, workers=[a.ip], allow_other_workers=True) await wait([x, y, z]) assert not s.waiting_data.get(x.key) assert not s.waiting_data.get(y.key) assert set(s.tasks) == {x.key, y.key, z.key} s.client_releases_keys(keys=[x.key], client=c.id) assert x.key in s.tasks s.client_releases_keys(keys=[z.key], client=c.id) assert x.key not in s.tasks assert z.key not in s.tasks assert not s.tasks[y.key].dependents s.client_releases_keys(keys=[y.key], client=c.id) assert not s.tasks @gen_cluster(client=True) async def test_forget_complex(e, s, A, B): a, b, c, d = await e.scatter(list(range(4))) ab = e.submit(add, a, b) cd = e.submit(add, c, d) ac = e.submit(add, a, c) acab = e.submit(add, ac, ab) await wait([a, b, c, d, ab, ac, cd, acab]) assert set(s.tasks) == {f.key for f in [ab, ac, cd, acab, a, b, c, d]} s.client_releases_keys(keys=[ab.key], client=e.id) assert set(s.tasks) == {f.key for f in [ab, ac, cd, acab, a, b, c, d]} s.client_releases_keys(keys=[b.key], client=e.id) assert set(s.tasks) == {f.key for f in [ac, cd, acab, a, c, d]} s.client_releases_keys(keys=[acab.key], client=e.id) assert set(s.tasks) == {f.key for f in [ac, cd, a, c, d]} assert b.key not in s.tasks while b.key in A.data or b.key in B.data: await asyncio.sleep(0.01) s.client_releases_keys(keys=[ac.key], client=e.id) assert set(s.tasks) == {f.key for f in [cd, a, c, d]} @gen_cluster(client=True) async def test_forget_in_flight(e, s, A, B): delayed2 = partial(delayed, pure=True) a, b, c, d = (delayed2(slowinc)(i) for i in range(4)) ab = delayed2(slowadd)(a, b, dask_key_name="ab") cd = delayed2(slowadd)(c, d, dask_key_name="cd") ac = delayed2(slowadd)(a, c, dask_key_name="ac") acab = delayed2(slowadd)(ac, ab, dask_key_name="acab") x, y = e.compute([ac, acab]) s.validate_state() for i in range(5): await asyncio.sleep(0.01) s.validate_state() s.client_releases_keys(keys=[y.key], client=e.id) s.validate_state() for k in [acab.key, ab.key, b.key]: assert k not in s.tasks @gen_cluster(client=True) async def test_forget_errors(c, s, a, b): x = c.submit(div, 1, 0) y = c.submit(inc, x) z = c.submit(inc, y) await wait([y]) assert x.key in s.exceptions assert x.key in s.exceptions_blame assert y.key in s.exceptions_blame assert z.key in s.exceptions_blame s.client_releases_keys(keys=[z.key], client=c.id) assert x.key in s.exceptions assert x.key in s.exceptions_blame assert y.key in s.exceptions_blame assert z.key not in s.exceptions_blame s.client_releases_keys(keys=[x.key], client=c.id) assert x.key in s.exceptions assert x.key in s.exceptions_blame assert y.key in s.exceptions_blame assert z.key not in s.exceptions_blame s.client_releases_keys(keys=[y.key], client=c.id) assert x.key not in s.exceptions assert x.key not in s.exceptions_blame assert y.key not in s.exceptions_blame assert z.key not in s.exceptions_blame def test_repr_sync(c): s = str(c) r = repr(c) assert c.scheduler.address in s assert c.scheduler.address in r assert str(2) in s # nworkers assert "cores" in s or "threads" in s @gen_cluster(client=True) async def test_waiting_data(c, s, a, b): x = c.submit(inc, 1) y = c.submit(inc, 2) z = c.submit(add, x, y, workers=[a.ip], allow_other_workers=True) await wait([x, y, z]) assert not s.waiting_data.get(x.key) assert not s.waiting_data.get(y.key) @gen_cluster() async def test_multi_client(s, a, b): c = await Client(s.address, asynchronous=True) f = await Client(s.address, asynchronous=True) assert set(s.client_comms) == {c.id, f.id} x = c.submit(inc, 1) y = f.submit(inc, 2) y2 = c.submit(inc, 2) assert y.key == y2.key await wait([x, y]) assert s.wants_what == { c.id: {x.key, y.key}, f.id: {y.key}, "fire-and-forget": set(), } assert s.who_wants == {x.key: {c.id}, y.key: {c.id, f.id}} await c.close() while c.id in s.wants_what: await asyncio.sleep(0.01) assert c.id not in s.wants_what assert c.id not in s.who_wants[y.key] assert x.key not in s.who_wants await f.close() while s.tasks: await asyncio.sleep(0.01) def long_running_client_connection(address): with pristine_loop(): c = Client(address) x = c.submit(lambda x: x + 1, 10) x.result() sleep(100) @gen_cluster() async def test_cleanup_after_broken_client_connection(s, a, b): proc = mp_context.Process(target=long_running_client_connection, args=(s.address,)) proc.daemon = True proc.start() while not s.tasks: await asyncio.sleep(0.01) proc.terminate() while s.tasks: await asyncio.sleep(0.01) @gen_cluster() async def test_multi_garbage_collection(s, a, b): c = await Client(s.address, asynchronous=True) f = await Client(s.address, asynchronous=True) x = c.submit(inc, 1) y = f.submit(inc, 2) y2 = c.submit(inc, 2) assert y.key == y2.key await wait([x, y]) x.__del__() while x.key in a.data or x.key in b.data: await asyncio.sleep(0.01) assert s.wants_what == {c.id: {y.key}, f.id: {y.key}, "fire-and-forget": set()} assert s.who_wants == {y.key: {c.id, f.id}} y.__del__() while x.key in s.wants_what[f.id]: await asyncio.sleep(0.01) await asyncio.sleep(0.1) assert y.key in a.data or y.key in b.data assert s.wants_what == {c.id: {y.key}, f.id: set(), "fire-and-forget": set()} assert s.who_wants == {y.key: {c.id}} y2.__del__() while y.key in a.data or y.key in b.data: await asyncio.sleep(0.01) assert not any(v for v in s.wants_what.values()) assert not s.who_wants await c.close() await f.close() @gen_cluster(client=True) async def test__broadcast(c, s, a, b): x, y = await c.scatter([1, 2], broadcast=True) assert a.data == b.data == {x.key: 1, y.key: 2} @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test__broadcast_integer(c, s, *workers): x, y = await c.scatter([1, 2], broadcast=2) assert len(s.tasks[x.key].who_has) == 2 assert len(s.tasks[y.key].who_has) == 2 @gen_cluster(client=True) async def test__broadcast_dict(c, s, a, b): d = await c.scatter({"x": 1}, broadcast=True) assert a.data == b.data == {"x": 1} def test_broadcast(c, s, a, b): x, y = c.scatter([1, 2], broadcast=True) has_what = sync(c.loop, c.scheduler.has_what) assert {k: set(v) for k, v in has_what.items()} == { a["address"]: {x.key, y.key}, b["address"]: {x.key, y.key}, } [z] = c.scatter([3], broadcast=True, workers=[a["address"]]) has_what = sync(c.loop, c.scheduler.has_what) assert {k: set(v) for k, v in has_what.items()} == { a["address"]: {x.key, y.key, z.key}, b["address"]: {x.key, y.key}, } @gen_cluster(client=True) async def test_proxy(c, s, a, b): msg = await c.scheduler.proxy(msg={"op": "identity"}, worker=a.address) assert msg["id"] == a.identity()["id"] @gen_cluster(client=True) async def test_cancel(c, s, a, b): x = c.submit(slowinc, 1) y = c.submit(slowinc, x) while y.key not in s.tasks: await asyncio.sleep(0.01) await c.cancel([x]) assert x.cancelled() assert "cancel" in str(x) s.validate_state() while not y.cancelled(): await asyncio.sleep(0.01) assert not s.tasks s.validate_state() @gen_cluster(client=True) async def test_cancel_tuple_key(c, s, a, b): x = c.submit(inc, 1, key=("x", 0, 1)) await x await c.cancel(x) with pytest.raises(CancelledError): await x @gen_cluster() async def test_cancel_multi_client(s, a, b): c = await Client(s.address, asynchronous=True) f = await Client(s.address, asynchronous=True) x = c.submit(slowinc, 1) y = f.submit(slowinc, 1) assert x.key == y.key await c.cancel([x]) assert x.cancelled() assert not y.cancelled() while y.key not in s.tasks: await asyncio.sleep(0.01) out = await y assert out == 2 with pytest.raises(CancelledError): await x await c.close() await f.close() @gen_cluster(client=True) async def test_cancel_collection(c, s, a, b): L = c.map(double, [[1], [2], [3]]) x = db.Bag({("b", i): f for i, f in enumerate(L)}, "b", 3) await c.cancel(x) await c.cancel([x]) assert all(f.cancelled() for f in L) while s.tasks: await asyncio.sleep(0.01) def test_cancel_sync(c): x = c.submit(slowinc, 1, key="x") y = c.submit(slowinc, x, key="y") z = c.submit(slowinc, y, key="z") c.cancel([y]) start = time() while not z.cancelled(): sleep(0.01) assert time() < start + 30 assert x.result() == 2 z.cancel() assert z.cancelled() @gen_cluster(client=True) async def test_future_type(c, s, a, b): x = c.submit(inc, 1) await wait([x]) assert x.type == int assert "int" in str(x) @gen_cluster(client=True) async def test_traceback_clean(c, s, a, b): x = c.submit(div, 1, 0) try: await x except Exception as e: f = e exc_type, exc_value, tb = sys.exc_info() while tb: assert "scheduler" not in tb.tb_frame.f_code.co_filename assert "worker" not in tb.tb_frame.f_code.co_filename tb = tb.tb_next @gen_cluster(client=True) async def test_map_differnet_lengths(c, s, a, b): assert len(c.map(add, [1, 2], [1, 2, 3])) == 2 def test_Future_exception_sync_2(loop, capsys): with cluster() as (s, [a, b]): with Client(s["address"], loop=loop) as c: assert dask.base.get_scheduler() == c.get out, err = capsys.readouterr() assert len(out.strip().split("\n")) == 1 assert dask.base.get_scheduler() != c.get @gen_cluster(timeout=60, client=True) async def test_async_persist(c, s, a, b): from dask.delayed import Delayed, delayed x = delayed(1) y = delayed(inc)(x) z = delayed(dec)(x) w = delayed(add)(y, z) yy, ww = c.persist([y, w]) assert type(yy) == type(y) assert type(ww) == type(w) assert len(yy.dask) == 1 assert len(ww.dask) == 1 assert len(w.dask) > 1 assert y.__dask_keys__() == yy.__dask_keys__() assert w.__dask_keys__() == ww.__dask_keys__() while y.key not in s.tasks and w.key not in s.tasks: await asyncio.sleep(0.01) assert s.who_wants[y.key] == {c.id} assert s.who_wants[w.key] == {c.id} yyf, wwf = c.compute([yy, ww]) yyy, www = await c.gather([yyf, wwf]) assert yyy == inc(1) assert www == add(inc(1), dec(1)) assert isinstance(c.persist(y), Delayed) assert isinstance(c.persist([y]), (list, tuple)) @gen_cluster(client=True) async def test__persist(c, s, a, b): pytest.importorskip("dask.array") import dask.array as da x = da.ones((10, 10), chunks=(5, 10)) y = 2 * (x + 1) assert len(y.dask) == 6 yy = c.persist(y) assert len(y.dask) == 6 assert len(yy.dask) == 2 assert all(isinstance(v, Future) for v in yy.dask.values()) assert yy.__dask_keys__() == y.__dask_keys__() g, h = c.compute([y, yy]) gg, hh = await c.gather([g, h]) assert (gg == hh).all() def test_persist(c): pytest.importorskip("dask.array") import dask.array as da x = da.ones((10, 10), chunks=(5, 10)) y = 2 * (x + 1) assert len(y.dask) == 6 yy = c.persist(y) assert len(y.dask) == 6 assert len(yy.dask) == 2 assert all(isinstance(v, Future) for v in yy.dask.values()) assert yy.__dask_keys__() == y.__dask_keys__() zz = yy.compute() z = y.compute() assert (zz == z).all() @gen_cluster(timeout=60, client=True) async def test_long_traceback(c, s, a, b): from distributed.protocol.pickle import dumps def deep(n): if n == 0: 1 / 0 else: return deep(n - 1) x = c.submit(deep, 200) await wait([x]) assert len(dumps(c.futures[x.key].traceback)) < 10000 assert isinstance(c.futures[x.key].exception, ZeroDivisionError) @gen_cluster(client=True) async def test_wait_on_collections(c, s, a, b): L = c.map(double, [[1], [2], [3]]) x = db.Bag({("b", i): f for i, f in enumerate(L)}, "b", 3) await wait(x) assert all(f.key in a.data or f.key in b.data for f in L) @gen_cluster(client=True) async def test_futures_of_get(c, s, a, b): x, y, z = c.map(inc, [1, 2, 3]) assert set(futures_of(0)) == set() assert set(futures_of(x)) == {x} assert set(futures_of([x, y, z])) == {x, y, z} assert set(futures_of([x, [y], [[z]]])) == {x, y, z} assert set(futures_of({"x": x, "y": [y]})) == {x, y} b = db.Bag({("b", i): f for i, f in enumerate([x, y, z])}, "b", 3) assert set(futures_of(b)) == {x, y, z} sg = SubgraphCallable( {"x": x, "y": y, "z": z, "out": (add, (add, (add, x, y), z), "in")}, "out", ("in",), ) assert set(futures_of(sg)) == {x, y, z} def test_futures_of_class(): da = pytest.importorskip("dask.array") assert futures_of([da.Array]) == [] @gen_cluster(client=True) async def test_futures_of_cancelled_raises(c, s, a, b): x = c.submit(inc, 1) await c.cancel([x]) with pytest.raises(CancelledError): await x with pytest.raises(CancelledError): await c.get({"x": (inc, x), "y": (inc, 2)}, ["x", "y"], sync=False) with pytest.raises(CancelledError): c.submit(inc, x) with pytest.raises(CancelledError): c.submit(add, 1, y=x) with pytest.raises(CancelledError): c.map(add, [1], y=x) assert "y" not in s.tasks @pytest.mark.skip @gen_cluster(nthreads=[("127.0.0.1", 1)], client=True) async def test_dont_delete_recomputed_results(c, s, w): x = c.submit(inc, 1) # compute first time await wait([x]) x.__del__() # trigger garbage collection await asyncio.sleep(0) xx = c.submit(inc, 1) # compute second time start = time() while xx.key not in w.data: # data shows up await asyncio.sleep(0.01) assert time() < start + 1 while time() < start + (s.delete_interval + 100) / 1000: # and stays assert xx.key in w.data await asyncio.sleep(0.01) @gen_cluster(nthreads=[], client=True) async def test_fatally_serialized_input(c, s): o = FatallySerializedObject() future = c.submit(inc, o) while not s.tasks: await asyncio.sleep(0.01) @pytest.mark.skip(reason="Use fast random selection now") @gen_cluster(client=True) async def test_balance_tasks_by_stacks(c, s, a, b): x = c.submit(inc, 1) await wait(x) y = c.submit(inc, 2) await wait(y) assert len(a.data) == len(b.data) == 1 @gen_cluster(client=True) async def test_run(c, s, a, b): results = await c.run(inc, 1) assert results == {a.address: 2, b.address: 2} results = await c.run(inc, 1, workers=[a.address]) assert results == {a.address: 2} results = await c.run(inc, 1, workers=[]) assert results == {} @gen_cluster(client=True) async def test_run_handles_picklable_data(c, s, a, b): futures = c.map(inc, range(10)) await wait(futures) def func(): return {}, set(), [], (), 1, "hello", b"100" results = await c.run_on_scheduler(func) assert results == func() results = await c.run(func) assert results == {w.address: func() for w in [a, b]} def test_run_sync(c, s, a, b): def func(x, y=10): return x + y result = c.run(func, 1, y=2) assert result == {a["address"]: 3, b["address"]: 3} result = c.run(func, 1, y=2, workers=[a["address"]]) assert result == {a["address"]: 3} @gen_cluster(client=True) async def test_run_coroutine(c, s, a, b): results = await c.run(geninc, 1, delay=0.05) assert results == {a.address: 2, b.address: 2} results = await c.run(geninc, 1, delay=0.05, workers=[a.address]) assert results == {a.address: 2} results = await c.run(geninc, 1, workers=[]) assert results == {} with pytest.raises(RuntimeError, match="hello"): await c.run(throws, 1) results = await c.run(asyncinc, 2, delay=0.01) assert results == {a.address: 3, b.address: 3} def test_run_coroutine_sync(c, s, a, b): result = c.run(geninc, 2, delay=0.01) assert result == {a["address"]: 3, b["address"]: 3} result = c.run(geninc, 2, workers=[a["address"]]) assert result == {a["address"]: 3} t1 = time() result = c.run(geninc, 2, delay=10, wait=False) t2 = time() assert result is None assert t2 - t1 <= 1.0 @gen_cluster(client=True) async def test_run_coroutine_deprecated(c, s, a, b): async def foo(): return "bar" with pytest.warns(FutureWarning, match="Client.run "): results = await c.run_coroutine(foo) assert results == {a.address: "bar", b.address: "bar"} def test_run_exception(c): def raise_exception(exc_type, exc_msg): raise exc_type(exc_msg) for exc_type in [ValueError, RuntimeError]: with pytest.raises(exc_type, match="informative message"): c.run(raise_exception, exc_type, "informative message") def test_diagnostic_ui(loop): with cluster() as (s, [a, b]): a_addr = a["address"] b_addr = b["address"] with Client(s["address"], loop=loop) as c: d = c.nthreads() assert d == {a_addr: 1, b_addr: 1} d = c.nthreads([a_addr]) assert d == {a_addr: 1} d = c.nthreads(a_addr) assert d == {a_addr: 1} d = c.nthreads(a["address"]) assert d == {a_addr: 1} x = c.submit(inc, 1) y = c.submit(inc, 2) z = c.submit(inc, 3) wait([x, y, z]) d = c.who_has() assert set(d) == {x.key, y.key, z.key} assert all(w in [a_addr, b_addr] for v in d.values() for w in v) assert all(d.values()) d = c.who_has([x, y]) assert set(d) == {x.key, y.key} d = c.who_has(x) assert set(d) == {x.key} d = c.has_what() assert set(d) == {a_addr, b_addr} assert all(k in [x.key, y.key, z.key] for v in d.values() for k in v) d = c.has_what([a_addr]) assert set(d) == {a_addr} d = c.has_what(a_addr) assert set(d) == {a_addr} def test_diagnostic_nbytes_sync(c): incs = c.map(inc, [1, 2, 3]) doubles = c.map(double, [1, 2, 3]) wait(incs + doubles) assert c.nbytes(summary=False) == {k.key: sizeof(1) for k in incs + doubles} assert c.nbytes(summary=True) == {"inc": sizeof(1) * 3, "double": sizeof(1) * 3} @gen_cluster(client=True) async def test_diagnostic_nbytes(c, s, a, b): incs = c.map(inc, [1, 2, 3]) doubles = c.map(double, [1, 2, 3]) await wait(incs + doubles) assert s.get_nbytes(summary=False) == {k.key: sizeof(1) for k in incs + doubles} assert s.get_nbytes(summary=True) == {"inc": sizeof(1) * 3, "double": sizeof(1) * 3} @gen_cluster(client=True, nthreads=[]) async def test_worker_aliases(c, s): a = Worker(s.address, name="alice") b = Worker(s.address, name="bob") w = Worker(s.address, name=3) await asyncio.gather(a, b, w) L = c.map(inc, range(10), workers="alice") future = await c.scatter(123, workers=3) await wait(L) assert len(a.data) == 10 assert len(b.data) == 0 assert dict(w.data) == {future.key: 123} for i, alias in enumerate([3, [3], "alice"]): result = await c.submit(lambda x: x + 1, i, workers=alias) assert result == i + 1 await asyncio.gather(a.close(), b.close(), w.close()) def test_persist_get_sync(c): x, y = delayed(1), delayed(2) xx = delayed(add)(x, x) yy = delayed(add)(y, y) xxyy = delayed(add)(xx, yy) xxyy2 = c.persist(xxyy) xxyy3 = delayed(add)(xxyy2, 10) assert xxyy3.compute() == ((1 + 1) + (2 + 2)) + 10 @gen_cluster(client=True) async def test_persist_get(c, s, a, b): x, y = delayed(1), delayed(2) xx = delayed(add)(x, x) yy = delayed(add)(y, y) xxyy = delayed(add)(xx, yy) xxyy2 = c.persist(xxyy) xxyy3 = delayed(add)(xxyy2, 10) await asyncio.sleep(0.5) result = await c.gather(c.get(xxyy3.dask, xxyy3.__dask_keys__(), sync=False)) assert result[0] == ((1 + 1) + (2 + 2)) + 10 result = await c.compute(xxyy3) assert result == ((1 + 1) + (2 + 2)) + 10 result = await c.compute(xxyy3) assert result == ((1 + 1) + (2 + 2)) + 10 result = await c.compute(xxyy3) assert result == ((1 + 1) + (2 + 2)) + 10 @pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows") def test_client_num_fds(loop): with cluster() as (s, [a, b]): proc = psutil.Process() with Client(s["address"], loop=loop) as c: # first client to start loop before = proc.num_fds() # measure for i in range(4): with Client(s["address"], loop=loop): # start more clients pass start = time() while proc.num_fds() > before: sleep(0.01) assert time() < start + 10, (before, proc.num_fds()) @gen_cluster() async def test_startup_close_startup(s, a, b): c = await Client(s.address, asynchronous=True) await c.close() c = await Client(s.address, asynchronous=True) await c.close() def test_startup_close_startup_sync(loop): with cluster() as (s, [a, b]): with Client(s["address"], loop=loop) as c: sleep(0.1) with Client(s["address"]) as c: pass with Client(s["address"]) as c: pass sleep(0.1) with Client(s["address"]) as c: pass @gen_cluster(client=True) async def test_badly_serialized_exceptions(c, s, a, b): def f(): class BadlySerializedException(Exception): def __reduce__(self): raise TypeError() raise BadlySerializedException("hello world") x = c.submit(f) with pytest.raises(Exception, match="hello world"): await x @gen_cluster( client=True, Worker=Nanny, worker_kwargs={"memory_limit": "1 GiB"}, config={"distributed.worker.memory.rebalance.sender-min": 0.3}, ) async def test_rebalance(c, s, *_): """Test Client.rebalance(). These are just to test the Client wrapper around Scheduler.rebalance(); for more thorough tests on the latter see test_scheduler.py. """ # We used nannies to have separate processes for each worker a, b = s.workers # Generate 10 buffers worth 512 MiB total on worker a. This sends its memory # utilisation slightly above 50% (after counting unmanaged) which is above the # distributed.worker.memory.rebalance.sender-min threshold. futures = c.map(lambda _: "x" * (2 ** 29 // 10), range(10), workers=[a]) await wait(futures) # Wait for heartbeats while s.memory.process < 2 ** 29: await asyncio.sleep(0.1) assert await c.run(lambda dask_worker: len(dask_worker.data)) == {a: 10, b: 0} await c.rebalance() ndata = await c.run(lambda dask_worker: len(dask_worker.data)) # Allow for some uncertainty as the unmanaged memory is not stable assert sum(ndata.values()) == 10 assert 3 <= ndata[a] <= 7 assert 3 <= ndata[b] <= 7 @gen_cluster( nthreads=[("127.0.0.1", 1)] * 3, client=True, Worker=Nanny, worker_kwargs={"memory_limit": "1 GiB"}, ) async def test_rebalance_workers_and_keys(client, s, *_): """Test Client.rebalance(). These are just to test the Client wrapper around Scheduler.rebalance(); for more thorough tests on the latter see test_scheduler.py. """ a, b, c = s.workers futures = client.map(lambda _: "x" * (2 ** 29 // 10), range(10), workers=[a]) await wait(futures) # Wait for heartbeats while s.memory.process < 2 ** 29: await asyncio.sleep(0.1) # Passing empty iterables is not the same as omitting the arguments await client.rebalance([]) await client.rebalance(workers=[]) assert await client.run(lambda dask_worker: len(dask_worker.data)) == { a: 10, b: 0, c: 0, } # Limit rebalancing to two arbitrary keys and two arbitrary workers. await client.rebalance([futures[3], futures[7]], [a, b]) assert await client.run(lambda dask_worker: len(dask_worker.data)) == { a: 8, b: 2, c: 0, } with pytest.raises(KeyError): await client.rebalance(workers=["notexist"]) def test_rebalance_sync(): # can't use the 'c' fixture because we need workers to run in a separate process with Client(n_workers=2, memory_limit="1 GiB", dashboard_address=":0") as c: s = c.cluster.scheduler a, b = (ws.address for ws in s.workers.values()) futures = c.map(lambda _: "x" * (2 ** 29 // 10), range(10), workers=[a]) wait(futures) # Wait for heartbeat while s.memory.process < 2 ** 29: sleep(0.1) assert c.run(lambda dask_worker: len(dask_worker.data)) == {a: 10, b: 0} c.rebalance() ndata = c.run(lambda dask_worker: len(dask_worker.data)) # Allow for some uncertainty as the unmanaged memory is not stable assert sum(ndata.values()) == 10 assert 3 <= ndata[a] <= 7 assert 3 <= ndata[b] <= 7 @gen_cluster(client=True) async def test_rebalance_unprepared(c, s, a, b): """Client.rebalance() internally waits for unfinished futures""" futures = c.map(slowinc, range(10), delay=0.05, workers=a.address) # Let the futures reach the scheduler await asyncio.sleep(0.1) # We didn't wait enough for futures to complete. However, Client.rebalance() will # block until all futures are completed before invoking Scheduler.rebalance(). await c.rebalance(futures) s.validate_state() @gen_cluster(client=True) async def test_rebalance_raises_on_explicit_missing_data(c, s, a, b): """rebalance() raises KeyError if explicitly listed futures disappear""" f = Future("x", client=c, state="memory") with pytest.raises(KeyError, match="Could not rebalance keys:"): await c.rebalance(futures=[f]) @gen_cluster(client=True) async def test_receive_lost_key(c, s, a, b): x = c.submit(inc, 1, workers=[a.address]) await x await a.close() while x.status == "finished": await asyncio.sleep(0.01) @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_unrunnable_task_runs(c, s, a, b): x = c.submit(inc, 1, workers=[a.ip]) await x await a.close() while x.status == "finished": await asyncio.sleep(0.01) assert s.tasks[x.key] in s.unrunnable assert s.get_task_status(keys=[x.key]) == {x.key: "no-worker"} w = await Worker(s.address, loop=s.loop) while x.status != "finished": await asyncio.sleep(0.01) assert s.tasks[x.key] not in s.unrunnable result = await x assert result == 2 await w.close() @gen_cluster(client=True, nthreads=[]) async def test_add_worker_after_tasks(c, s): futures = c.map(inc, range(10)) n = await Nanny(s.address, nthreads=2, loop=s.loop) await c.gather(futures) await n.close() @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_workers_register_indirect_data(c, s, a, b): [x] = await c.scatter([1], workers=a.address) y = c.submit(inc, x, workers=b.ip) await y assert b.data[x.key] == 1 assert s.tasks[x.key].who_has == {s.workers[a.address], s.workers[b.address]} assert s.workers[b.address].has_what == {s.tasks[x.key], s.tasks[y.key]} s.validate_state() @gen_cluster(client=True) async def test_submit_on_cancelled_future(c, s, a, b): x = c.submit(inc, 1) await x await c.cancel(x) with pytest.raises(CancelledError): c.submit(inc, x) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 10) async def test_replicate(c, s, *workers): [a, b] = await c.scatter([1, 2]) await s.replicate(keys=[a.key, b.key], n=5) s.validate_state() assert len(s.tasks[a.key].who_has) == 5 assert len(s.tasks[b.key].who_has) == 5 assert sum(a.key in w.data for w in workers) == 5 assert sum(b.key in w.data for w in workers) == 5 @gen_cluster(client=True) async def test_replicate_tuple_keys(c, s, a, b): x = delayed(inc)(1, dask_key_name=("x", 1)) f = c.persist(x) await c.replicate(f, n=5) s.validate_state() assert a.data and b.data await c.rebalance(f) s.validate_state() @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 10) async def test_replicate_workers(c, s, *workers): [a, b] = await c.scatter([1, 2], workers=[workers[0].address]) await s.replicate( keys=[a.key, b.key], n=5, workers=[w.address for w in workers[:5]] ) assert len(s.tasks[a.key].who_has) == 5 assert len(s.tasks[b.key].who_has) == 5 assert sum(a.key in w.data for w in workers[:5]) == 5 assert sum(b.key in w.data for w in workers[:5]) == 5 assert sum(a.key in w.data for w in workers[5:]) == 0 assert sum(b.key in w.data for w in workers[5:]) == 0 await s.replicate(keys=[a.key, b.key], n=1) assert len(s.tasks[a.key].who_has) == 1 assert len(s.tasks[b.key].who_has) == 1 assert sum(a.key in w.data for w in workers) == 1 assert sum(b.key in w.data for w in workers) == 1 s.validate_state() await s.replicate(keys=[a.key, b.key], n=None) # all assert len(s.tasks[a.key].who_has) == 10 assert len(s.tasks[b.key].who_has) == 10 s.validate_state() await s.replicate( keys=[a.key, b.key], n=1, workers=[w.address for w in workers[:5]] ) assert sum(a.key in w.data for w in workers[:5]) == 1 assert sum(b.key in w.data for w in workers[:5]) == 1 assert sum(a.key in w.data for w in workers[5:]) == 5 assert sum(b.key in w.data for w in workers[5:]) == 5 s.validate_state() class CountSerialization: def __init__(self): self.n = 0 def __setstate__(self, n): self.n = n + 1 def __getstate__(self): return self.n @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 10) async def test_replicate_tree_branching(c, s, *workers): obj = CountSerialization() [future] = await c.scatter([obj]) await s.replicate(keys=[future.key], n=10) max_count = max(w.data[future.key].n for w in workers) assert max_count > 1 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 10) async def test_client_replicate(c, s, *workers): x = c.submit(inc, 1) y = c.submit(inc, 2) await c.replicate([x, y], n=5) assert len(s.tasks[x.key].who_has) == 5 assert len(s.tasks[y.key].who_has) == 5 await c.replicate([x, y], n=3) assert len(s.tasks[x.key].who_has) == 3 assert len(s.tasks[y.key].who_has) == 3 await c.replicate([x, y]) s.validate_state() assert len(s.tasks[x.key].who_has) == 10 assert len(s.tasks[y.key].who_has) == 10 @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster( client=True, nthreads=[("127.0.0.1", 1), ("127.0.0.2", 1), ("127.0.0.2", 1)], ) async def test_client_replicate_host(client, s, a, b, c): aws = s.workers[a.address] bws = s.workers[b.address] cws = s.workers[c.address] x = client.submit(inc, 1, workers="127.0.0.2") await wait([x]) assert s.tasks[x.key].who_has == {bws} or s.tasks[x.key].who_has == {cws} await client.replicate([x], workers=["127.0.0.2"]) assert s.tasks[x.key].who_has == {bws, cws} await client.replicate([x], workers=["127.0.0.1"]) assert s.tasks[x.key].who_has == {aws, bws, cws} def test_client_replicate_sync(c): x = c.submit(inc, 1) y = c.submit(inc, 2) c.replicate([x, y], n=2) who_has = c.who_has() assert len(who_has[x.key]) == len(who_has[y.key]) == 2 with pytest.raises(ValueError): c.replicate([x], n=0) assert y.result() == 3 @pytest.mark.skipif(WINDOWS, reason="Windows timer too coarse-grained") @gen_cluster(client=True, nthreads=[("127.0.0.1", 4)] * 1) async def test_task_load_adapts_quickly(c, s, a): future = c.submit(slowinc, 1, delay=0.2) # slow await wait(future) assert 0.15 < s.task_prefixes["slowinc"].duration_average < 0.4 futures = c.map(slowinc, range(10), delay=0) # very fast await wait(futures) assert 0 < s.task_prefixes["slowinc"].duration_average < 0.1 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 2) async def test_even_load_after_fast_functions(c, s, a, b): x = c.submit(inc, 1, workers=a.address) # very fast y = c.submit(inc, 2, workers=b.address) # very fast await wait([x, y]) futures = c.map(inc, range(2, 11)) await wait(futures) assert any(f.key in a.data for f in futures) assert any(f.key in b.data for f in futures) # assert abs(len(a.data) - len(b.data)) <= 3 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 2) async def test_even_load_on_startup(c, s, a, b): x, y = c.map(inc, [1, 2]) await wait([x, y]) assert len(a.data) == len(b.data) == 1 @pytest.mark.skip @gen_cluster(client=True, nthreads=[("127.0.0.1", 2)] * 2) async def test_contiguous_load(c, s, a, b): w, x, y, z = c.map(inc, [1, 2, 3, 4]) await wait([w, x, y, z]) groups = [set(a.data), set(b.data)] assert {w.key, x.key} in groups assert {y.key, z.key} in groups @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_balanced_with_submit(c, s, *workers): L = [c.submit(slowinc, i) for i in range(4)] await wait(L) for w in workers: assert len(w.data) == 1 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_balanced_with_submit_and_resident_data(c, s, *workers): [x] = await c.scatter([10], broadcast=True) L = [c.submit(slowinc, x, pure=False) for i in range(4)] await wait(L) for w in workers: assert len(w.data) == 2 @gen_cluster(client=True, nthreads=[("127.0.0.1", 20)] * 2) async def test_scheduler_saturates_cores(c, s, a, b): for delay in [0, 0.01, 0.1]: futures = c.map(slowinc, range(100), delay=delay) futures = c.map(slowinc, futures, delay=delay / 10) while not s.tasks: if s.tasks: assert all( len(p) >= 20 for w in s.workers.values() for p in w.processing.values() ) await asyncio.sleep(0.01) @gen_cluster(client=True, nthreads=[("127.0.0.1", 20)] * 2) async def test_scheduler_saturates_cores_random(c, s, a, b): for delay in [0, 0.01, 0.1]: futures = c.map(randominc, range(100), scale=0.1) while not s.tasks: if s.tasks: assert all( len(p) >= 20 for w in s.workers.values() for p in w.processing.values() ) await asyncio.sleep(0.01) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_cancel_clears_processing(c, s, *workers): da = pytest.importorskip("dask.array") x = c.submit(slowinc, 1, delay=0.2) while not s.tasks: await asyncio.sleep(0.01) await c.cancel(x) while any(v for w in s.workers.values() for v in w.processing): await asyncio.sleep(0.01) s.validate_state() def test_default_get(): with cluster() as (s, [a, b]): pre_get = dask.base.get_scheduler() pytest.raises(KeyError, dask.config.get, "shuffle") with Client(s["address"], set_as_default=True) as c: assert dask.base.get_scheduler() == c.get assert dask.config.get("shuffle") == "tasks" assert dask.base.get_scheduler() == pre_get pytest.raises(KeyError, dask.config.get, "shuffle") c = Client(s["address"], set_as_default=False) assert dask.base.get_scheduler() == pre_get pytest.raises(KeyError, dask.config.get, "shuffle") c.close() c = Client(s["address"], set_as_default=True) assert dask.config.get("shuffle") == "tasks" assert dask.base.get_scheduler() == c.get c.close() assert dask.base.get_scheduler() == pre_get pytest.raises(KeyError, dask.config.get, "shuffle") with Client(s["address"]) as c: assert dask.base.get_scheduler() == c.get with Client(s["address"], set_as_default=False) as c: assert dask.base.get_scheduler() != c.get assert dask.base.get_scheduler() != c.get with Client(s["address"], set_as_default=True) as c1: assert dask.base.get_scheduler() == c1.get with Client(s["address"], set_as_default=True) as c2: assert dask.base.get_scheduler() == c2.get assert dask.base.get_scheduler() == c1.get assert dask.base.get_scheduler() == pre_get @gen_cluster() async def test_set_as_default(s, a, b): with pytest.raises(ValueError): default_client() async with Client(s.address, set_as_default=False, asynchronous=True) as c1: with pytest.raises(ValueError): default_client() async with Client(s.address, set_as_default=True, asynchronous=True) as c2: assert default_client() is c2 async with Client(s.address, set_as_default=True, asynchronous=True) as c3: assert default_client() is c3 async with Client( s.address, set_as_default=False, asynchronous=True ) as c4: assert default_client() is c3 await c4.scheduler_comm.close() while c4.status != "running": await asyncio.sleep(0.01) assert default_client() is c3 with pytest.raises(ValueError): default_client() @gen_cluster(client=True) async def test_get_processing(c, s, a, b): processing = await c.processing() assert processing == valmap(tuple, s.processing) futures = c.map( slowinc, range(10), delay=0.1, workers=[a.address], allow_other_workers=True ) await asyncio.sleep(0.2) x = await c.processing() assert set(x) == {a.address, b.address} x = await c.processing(workers=[a.address]) assert isinstance(x[a.address], (list, tuple)) @gen_cluster(client=True) async def test_get_foo(c, s, a, b): futures = c.map(inc, range(10)) await wait(futures) x = await c.scheduler.ncores() assert x == s.nthreads x = await c.scheduler.ncores(workers=[a.address]) assert x == {a.address: s.nthreads[a.address]} x = await c.scheduler.has_what() assert valmap(sorted, x) == valmap(sorted, s.has_what) x = await c.scheduler.has_what(workers=[a.address]) assert valmap(sorted, x) == {a.address: sorted(s.has_what[a.address])} x = await c.scheduler.nbytes(summary=False) assert x == s.get_nbytes(summary=False) x = await c.scheduler.nbytes(keys=[futures[0].key], summary=False) assert x == {futures[0].key: s.tasks[futures[0].key].nbytes} x = await c.scheduler.who_has() assert valmap(sorted, x) == valmap(sorted, s.who_has) x = await c.scheduler.who_has(keys=[futures[0].key]) assert valmap(sorted, x) == {futures[0].key: sorted(s.who_has[futures[0].key])} def assert_dict_key_equal(expected, actual): assert set(expected.keys()) == set(actual.keys()) for k in actual.keys(): ev = expected[k] av = actual[k] assert list(ev) == list(av) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 3) async def test_get_foo_lost_keys(c, s, u, v, w): x = c.submit(inc, 1, workers=[u.address]) y = await c.scatter(3, workers=[v.address]) await wait([x, y]) ua, va, wa = u.address, v.address, w.address d = await c.scheduler.has_what() assert_dict_key_equal(d, {ua: [x.key], va: [y.key], wa: []}) d = await c.scheduler.has_what(workers=[ua, va]) assert_dict_key_equal(d, {ua: [x.key], va: [y.key]}) d = await c.scheduler.who_has() assert_dict_key_equal(d, {x.key: [ua], y.key: [va]}) d = await c.scheduler.who_has(keys=[x.key, y.key]) assert_dict_key_equal(d, {x.key: [ua], y.key: [va]}) await u.close() await v.close() d = await c.scheduler.has_what() assert_dict_key_equal(d, {wa: []}) d = await c.scheduler.has_what(workers=[ua, va]) assert_dict_key_equal(d, {ua: [], va: []}) # The scattered key cannot be recomputed so it is forgotten d = await c.scheduler.who_has() assert_dict_key_equal(d, {x.key: []}) # ... but when passed explicitly, it is included in the result d = await c.scheduler.who_has(keys=[x.key, y.key]) assert_dict_key_equal(d, {x.key: [], y.key: []}) @pytest.mark.slow @gen_cluster( client=True, Worker=Nanny, clean_kwargs={"threads": False, "processes": False} ) async def test_bad_tasks_fail(c, s, a, b): f = c.submit(sys.exit, 0) with captured_logger(logging.getLogger("distributed.scheduler")) as logger: with pytest.raises(KilledWorker) as info: await f text = logger.getvalue() assert f.key in text assert info.value.last_worker.nanny in {a.address, b.address} await asyncio.gather(a.close(), b.close()) def test_get_processing_sync(c, s, a, b): processing = c.processing() assert not any(v for v in processing.values()) futures = c.map( slowinc, range(10), delay=0.1, workers=[a["address"]], allow_other_workers=False ) sleep(0.2) aa = a["address"] bb = b["address"] processing = c.processing() assert set(c.processing(aa)) == {aa} assert set(c.processing([aa])) == {aa} c.cancel(futures) def test_close_idempotent(c): c.close() c.close() c.close() @nodebug def test_get_returns_early(c): start = time() with suppress(RuntimeError): result = c.get({"x": (throws, 1), "y": (sleep, 1)}, ["x", "y"]) assert time() < start + 0.5 # Futures should be released and forgotten wait_for(lambda: not c.futures, timeout=0.1) wait_for(lambda: not any(c.processing().values()), timeout=3) x = c.submit(inc, 1) x.result() with suppress(RuntimeError): result = c.get({"x": (throws, 1), x.key: (inc, 1)}, ["x", x.key]) assert x.key in c.futures @pytest.mark.slow @gen_cluster(Worker=Nanny, client=True, timeout=60) async def test_Client_clears_references_after_restart(c, s, a, b): x = c.submit(inc, 1) assert x.key in c.refcount await c.restart() assert x.key not in c.refcount key = x.key del x import gc gc.collect() await asyncio.sleep(0) assert key not in c.refcount @gen_cluster(Worker=Nanny, client=True) async def test_restart_timeout_is_logged(c, s, a, b): with captured_logger(logging.getLogger("distributed.client")) as logger: await c.restart(timeout="0.5s") text = logger.getvalue() assert "Restart timed out after 0.50 seconds" in text def test_get_stops_work_after_error(c): with pytest.raises(RuntimeError): c.get({"x": (throws, 1), "y": (sleep, 1.5)}, ["x", "y"]) start = time() while any(c.processing().values()): sleep(0.01) assert time() < start + 0.5 def test_as_completed_list(c): seq = c.map(inc, range(5)) seq2 = list(as_completed(seq)) assert set(c.gather(seq2)) == {1, 2, 3, 4, 5} def test_as_completed_results(c): seq = c.map(inc, range(5)) seq2 = list(as_completed(seq, with_results=True)) assert set(pluck(1, seq2)) == {1, 2, 3, 4, 5} assert set(pluck(0, seq2)) == set(seq) @pytest.mark.parametrize("with_results", [True, False]) def test_as_completed_batches(c, with_results): n = 50 futures = c.map(slowinc, range(n), delay=0.01) out = [] for batch in as_completed(futures, with_results=with_results).batches(): assert isinstance(batch, (tuple, list)) sleep(0.05) out.extend(batch) assert len(out) == n if with_results: assert set(pluck(1, out)) == set(range(1, n + 1)) else: assert set(out) == set(futures) def test_as_completed_next_batch(c): futures = c.map(slowinc, range(2), delay=0.1) ac = as_completed(futures) assert not ac.is_empty() assert ac.next_batch(block=False) == [] assert set(ac.next_batch(block=True)).issubset(futures) while not ac.is_empty(): assert set(ac.next_batch(block=True)).issubset(futures) assert ac.is_empty() assert not ac.has_ready() @gen_cluster(nthreads=[]) async def test_status(s): c = await Client(s.address, asynchronous=True) assert c.status == "running" x = c.submit(inc, 1) await c.close() assert c.status == "closed" @gen_cluster(client=True) async def test_async_whowhat(c, s, a, b): [x] = await c.scatter([1], workers=a.address) who_has = await c.who_has() has_what = await c.has_what() assert type(who_has) is WhoHas assert type(has_what) is HasWhat assert who_has == {x.key: (a.address,)} assert has_what == {a.address: (x.key,), b.address: ()} def test_client_repr_html(c): x = c.submit(inc, 1) who_has = c.who_has() has_what = c.has_what() assert type(who_has) is WhoHas assert type(has_what) is HasWhat @gen_cluster(client=True) async def test_persist_optimize_graph(c, s, a, b): i = 10 for method in [c.persist, c.compute]: b = db.range(i, npartitions=2) i += 1 b2 = b.map(inc) b3 = b2.map(inc) b4 = method(b3, optimize_graph=False) await wait(b4) assert set(map(stringify, b3.__dask_keys__())).issubset(s.tasks) b = db.range(i, npartitions=2) i += 1 b2 = b.map(inc) b3 = b2.map(inc) b4 = method(b3, optimize_graph=True) await wait(b4) assert not any(stringify(k) in s.tasks for k in b2.__dask_keys__()) @gen_cluster(client=True, nthreads=[]) async def test_scatter_raises_if_no_workers(c, s): with pytest.raises(TimeoutError): await c.scatter(1, timeout=0.5) @pytest.mark.slow def test_reconnect(loop): w = Worker("127.0.0.1", 9393, loop=loop) loop.add_callback(w.start) scheduler_cli = [ "dask-scheduler", "--host", "127.0.0.1", "--port", "9393", "--no-dashboard", ] with popen(scheduler_cli) as s: c = Client("127.0.0.1:9393", loop=loop) start = time() while len(c.nthreads()) != 1: sleep(0.1) assert time() < start + 3 x = c.submit(inc, 1) assert x.result() == 2 start = time() while c.status != "connecting": assert time() < start + 5 sleep(0.01) assert x.status == "cancelled" with pytest.raises(CancelledError): x.result() with popen(scheduler_cli) as s: start = time() while c.status != "running": sleep(0.1) assert time() < start + 5 start = time() while len(c.nthreads()) != 1: sleep(0.05) assert time() < start + 15 x = c.submit(inc, 1) assert x.result() == 2 start = time() while True: try: x.result() assert False except CommClosedError: continue except CancelledError: break assert time() < start + 5 sleep(0.1) sync(loop, w.close) c.close() @gen_cluster(client=True, nthreads=[], client_kwargs={"timeout": 0.5}) async def test_reconnect_timeout(c, s): with captured_logger(logging.getLogger("distributed.client")) as logger: await s.close() while c.status != "closed": await c._update_scheduler_info() await asyncio.sleep(0.05) text = logger.getvalue() assert "Failed to reconnect" in text @pytest.mark.avoid_ci(reason="hangs on github actions ubuntu-latest CI") @pytest.mark.slow @pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows") @pytest.mark.parametrize("worker,count,repeat", [(Worker, 100, 5), (Nanny, 10, 20)]) def test_open_close_many_workers(loop, worker, count, repeat): proc = psutil.Process() with cluster(nworkers=0, active_rpc_timeout=2) as (s, _): gc.collect() before = proc.num_fds() done = Semaphore(0) running = weakref.WeakKeyDictionary() workers = set() status = True async def start_worker(sleep, duration, repeat=1): for i in range(repeat): await asyncio.sleep(sleep) if not status: return w = worker(s["address"], loop=loop) running[w] = None await w workers.add(w) addr = w.worker_address running[w] = addr await asyncio.sleep(duration) await w.close() del w await asyncio.sleep(0) done.release() for i in range(count): loop.add_callback( start_worker, random.random() / 5, random.random() / 5, repeat=repeat ) with Client(s["address"], loop=loop) as c: sleep(1) for i in range(count): done.acquire(timeout=5) gc.collect() if not running: break start = time() while c.nthreads(): sleep(0.2) assert time() < start + 10 while len(workers) < count * repeat: sleep(0.2) status = False [c.sync(w.close) for w in list(workers)] for w in workers: assert w.status == Status.closed start = time() while proc.num_fds() > before: print("fds:", before, proc.num_fds()) sleep(0.1) if time() > start + 10: if worker == Worker: # this is an esoteric case print("File descriptors did not clean up") break else: raise ValueError("File descriptors did not clean up") @gen_cluster() async def test_idempotence(s, a, b): c = await Client(s.address, asynchronous=True) f = await Client(s.address, asynchronous=True) # Submit x = c.submit(inc, 1) await x log = list(s.transition_log) len_single_submit = len(log) # see last assert y = f.submit(inc, 1) assert x.key == y.key await y await asyncio.sleep(0.1) log2 = list(s.transition_log) assert log == log2 # Error a = c.submit(div, 1, 0) await wait(a) assert a.status == "error" log = list(s.transition_log) b = f.submit(div, 1, 0) assert a.key == b.key await wait(b) await asyncio.sleep(0.1) log2 = list(s.transition_log) assert log == log2 s.transition_log.clear() # Simultaneous Submit d = c.submit(inc, 2) e = c.submit(inc, 2) await wait([d, e]) assert len(s.transition_log) == len_single_submit await c.close() await f.close() def test_scheduler_info(c): info = c.scheduler_info() assert isinstance(info, dict) assert len(info["workers"]) == 2 assert isinstance(info["started"], float) def test_write_scheduler_file(c): info = c.scheduler_info() with tmpfile("json") as scheduler_file: c.write_scheduler_file(scheduler_file) with Client(scheduler_file=scheduler_file) as c2: info2 = c2.scheduler_info() assert c.scheduler.address == c2.scheduler.address # test that a ValueError is raised if the scheduler_file # attribute is already set with pytest.raises(ValueError): c.write_scheduler_file(scheduler_file) def test_get_versions(c): requests = pytest.importorskip("requests") v = c.get_versions() assert v["scheduler"] is not None assert v["client"] is not None assert len(v["workers"]) == 2 for k, v in v["workers"].items(): assert v is not None c.get_versions(check=True) # smoke test for versions # that this does not raise v = c.get_versions(packages=["requests"]) assert v["client"]["packages"]["requests"] == requests.__version__ @gen_cluster(client=True) async def test_async_get_versions(c, s, a, b): await c.get_versions(check=True) def test_threaded_get_within_distributed(c): import dask.multiprocessing for get in [dask.local.get_sync, dask.multiprocessing.get, dask.threaded.get]: def f(): return get({"x": (lambda: 1,)}, "x") future = c.submit(f) assert future.result() == 1 @gen_cluster(client=True) async def test_lose_scattered_data(c, s, a, b): [x] = await c.scatter([1], workers=a.address) await a.close() await asyncio.sleep(0.1) assert x.status == "cancelled" assert x.key not in s.tasks @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 3) async def test_partially_lose_scattered_data(e, s, a, b, c): x = await e.scatter(1, workers=a.address) await e.replicate(x, n=2) await a.close() await asyncio.sleep(0.1) assert x.status == "finished" assert s.get_task_status(keys=[x.key]) == {x.key: "memory"} @gen_cluster(client=True) async def test_scatter_compute_lose(c, s, a, b): [x] = await c.scatter([[1, 2, 3, 4]], workers=a.address) y = c.submit(inc, 1, workers=b.address) z = c.submit(slowadd, x, y, delay=0.2) await asyncio.sleep(0.1) await a.close() with pytest.raises(CancelledError): await wait(z) assert x.status == "cancelled" assert y.status == "finished" assert z.status == "cancelled" @gen_cluster(client=True) async def test_scatter_compute_store_lose(c, s, a, b): """ Create irreplaceable data on one machine, cause a dependent computation to occur on another and complete Kill the machine with the irreplaceable data. What happens to the complete result? How about after it GCs and tries to come back? """ x = await c.scatter(1, workers=a.address) xx = c.submit(inc, x, workers=a.address) y = c.submit(inc, 1) z = c.submit(slowadd, xx, y, delay=0.2, workers=b.address) await wait(z) await a.close() while x.status == "finished": await asyncio.sleep(0.01) # assert xx.status == 'finished' assert y.status == "finished" assert z.status == "finished" zz = c.submit(inc, z) await wait(zz) zkey = z.key del z while s.get_task_status(keys=[zkey]) != {zkey: "released"}: await asyncio.sleep(0.01) xxkey = xx.key del xx while x.key in s.tasks and zkey not in s.tasks and xxkey not in s.tasks: await asyncio.sleep(0.01) @gen_cluster(client=True) async def test_scatter_compute_store_lose_processing(c, s, a, b): """ Create irreplaceable data on one machine, cause a dependent computation to occur on another and complete Kill the machine with the irreplaceable data. What happens to the complete result? How about after it GCs and tries to come back? """ [x] = await c.scatter([1], workers=a.address) y = c.submit(slowinc, x, delay=0.2) z = c.submit(inc, y) await asyncio.sleep(0.1) await a.close() while x.status == "finished": await asyncio.sleep(0.01) assert y.status == "cancelled" assert z.status == "cancelled" @gen_cluster() async def test_serialize_future(s, a, b): c1 = await Client(s.address, asynchronous=True) c2 = await Client(s.address, asynchronous=True) future = c1.submit(lambda: 1) result = await future for ci in (c1, c2): for ctxman in ci.as_current, lambda: temp_default_client(ci): with ctxman(): future2 = pickle.loads(pickle.dumps(future)) assert future2.client is ci assert stringify(future2.key) in ci.futures result2 = await future2 assert result == result2 await c1.close() await c2.close() @gen_cluster() async def test_temp_default_client(s, a, b): c1 = await Client(s.address, asynchronous=True) c2 = await Client(s.address, asynchronous=True) with temp_default_client(c1): assert default_client() is c1 assert default_client(c2) is c2 with temp_default_client(c2): assert default_client() is c2 assert default_client(c1) is c1 await c1.close() await c2.close() @gen_cluster(client=True) async def test_as_current(c, s, a, b): c1 = await Client(s.address, asynchronous=True) c2 = await Client(s.address, asynchronous=True) with temp_default_client(c): assert Client.current() is c with pytest.raises(ValueError): Client.current(allow_global=False) with c1.as_current(): assert Client.current() is c1 assert Client.current(allow_global=True) is c1 with c2.as_current(): assert Client.current() is c2 assert Client.current(allow_global=True) is c2 await c1.close() await c2.close() def test_as_current_is_thread_local(s): l1 = threading.Lock() l2 = threading.Lock() l3 = threading.Lock() l4 = threading.Lock() l1.acquire() l2.acquire() l3.acquire() l4.acquire() def run1(): with Client(s["address"]) as c: with c.as_current(): l1.acquire() l2.release() try: # This line runs only when both run1 and run2 are inside the # context manager assert Client.current(allow_global=False) is c finally: l3.acquire() l4.release() def run2(): with Client(s["address"]) as c: with c.as_current(): l1.release() l2.acquire() try: # This line runs only when both run1 and run2 are inside the # context manager assert Client.current(allow_global=False) is c finally: l3.release() l4.acquire() t1 = threading.Thread(target=run1) t2 = threading.Thread(target=run2) t1.start() t2.start() t1.join() t2.join() @gen_cluster() async def test_as_current_is_task_local(s, a, b): l1 = asyncio.Lock() l2 = asyncio.Lock() l3 = asyncio.Lock() l4 = asyncio.Lock() await l1.acquire() await l2.acquire() await l3.acquire() await l4.acquire() async def run1(): async with Client(s.address, asynchronous=True) as c: with c.as_current(): await l1.acquire() l2.release() try: # This line runs only when both run1 and run2 are inside the # context manager assert Client.current(allow_global=False) is c finally: await l3.acquire() l4.release() async def run2(): async with Client(s.address, asynchronous=True) as c: with c.as_current(): l1.release() await l2.acquire() try: # This line runs only when both run1 and run2 are inside the # context manager assert Client.current(allow_global=False) is c finally: l3.release() await l4.acquire() await asyncio.gather(run1(), run2()) @nodebug # test timing is fragile @gen_cluster(nthreads=[("127.0.0.1", 1)] * 3, client=True) async def test_persist_workers_annotate(e, s, a, b, c): with dask.annotate(workers=a.address, allow_other_workers=False): L1 = [delayed(inc)(i) for i in range(4)] with dask.annotate(workers=b.address, allow_other_workers=False): total = delayed(sum)(L1) with dask.annotate(workers=c.address, allow_other_workers=True): L2 = [delayed(add)(i, total) for i in L1] with dask.annotate(workers=b.address, allow_other_workers=True): total2 = delayed(sum)(L2) # TODO: once annotations are faithfully forwarded upon graph optimization, # we shouldn't need to disable that here. out = e.persist(L1 + L2 + [total, total2], optimize_graph=False) await wait(out) assert all(v.key in a.data for v in L1) assert total.key in b.data assert s.loose_restrictions == {total2.key} | {v.key for v in L2} @gen_cluster(nthreads=[("127.0.0.1", 1)] * 3, client=True) async def test_persist_workers_annotate2(e, s, a, b, c): def key_to_worker(key): return a.address L1 = [delayed(inc)(i) for i in range(4)] for x in L1: assert all(layer.annotations is None for layer in x.dask.layers.values()) with dask.annotate(workers=key_to_worker): out = e.persist(L1, optimize_graph=False) await wait(out) for x in L1: assert all(layer.annotations is None for layer in x.dask.layers.values()) for v in L1: assert s.worker_restrictions[v.key] == {a.address} @nodebug # test timing is fragile @gen_cluster(nthreads=[("127.0.0.1", 1)] * 3, client=True) async def test_persist_workers(e, s, a, b, c): L1 = [delayed(inc)(i) for i in range(4)] total = delayed(sum)(L1) L2 = [delayed(add)(i, total) for i in L1] total2 = delayed(sum)(L2) out = e.persist( L1 + L2 + [total, total2], workers=[a.address, b.address], allow_other_workers=True, ) await wait(out) for v in L1 + L2 + [total, total2]: assert s.worker_restrictions[v.key] == {a.address, b.address} assert not any(c.address in r for r in s.worker_restrictions) assert s.loose_restrictions == {total.key, total2.key} | {v.key for v in L1 + L2} @gen_cluster(nthreads=[("127.0.0.1", 1)] * 3, client=True) async def test_compute_workers_annotate(e, s, a, b, c): with dask.annotate(workers=a.address, allow_other_workers=True): L1 = [delayed(inc)(i) for i in range(4)] with dask.annotate(workers=b.address, allow_other_workers=True): total = delayed(sum)(L1) with dask.annotate(workers=[c.address]): L2 = [delayed(add)(i, total) for i in L1] # TODO: once annotations are faithfully forwarded upon graph optimization, # we shouldn't need to disable that here. out = e.compute(L1 + L2 + [total], optimize_graph=False) await wait(out) for v in L1: assert s.worker_restrictions[v.key] == {a.address} for v in L2: assert s.worker_restrictions[v.key] == {c.address} assert s.worker_restrictions[total.key] == {b.address} assert s.loose_restrictions == {total.key} | {v.key for v in L1} @gen_cluster(nthreads=[("127.0.0.1", 1)] * 3, client=True) async def test_compute_workers(e, s, a, b, c): L1 = [delayed(inc)(i) for i in range(4)] total = delayed(sum)(L1) L2 = [delayed(add)(i, total) for i in L1] out = e.compute( L1 + L2 + [total], workers=[a.address, b.address], allow_other_workers=True, ) await wait(out) for v in L1 + L2 + [total]: assert s.worker_restrictions[v.key] == {a.address, b.address} assert not any(c.address in r for r in s.worker_restrictions) assert s.loose_restrictions == {total.key} | {v.key for v in L1 + L2} @gen_cluster(client=True) async def test_compute_nested_containers(c, s, a, b): da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") x = da.ones(10, chunks=(5,)) + 1 future = c.compute({"x": [x], "y": 123}) result = await future assert isinstance(result, dict) assert (result["x"][0] == np.ones(10) + 1).all() assert result["y"] == 123 @gen_cluster(client=True) async def test_scatter_type(c, s, a, b): [future] = await c.scatter([1]) assert future.type == int d = await c.scatter({"x": 1.0}) assert d["x"].type == float @gen_cluster(client=True) async def test_retire_workers_2(c, s, a, b): [x] = await c.scatter([1], workers=a.address) await s.retire_workers(workers=[a.address]) assert b.data == {x.key: 1} assert s.who_has == {x.key: {b.address}} assert s.has_what == {b.address: {x.key}} assert a.address not in s.workers @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 10) async def test_retire_many_workers(c, s, *workers): futures = await c.scatter(list(range(100))) await s.retire_workers(workers=[w.address for w in workers[:7]]) results = await c.gather(futures) assert results == list(range(100)) while len(s.workers) != 3: await asyncio.sleep(0.01) assert len(s.has_what) == len(s.nthreads) == 3 assert all(future.done() for future in futures) assert all(s.tasks[future.key].state == "memory" for future in futures) for w, keys in s.has_what.items(): assert 15 < len(keys) < 50 @gen_cluster( client=True, nthreads=[("127.0.0.1", 3)] * 2, config={"distributed.scheduler.default-task-durations": {"f": "10ms"}}, ) async def test_weight_occupancy_against_data_movement(c, s, a, b): s.extensions["stealing"]._pc.callback_time = 1000000 def f(x, y=0, z=0): sleep(0.01) return x y = await c.scatter([[1, 2, 3, 4]], workers=[a.address]) z = await c.scatter([1], workers=[b.address]) futures = c.map(f, [1, 2, 3, 4], y=y, z=z) await wait(futures) assert sum(f.key in a.data for f in futures) >= 2 assert sum(f.key in b.data for f in futures) >= 1 @gen_cluster( client=True, nthreads=[("127.0.0.1", 1), ("127.0.0.1", 10)], config={"distributed.scheduler.default-task-durations": {"f": "10ms"}}, ) async def test_distribute_tasks_by_nthreads(c, s, a, b): s.extensions["stealing"]._pc.callback_time = 1000000 def f(x, y=0): sleep(0.01) return x y = await c.scatter([1], broadcast=True) futures = c.map(f, range(20), y=y) await wait(futures) assert len(b.data) > 2 * len(a.data) @gen_cluster(client=True, clean_kwargs={"threads": False}) async def test_add_done_callback(c, s, a, b): S = set() def f(future): future.add_done_callback(g) def g(future): S.add((future.key, future.status)) u = c.submit(inc, 1, key="u") v = c.submit(throws, "hello", key="v") w = c.submit(slowinc, 2, delay=0.3, key="w") x = c.submit(inc, 3, key="x") u.add_done_callback(f) v.add_done_callback(f) w.add_done_callback(f) await wait((u, v, w, x)) x.add_done_callback(f) while len(S) < 4: await asyncio.sleep(0.01) assert S == {(f.key, f.status) for f in (u, v, w, x)} @gen_cluster(client=True) async def test_normalize_collection(c, s, a, b): x = delayed(inc)(1) y = delayed(inc)(x) z = delayed(inc)(y) yy = c.persist(y) zz = c.normalize_collection(z) assert len(z.dask) == len(y.dask) + 1 assert isinstance(zz.dask[y.key], Future) assert len(zz.dask) < len(z.dask) @gen_cluster(client=True) async def test_normalize_collection_dask_array(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones(10, chunks=(5,)) y = x + 1 yy = c.persist(y) z = y.sum() zdsk = dict(z.dask) zz = c.normalize_collection(z) assert z.dask == zdsk # do not mutate input assert len(z.dask) > len(zz.dask) assert any(isinstance(v, Future) for v in zz.dask.values()) for k, v in yy.dask.items(): assert zz.dask[k].key == v.key result1 = await c.compute(z) result2 = await c.compute(zz) assert result1 == result2 @pytest.mark.slow def test_normalize_collection_with_released_futures(c): da = pytest.importorskip("dask.array") x = da.arange(2 ** 20, chunks=2 ** 10) y = x.persist() wait(y) sol = y.sum().compute() # Start releasing futures del y # Try to reuse futures. Previously this was a race condition, # and the call to `.compute()` would error out due to missing # futures on the scheduler at compute time. normalized = c.normalize_collection(x) res = normalized.sum().compute() assert res == sol @pytest.mark.xfail(reason="https://github.com/dask/distributed/issues/4404") @gen_cluster(client=True) async def test_auto_normalize_collection(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones(10, chunks=5) assert len(x.dask) == 2 with dask.config.set(optimizations=[c._optimize_insert_futures]): y = x.map_blocks(slowinc, delay=1, dtype=x.dtype) yy = c.persist(y) await wait(yy) start = time() future = c.compute(y.sum()) await future end = time() assert end - start < 1 start = time() z = c.persist(y + 1) await wait(z) end = time() assert end - start < 1 @pytest.mark.xfail(reason="https://github.com/dask/distributed/issues/4404") def test_auto_normalize_collection_sync(c): da = pytest.importorskip("dask.array") x = da.ones(10, chunks=5) y = x.map_blocks(slowinc, delay=1, dtype=x.dtype) yy = c.persist(y) wait(yy) with dask.config.set(optimizations=[c._optimize_insert_futures]): start = time() y.sum().compute() end = time() assert end - start < 1 def assert_no_data_loss(scheduler): for key, start, finish, recommendations, _ in scheduler.transition_log: if start == "memory" and finish == "released": for k, v in recommendations.items(): assert not (k == key and v == "waiting") @gen_cluster(client=True) async def test_interleave_computations(c, s, a, b): import distributed distributed.g = s xs = [delayed(slowinc)(i, delay=0.02) for i in range(30)] ys = [delayed(slowdec)(x, delay=0.02) for x in xs] zs = [delayed(slowadd)(x, y, delay=0.02) for x, y in zip(xs, ys)] total = delayed(sum)(zs) future = c.compute(total) done = ("memory", "released") await asyncio.sleep(0.1) x_keys = [x.key for x in xs] y_keys = [y.key for y in ys] z_keys = [z.key for z in zs] while not s.tasks or any(w.processing for w in s.workers.values()): await asyncio.sleep(0.05) x_done = sum(state in done for state in s.get_task_status(keys=x_keys).values()) y_done = sum(state in done for state in s.get_task_status(keys=y_keys).values()) z_done = sum(state in done for state in s.get_task_status(keys=z_keys).values()) assert x_done >= y_done >= z_done assert x_done < y_done + 10 assert y_done < z_done + 10 assert_no_data_loss(s) @pytest.mark.skip(reason="Now prefer first-in-first-out") @gen_cluster(client=True) async def test_interleave_computations_map(c, s, a, b): xs = c.map(slowinc, range(30), delay=0.02) ys = c.map(slowdec, xs, delay=0.02) zs = c.map(slowadd, xs, ys, delay=0.02) done = ("memory", "released") x_keys = [x.key for x in xs] y_keys = [y.key for y in ys] z_keys = [z.key for z in zs] while not s.tasks or any(w.processing for w in s.workers.values()): await asyncio.sleep(0.05) x_done = sum(state in done for state in s.get_task_status(keys=x_keys).values()) y_done = sum(state in done for state in s.get_task_status(keys=y_keys).values()) z_done = sum(state in done for state in s.get_task_status(keys=z_keys).values()) assert x_done >= y_done >= z_done assert x_done < y_done + 10 assert y_done < z_done + 10 @gen_cluster(client=True) async def test_scatter_dict_workers(c, s, a, b): await c.scatter({"a": 10}, workers=[a.address, b.address]) assert "a" in a.data or "a" in b.data @pytest.mark.slow @gen_test(timeout=180) async def test_client_timeout(): c = Client("127.0.0.1:57484", asynchronous=True) s = Scheduler(loop=c.loop, port=57484, dashboard_address=":0") await asyncio.sleep(4) try: await s except OSError: # port in use await c.close() return try: await c await c.close() finally: await s.close() @gen_cluster(client=True) async def test_submit_list_kwargs(c, s, a, b): futures = await c.scatter([1, 2, 3]) def f(L=None): return sum(L) future = c.submit(f, L=futures) result = await future assert result == 1 + 2 + 3 @gen_cluster(client=True) async def test_map_list_kwargs(c, s, a, b): futures = await c.scatter([1, 2, 3]) def f(i, L=None): return i + sum(L) futures = c.map(f, range(10), L=futures) results = await c.gather(futures) assert results == [i + 6 for i in range(10)] @gen_cluster(client=True) async def test_dont_clear_waiting_data(c, s, a, b): x = await c.scatter(1) y = c.submit(slowinc, x, delay=0.5) while y.key not in s.tasks: await asyncio.sleep(0.01) key = x.key del x for i in range(5): assert s.waiting_data[key] await asyncio.sleep(0) @gen_cluster(client=True) async def test_recreate_error_delayed(c, s, a, b): x0 = delayed(dec)(2) y0 = delayed(dec)(1) x = delayed(div)(1, x0) y = delayed(div)(1, y0) tot = delayed(sum)(x, y) f = c.compute(tot) assert f.status == "pending" error_f = await c._get_errored_future(f) function, args, kwargs = await c._get_components_from_future(error_f) assert f.status == "error" assert function.__name__ == "div" assert args == (1, 0) with pytest.raises(ZeroDivisionError): function(*args, **kwargs) @gen_cluster(client=True) async def test_recreate_error_futures(c, s, a, b): x0 = c.submit(dec, 2) y0 = c.submit(dec, 1) x = c.submit(div, 1, x0) y = c.submit(div, 1, y0) tot = c.submit(sum, x, y) f = c.compute(tot) assert f.status == "pending" error_f = await c._get_errored_future(f) function, args, kwargs = await c._get_components_from_future(error_f) assert f.status == "error" assert function.__name__ == "div" assert args == (1, 0) with pytest.raises(ZeroDivisionError): function(*args, **kwargs) @gen_cluster(client=True) async def test_recreate_error_collection(c, s, a, b): b = db.range(10, npartitions=4) b = b.map(lambda x: 1 / x) b = b.persist() f = c.compute(b) error_f = await c._get_errored_future(f) function, args, kwargs = await c._get_components_from_future(error_f) with pytest.raises(ZeroDivisionError): function(*args, **kwargs) dd = pytest.importorskip("dask.dataframe") import pandas as pd df = dd.from_pandas(pd.DataFrame({"a": [0, 1, 2, 3, 4]}), chunksize=2) def make_err(x): # because pandas would happily work with NaN if x == 0: raise ValueError return x df2 = df.a.map(make_err) f = c.compute(df2) error_f = await c._get_errored_future(f) function, args, kwargs = await c._get_components_from_future(error_f) with pytest.raises(ValueError): function(*args, **kwargs) # with persist df3 = c.persist(df2) error_f = await c._get_errored_future(df3) function, args, kwargs = await c._get_components_from_future(error_f) with pytest.raises(ValueError): function(*args, **kwargs) @gen_cluster(client=True) async def test_recreate_error_array(c, s, a, b): da = pytest.importorskip("dask.array") pytest.importorskip("scipy") z = (da.linalg.inv(da.zeros((10, 10), chunks=10)) + 1).sum() zz = z.persist() error_f = await c._get_errored_future(zz) function, args, kwargs = await c._get_components_from_future(error_f) assert "0.,0.,0." in str(args).replace(" ", "") # args contain actual arrays def test_recreate_error_sync(c): x0 = c.submit(dec, 2) y0 = c.submit(dec, 1) x = c.submit(div, 1, x0) y = c.submit(div, 1, y0) tot = c.submit(sum, x, y) f = c.compute(tot) with pytest.raises(ZeroDivisionError): c.recreate_error_locally(f) assert f.status == "error" def test_recreate_error_not_error(c): f = c.submit(dec, 2) with pytest.raises(ValueError, match="No errored futures passed"): c.recreate_error_locally(f) @gen_cluster(client=True) async def test_recreate_task_delayed(c, s, a, b): x0 = delayed(dec)(2) y0 = delayed(dec)(2) x = delayed(div)(1, x0) y = delayed(div)(1, y0) tot = delayed(sum)([x, y]) f = c.compute(tot) assert f.status == "pending" function, args, kwargs = await c._get_components_from_future(f) assert f.status == "finished" assert function.__name__ == "sum" assert args == ([1, 1],) assert function(*args, **kwargs) == 2 @gen_cluster(client=True) async def test_recreate_task_futures(c, s, a, b): x0 = c.submit(dec, 2) y0 = c.submit(dec, 2) x = c.submit(div, 1, x0) y = c.submit(div, 1, y0) tot = c.submit(sum, [x, y]) f = c.compute(tot) assert f.status == "pending" function, args, kwargs = await c._get_components_from_future(f) assert f.status == "finished" assert function.__name__ == "sum" assert args == ([1, 1],) assert function(*args, **kwargs) == 2 @gen_cluster(client=True) async def test_recreate_task_collection(c, s, a, b): b = db.range(10, npartitions=4) b = b.map(lambda x: int(3628800 / (x + 1))) b = b.persist() f = c.compute(b) function, args, kwargs = await c._get_components_from_future(f) assert function(*args, **kwargs) == [ 3628800, 1814400, 1209600, 907200, 725760, 604800, 518400, 453600, 403200, 362880, ] dd = pytest.importorskip("dask.dataframe") import pandas as pd df = dd.from_pandas(pd.DataFrame({"a": [0, 1, 2, 3, 4]}), chunksize=2) df2 = df.a.map(lambda x: x + 1) f = c.compute(df2) function, args, kwargs = await c._get_components_from_future(f) expected = pd.DataFrame({"a": [1, 2, 3, 4, 5]})["a"] assert function(*args, **kwargs).equals(expected) # with persist df3 = c.persist(df2) # recreate_task_locally only works with futures with pytest.raises(AttributeError): function, args, kwargs = await c._get_components_from_future(df3) f = c.compute(df3) function, args, kwargs = await c._get_components_from_future(f) assert function(*args, **kwargs).equals(expected) @gen_cluster(client=True) async def test_recreate_task_array(c, s, a, b): da = pytest.importorskip("dask.array") z = (da.zeros((10, 10), chunks=10) + 1).sum() f = c.compute(z) function, args, kwargs = await c._get_components_from_future(f) assert function(*args, **kwargs) == 100 def test_recreate_task_sync(c): x0 = c.submit(dec, 2) y0 = c.submit(dec, 2) x = c.submit(div, 1, x0) y = c.submit(div, 1, y0) tot = c.submit(sum, [x, y]) f = c.compute(tot) assert c.recreate_task_locally(f) == 2 @gen_cluster(client=True) async def test_retire_workers(c, s, a, b): assert set(s.workers) == {a.address, b.address} await c.retire_workers(workers=[a.address], close_workers=True) assert set(s.workers) == {b.address} while a.status != Status.closed: await asyncio.sleep(0.01) class MyException(Exception): pass @gen_cluster(client=True) async def test_robust_unserializable(c, s, a, b): class Foo: def __getstate__(self): raise MyException() with pytest.raises(MyException): future = c.submit(identity, Foo()) futures = c.map(inc, range(10)) results = await c.gather(futures) assert results == list(map(inc, range(10))) assert a.data and b.data @gen_cluster(client=True) async def test_robust_undeserializable(c, s, a, b): class Foo: def __getstate__(self): return 1 def __setstate__(self, state): raise MyException("hello") future = c.submit(identity, Foo()) with pytest.raises(MyException): await future futures = c.map(inc, range(10)) results = await c.gather(futures) assert results == list(map(inc, range(10))) assert a.data and b.data @gen_cluster(client=True) async def test_robust_undeserializable_function(c, s, a, b): class Foo: def __getstate__(self): return 1 def __setstate__(self, state): raise MyException("hello") def __call__(self, *args): return 1 future = c.submit(Foo(), 1) with pytest.raises(MyException): await future futures = c.map(inc, range(10)) results = await c.gather(futures) assert results == list(map(inc, range(10))) assert a.data and b.data @gen_cluster(client=True) async def test_fire_and_forget(c, s, a, b): future = c.submit(slowinc, 1, delay=0.1) import distributed def f(x): distributed.foo = 123 try: fire_and_forget(c.submit(f, future)) while not hasattr(distributed, "foo"): await asyncio.sleep(0.01) assert distributed.foo == 123 finally: del distributed.foo while len(s.tasks) > 1: await asyncio.sleep(0.01) assert set(s.who_wants) == {future.key} assert set(s.tasks) == {future.key} @gen_cluster(client=True) async def test_fire_and_forget_err(c, s, a, b): fire_and_forget(c.submit(div, 1, 0)) await asyncio.sleep(0.1) # erred task should clear out quickly start = time() while s.tasks: await asyncio.sleep(0.01) assert time() < start + 1 def test_quiet_client_close(loop): with captured_logger(logging.getLogger("distributed")) as logger: with Client( loop=loop, processes=False, dashboard_address=":0", threads_per_worker=4, ) as c: futures = c.map(slowinc, range(1000), delay=0.01) sleep(0.200) # stop part-way sleep(0.1) # let things settle out = logger.getvalue() lines = out.strip().split("\n") assert len(lines) <= 2 for line in lines: assert ( not line or "Reconnecting" in line or "garbage" in line or set(line) == {"-"} ), line @pytest.mark.slow def test_quiet_client_close_when_cluster_is_closed_before_client(loop): with captured_logger(logging.getLogger("tornado.application")) as logger: cluster = LocalCluster(loop=loop, n_workers=1, dashboard_address=":0") client = Client(cluster, loop=loop) cluster.close() client.close() out = logger.getvalue() assert "CancelledError" not in out @gen_cluster() async def test_close(s, a, b): c = await Client(s.address, asynchronous=True) future = c.submit(inc, 1) await wait(future) assert c.id in s.wants_what await c.close() while c.id in s.wants_what or s.tasks: await asyncio.sleep(0.01) def test_threadsafe(c): def f(_): d = deque(maxlen=50) for i in range(100): future = c.submit(inc, random.randint(0, 100)) d.append(future) sleep(0.001) c.gather(list(d)) total = c.submit(sum, list(d)) return total.result() from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(20) as e: results = list(e.map(f, range(20))) assert results and all(results) del results @pytest.mark.slow def test_threadsafe_get(c): da = pytest.importorskip("dask.array") x = da.arange(100, chunks=(10,)) def f(_): total = 0 for i in range(20): total += (x + random.randint(0, 20)).sum().compute() sleep(0.001) return total from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(30) as e: results = list(e.map(f, range(30))) assert results and all(results) @pytest.mark.slow def test_threadsafe_compute(c): da = pytest.importorskip("dask.array") x = da.arange(100, chunks=(10,)) def f(_): total = 0 for i in range(20): future = c.compute((x + random.randint(0, 20)).sum()) total += future.result() sleep(0.001) return total from concurrent.futures import ThreadPoolExecutor e = ThreadPoolExecutor(30) results = list(e.map(f, range(30))) assert results and all(results) @gen_cluster(client=True) async def test_identity(c, s, a, b): assert c.id.lower().startswith("client") assert a.id.lower().startswith("worker") assert b.id.lower().startswith("worker") assert s.id.lower().startswith("scheduler") @gen_cluster(client=True, nthreads=[("127.0.0.1", 4)] * 2) async def test_get_client(c, s, a, b): assert get_client() is c assert c.asynchronous def f(x): client = get_client() future = client.submit(inc, x) import distributed assert not client.asynchronous assert client is distributed.tmp_client return future.result() import distributed distributed.tmp_client = c try: futures = c.map(f, range(5)) results = await c.gather(futures) assert results == list(map(inc, range(5))) finally: del distributed.tmp_client def test_get_client_no_cluster(): # Clean up any global workers added by other tests. This test requires that # there are no global workers. Worker._instances.clear() msg = "No global client found and no address provided" with pytest.raises(ValueError, match=fr"^{msg}$"): get_client() @gen_cluster(client=True) async def test_serialize_collections(c, s, a, b): da = pytest.importorskip("dask.array") x = da.arange(10, chunks=(5,)).persist() def f(x): assert isinstance(x, da.Array) return x.sum().compute() future = c.submit(f, x) result = await future assert result == sum(range(10)) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 1) async def test_secede_simple(c, s, a): def f(): client = get_client() secede() return client.submit(inc, 1).result() result = await c.submit(f) assert result == 2 @gen_cluster(client=True) async def test_secede_balances(c, s, a, b): """Ensure that tasks scheduled from a seceded thread can be scheduled elsewhere""" def f(x): client = get_client() secede() futures = client.map(inc, range(10), pure=False) total = client.submit(sum, futures).result() return total futures = c.map(f, range(100)) results = await c.gather(futures) assert a.executed_count + b.executed_count == 1100 assert a.executed_count > 200 assert b.executed_count > 200 assert results == [sum(map(inc, range(10)))] * 100 @gen_cluster(client=True) async def test_sub_submit_priority(c, s, a, b): def func(): client = get_client() f = client.submit(slowinc, 1, delay=0.5, key="slowinc") client.gather(f) future = c.submit(func, key="f") while len(s.tasks) != 2: await asyncio.sleep(0.001) # lower values schedule first assert s.tasks["f"].priority > s.tasks["slowinc"].priority, ( s.tasks["f"].priority, s.tasks["slowinc"].priority, ) def test_get_client_sync(c, s, a, b): results = c.run(lambda: get_worker().scheduler.address) assert results == {w["address"]: s["address"] for w in [a, b]} results = c.run(lambda: get_client().scheduler.address) assert results == {w["address"]: s["address"] for w in [a, b]} @gen_cluster(client=True) async def test_serialize_collections_of_futures(c, s, a, b): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") from dask.dataframe.utils import assert_eq df = pd.DataFrame({"x": [1, 2, 3]}) ddf = dd.from_pandas(df, npartitions=2).persist() future = await c.scatter(ddf) ddf2 = await future df2 = await c.compute(ddf2) assert_eq(df, df2) def test_serialize_collections_of_futures_sync(c): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") from dask.dataframe.utils import assert_eq df = pd.DataFrame({"x": [1, 2, 3]}) ddf = dd.from_pandas(df, npartitions=2).persist() future = c.scatter(ddf) result = future.result() assert_eq(result.compute(), df) assert future.type == dd.DataFrame assert c.submit(lambda x, y: assert_eq(x.compute(), y), future, df).result() def _dynamic_workload(x, delay=0.01): if delay == "random": sleep(random.random() / 2) else: sleep(delay) if x > 4: return 4 secede() client = get_client() futures = client.map( _dynamic_workload, [x + i + 1 for i in range(2)], pure=False, delay=delay ) total = client.submit(sum, futures) return total.result() def test_dynamic_workloads_sync(c): future = c.submit(_dynamic_workload, 0, delay=0.02) assert future.result(timeout=20) == 52 @pytest.mark.slow def test_dynamic_workloads_sync_random(c): future = c.submit(_dynamic_workload, 0, delay="random") assert future.result(timeout=20) == 52 @pytest.mark.xfail(COMPILED, reason="Fails with cythonized scheduler") @gen_cluster(client=True) async def test_bytes_keys(c, s, a, b): key = b"inc-123" future = c.submit(inc, 1, key=key) result = await future assert type(future.key) is bytes assert set(s.tasks) == {key} assert key in a.data or key in b.data assert result == 2 @gen_cluster(client=True) async def test_unicode_ascii_keys(c, s, a, b): uni_type = str key = "inc-123" future = c.submit(inc, 1, key=key) result = await future assert type(future.key) is uni_type assert set(s.tasks) == {key} assert key in a.data or key in b.data assert result == 2 @gen_cluster(client=True) async def test_unicode_keys(c, s, a, b): uni_type = str key = "inc-123\u03bc" future = c.submit(inc, 1, key=key) result = await future assert type(future.key) is uni_type assert set(s.tasks) == {key} assert key in a.data or key in b.data assert result == 2 future2 = c.submit(inc, future) result2 = await future2 assert result2 == 3 future3 = await c.scatter({"data-123": 123}) result3 = await future3["data-123"] assert result3 == 123 def test_use_synchronous_client_in_async_context(loop, c): async def f(): x = await c.scatter(123) y = c.submit(inc, x) z = await c.gather(y) return z z = sync(loop, f) assert z == 124 def test_quiet_quit_when_cluster_leaves(loop_in_thread): loop = loop_in_thread with LocalCluster(loop=loop, dashboard_address=":0", silence_logs=False) as cluster: with captured_logger("distributed.comm") as sio: with Client(cluster, loop=loop) as client: futures = client.map(lambda x: x + 1, range(10)) sleep(0.05) cluster.close() sleep(0.05) text = sio.getvalue() assert not text def test_warn_executor(loop, s, a, b): with warnings.catch_warnings(record=True) as record: with Executor(s["address"], loop=loop) as c: pass assert any("Client" in str(r.message) for r in record) @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_future(c, s, a, b): x = c.submit(slowdec, 1, delay=0.5) future = c.submit(slowinc, 1, delay=0.5) await asyncio.sleep(0.1) results = await asyncio.gather( c.call_stack(future), c.call_stack(keys=[future.key]) ) assert all(list(first(result.values())) == [future.key] for result in results) assert results[0] == results[1] result = results[0] ts = a.tasks.get(future.key) if ts is not None and ts.state == "executing": w = a else: w = b assert list(result) == [w.address] assert list(result[w.address]) == [future.key] assert "slowinc" in str(result) assert "slowdec" not in str(result) @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_all(c, s, a, b): future = c.submit(slowinc, 1, delay=0.8) while not a.executing_count and not b.executing_count: await asyncio.sleep(0.01) result = await c.call_stack() w = a if a.executing_count else b assert list(result) == [w.address] assert list(result[w.address]) == [future.key] assert "slowinc" in str(result) @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_collections(c, s, a, b): da = pytest.importorskip("dask.array") x = da.random.random(100, chunks=(10,)).map_blocks(slowinc, delay=0.5).persist() while not a.executing_count and not b.executing_count: await asyncio.sleep(0.001) result = await c.call_stack(x) assert result @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_collections_all(c, s, a, b): da = pytest.importorskip("dask.array") x = da.random.random(100, chunks=(10,)).map_blocks(slowinc, delay=0.5).persist() while not a.executing_count and not b.executing_count: await asyncio.sleep(0.001) result = await c.call_stack() assert result @pytest.mark.flaky(condition=WINDOWS, reruns=10, reruns_delay=5) @gen_cluster(client=True, worker_kwargs={"profile_cycle_interval": "100ms"}) async def test_profile(c, s, a, b): futures = c.map(slowinc, range(10), delay=0.05, workers=a.address) await wait(futures) x = await c.profile(start=time() + 10, stop=time() + 20) assert not x["count"] x = await c.profile(start=0, stop=time()) assert ( x["count"] == sum(p["count"] for _, p in a.profile_history) + a.profile_recent["count"] ) y = await c.profile(start=time() - 0.300, stop=time()) assert 0 < y["count"] < x["count"] assert not any(p["count"] for _, p in b.profile_history) result = await c.profile(workers=b.address) assert not result["count"] @gen_cluster(client=True, worker_kwargs={"profile_cycle_interval": "100ms"}) async def test_profile_keys(c, s, a, b): x = c.map(slowinc, range(10), delay=0.05, workers=a.address) y = c.map(slowdec, range(10), delay=0.05, workers=a.address) await wait(x + y) xp = await c.profile("slowinc") yp = await c.profile("slowdec") p = await c.profile() assert p["count"] == xp["count"] + yp["count"] with captured_logger(logging.getLogger("distributed")) as logger: prof = await c.profile("does-not-exist") assert prof == profile.create() out = logger.getvalue() assert not out @gen_cluster() async def test_client_with_name(s, a, b): with captured_logger("distributed.scheduler") as sio: client = await Client(s.address, asynchronous=True, name="foo") assert "foo" in client.id await client.close() text = sio.getvalue() assert "foo" in text @gen_cluster(client=True) async def test_future_defaults_to_default_client(c, s, a, b): x = c.submit(inc, 1) await wait(x) future = Future(x.key) assert future.client is c @gen_cluster(client=True) async def test_future_auto_inform(c, s, a, b): x = c.submit(inc, 1) await wait(x) client = await Client(s.address, asynchronous=True) future = Future(x.key, client) while future.status != "finished": await asyncio.sleep(0.01) await client.close() def test_client_async_before_loop_starts(): with pristine_loop() as loop: client = Client(asynchronous=True, loop=loop) assert client.asynchronous client.close() @pytest.mark.slow @gen_cluster(client=True, Worker=Nanny, timeout=60, nthreads=[("127.0.0.1", 3)] * 2) async def test_nested_compute(c, s, a, b): def fib(x): assert get_worker().get_current_task() if x < 2: return x a = delayed(fib)(x - 1) b = delayed(fib)(x - 2) c = a + b return c.compute() future = c.submit(fib, 8) result = await future assert result == 21 assert len(s.transition_log) > 50 @gen_cluster(client=True) async def test_task_metadata(c, s, a, b): await c.set_metadata("x", 1) result = await c.get_metadata("x") assert result == 1 future = c.submit(inc, 1) key = future.key await wait(future) await c.set_metadata(key, 123) result = await c.get_metadata(key) assert result == 123 del future while key in s.tasks: await asyncio.sleep(0.01) with pytest.raises(KeyError): await c.get_metadata(key) result = await c.get_metadata(key, None) assert result is None await c.set_metadata(["x", "a"], 1) result = await c.get_metadata("x") assert result == {"a": 1} await c.set_metadata(["x", "b"], 2) result = await c.get_metadata("x") assert result == {"a": 1, "b": 2} result = await c.get_metadata(["x", "a"]) assert result == 1 await c.set_metadata(["x", "a", "c", "d"], 1) result = await c.get_metadata("x") assert result == {"a": {"c": {"d": 1}}, "b": 2} @gen_cluster(client=True, Worker=Nanny) async def test_logs(c, s, a, b): await wait(c.map(inc, range(5))) logs = await c.get_scheduler_logs(n=5) assert logs for _, msg in logs: assert "distributed.scheduler" in msg w_logs = await c.get_worker_logs(n=5) assert set(w_logs.keys()) == {a.worker_address, b.worker_address} for log in w_logs.values(): for _, msg in log: assert "distributed.worker" in msg n_logs = await c.get_worker_logs(nanny=True) assert set(n_logs.keys()) == {a.worker_address, b.worker_address} for log in n_logs.values(): for _, msg in log: assert "distributed.nanny" in msg n_logs = await c.get_worker_logs(nanny=True, workers=[a.worker_address]) assert set(n_logs.keys()) == {a.worker_address} for log in n_logs.values(): for _, msg in log: assert "distributed.nanny" in msg @gen_cluster(client=True) async def test_avoid_delayed_finalize(c, s, a, b): x = delayed(inc)(1) future = c.compute(x) result = await future assert result == 2 assert list(s.tasks) == [future.key] == [x.key] @gen_cluster() async def test_config_scheduler_address(s, a, b): with dask.config.set({"scheduler-address": s.address}): with captured_logger("distributed.client") as sio: c = await Client(asynchronous=True) assert c.scheduler.address == s.address text = sio.getvalue() assert s.address in text await c.close() @gen_cluster(client=True) async def test_warn_when_submitting_large_values(c, s, a, b): with warnings.catch_warnings(record=True) as record: future = c.submit(lambda x: x + 1, b"0" * 2000000) text = str(record[0].message) assert "2.00 MB" in text or "1.91 MiB" in text assert "large" in text assert "..." in text assert "'000" in text assert "000'" in text assert len(text) < 2000 with warnings.catch_warnings(record=True) as record: data = b"0" * 2000000 for i in range(10): future = c.submit(lambda x, y: x, data, i) assert len(record) < 2 @gen_cluster(client=True) async def test_unhashable_function(c, s, a, b): func = _UnhashableCallable() result = await c.submit(func, 1) assert result == 2 @gen_cluster() async def test_client_name(s, a, b): with dask.config.set({"client-name": "hello-world"}): c = await Client(s.address, asynchronous=True) assert any("hello-world" in name for name in list(s.clients)) await c.close() def test_client_doesnt_close_given_loop(loop_in_thread, s, a, b): with Client(s["address"], loop=loop_in_thread) as c: assert c.submit(inc, 1).result() == 2 with Client(s["address"], loop=loop_in_thread) as c: assert c.submit(inc, 2).result() == 3 @gen_cluster(client=True, nthreads=[]) async def test_quiet_scheduler_loss(c, s): c._periodic_callbacks["scheduler-info"].interval = 10 with captured_logger(logging.getLogger("distributed.client")) as logger: await s.close() await c._update_scheduler_info() text = logger.getvalue() assert "BrokenPipeError" not in text def test_dashboard_link(loop, monkeypatch): monkeypatch.setenv("USER", "myusername") with cluster(scheduler_kwargs={"dashboard_address": ":12355"}) as (s, [a, b]): with Client(s["address"], loop=loop) as c: with dask.config.set( {"distributed.dashboard.link": "{scheme}://foo-{USER}:{port}/status"} ): link = "http://foo-myusername:12355/status" assert link == c.dashboard_link text = c._repr_html_() assert link in text @gen_test() async def test_dashboard_link_inproc(): async with Client(processes=False, asynchronous=True, dashboard_address=":0") as c: with dask.config.set({"distributed.dashboard.link": "{host}"}): assert "/" not in c.dashboard_link @gen_test() async def test_client_timeout_2(): with dask.config.set({"distributed.comm.timeouts.connect": "10ms"}): start = time() c = Client("127.0.0.1:3755", asynchronous=True) with pytest.raises((TimeoutError, IOError)): await c stop = time() assert c.status == "closed" await c.close() assert stop - start < 1 @gen_test() async def test_client_active_bad_port(): import tornado.httpserver import tornado.web application = tornado.web.Application([(r"/", tornado.web.RequestHandler)]) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8080) with dask.config.set({"distributed.comm.timeouts.connect": "10ms"}): c = Client("127.0.0.1:8080", asynchronous=True) with pytest.raises((TimeoutError, IOError)): await c await c._close(fast=True) http_server.stop() @pytest.mark.parametrize("direct", [True, False]) def test_turn_off_pickle(direct): @gen_cluster() async def test(s, a, b): np = pytest.importorskip("numpy") async with Client( s.address, asynchronous=True, serializers=["dask", "msgpack"] ) as c: assert (await c.submit(inc, 1)) == 2 await c.submit(np.ones, 5) await c.scatter(1) # Can't send complex data with pytest.raises(TypeError): future = await c.scatter(inc) # can send complex tasks (this uses pickle regardless) future = c.submit(lambda x: x, inc) await wait(future) # but can't receive complex results with pytest.raises(TypeError): await c.gather(future, direct=direct) # Run works result = await c.run(lambda: 1) assert list(result.values()) == [1, 1] result = await c.run_on_scheduler(lambda: 1) assert result == 1 # But not with complex return values with pytest.raises(TypeError): await c.run(lambda: inc) with pytest.raises(TypeError): await c.run_on_scheduler(lambda: inc) test() @gen_cluster() async def test_de_serialization(s, a, b): np = pytest.importorskip("numpy") c = await Client( s.address, asynchronous=True, serializers=["msgpack", "pickle"], deserializers=["msgpack"], ) try: # Can send complex data future = await c.scatter(np.ones(5)) # But can not retrieve it with pytest.raises(TypeError): result = await future finally: await c.close() @gen_cluster() async def test_de_serialization_none(s, a, b): np = pytest.importorskip("numpy") c = await Client(s.address, asynchronous=True, deserializers=["msgpack"]) try: # Can send complex data future = await c.scatter(np.ones(5)) # But can not retrieve it with pytest.raises(TypeError): result = await future finally: await c.close() @gen_cluster() async def test_client_repr_closed(s, a, b): c = await Client(s.address, asynchronous=True) await c.close() c._repr_html_() def test_client_repr_closed_sync(loop): with Client(loop=loop, processes=False, dashboard_address=":0") as c: pass c._repr_html_() @pytest.mark.xfail(reason="https://github.com/dask/dask/pull/6807") @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)]) async def test_nested_prioritization(c, s, w): x = delayed(inc)(1, dask_key_name=("a", 2)) y = delayed(inc)(2, dask_key_name=("a", 10)) o = dask.order.order(merge(x.__dask_graph__(), y.__dask_graph__())) fx, fy = c.compute([x, y]) await wait([fx, fy]) assert (o[x.key] < o[y.key]) == ( s.tasks[stringify(fx.key)].priority < s.tasks[stringify(fy.key)].priority ) @gen_cluster(client=True) async def test_scatter_error_cancel(c, s, a, b): # https://github.com/dask/distributed/issues/2038 def bad_fn(x): raise Exception("lol") x = await c.scatter(1) y = c.submit(bad_fn, x) del x await wait(y) assert y.status == "error" await asyncio.sleep(0.1) assert y.status == "error" # not cancelled @pytest.mark.xfail(reason="GH#5409 Dask-Default-Threads are frequently detected") def test_no_threads_lingering(): if threading.active_count() < 40: return active = dict(threading._active) print(f"==== Found {len(active)} active threads: ====") for t in active.values(): print(t) assert False @gen_cluster() async def test_direct_async(s, a, b): c = await Client(s.address, asynchronous=True, direct_to_workers=True) assert c.direct_to_workers await c.close() c = await Client(s.address, asynchronous=True, direct_to_workers=False) assert not c.direct_to_workers await c.close() def test_direct_sync(c): assert not c.direct_to_workers def f(): return get_client().direct_to_workers assert c.submit(f).result() @gen_cluster() async def test_mixing_clients(s, a, b): c1 = await Client(s.address, asynchronous=True) c2 = await Client(s.address, asynchronous=True) future = c1.submit(inc, 1) with pytest.raises(ValueError): c2.submit(inc, future) assert not c2.futures # Don't create Futures on second Client await c1.close() await c2.close() @gen_cluster(client=True) async def test_tuple_keys(c, s, a, b): x = dask.delayed(inc)(1, dask_key_name=("x", 1)) y = dask.delayed(inc)(x, dask_key_name=("y", 1)) future = c.compute(y) assert (await future) == 3 @gen_cluster(client=True) async def test_multiple_scatter(c, s, a, b): futures = await asyncio.gather(*(c.scatter(1, direct=True) for _ in range(5))) x = await futures[0] x = await futures[0] @gen_cluster(client=True) async def test_map_large_kwargs_in_graph(c, s, a, b): np = pytest.importorskip("numpy") x = np.random.random(100000) futures = c.map(lambda a, b: a + b, range(100), b=x) while not s.tasks: await asyncio.sleep(0.01) assert len(s.tasks) == 101 assert any(k.startswith("ndarray") for k in s.tasks) @gen_cluster(client=True) async def test_retry(c, s, a, b): def f(): assert dask.config.get("foo") with dask.config.set(foo=False): future = c.submit(f) with pytest.raises(AssertionError): await future with dask.config.set(foo=True): await future.retry() await future @gen_cluster(client=True) async def test_retry_dependencies(c, s, a, b): def f(): return dask.config.get("foo") x = c.submit(f) y = c.submit(inc, x) with pytest.raises(KeyError): await y with dask.config.set(foo=100): await y.retry() result = await y assert result == 101 await y.retry() await x.retry() result = await y assert result == 101 @gen_cluster(client=True) async def test_released_dependencies(c, s, a, b): def f(x): return dask.config.get("foo") + 1 x = c.submit(inc, 1, key="x") y = c.submit(f, x, key="y") del x with pytest.raises(KeyError): await y with dask.config.set(foo=100): await y.retry() result = await y assert result == 101 @gen_cluster(client=True, clean_kwargs={"threads": False}) async def test_profile_bokeh(c, s, a, b): pytest.importorskip("bokeh.plotting") from bokeh.model import Model await c.gather(c.map(slowinc, range(10), delay=0.2)) state, figure = await c.profile(plot=True) assert isinstance(figure, Model) with tmpfile("html") as fn: try: await c.profile(filename=fn) except PermissionError: if WINDOWS: pytest.xfail() assert os.path.exists(fn) @gen_cluster(client=True) async def test_get_mix_futures_and_SubgraphCallable(c, s, a, b): future = c.submit(add, 1, 2) subgraph = SubgraphCallable( {"_2": (add, "_0", "_1"), "_3": (add, future, "_2")}, "_3", ("_0", "_1") ) dsk = {"a": 1, "b": 2, "c": (subgraph, "a", "b"), "d": (subgraph, "c", "b")} future2 = c.get(dsk, "d", sync=False) result = await future2 assert result == 11 # Nested subgraphs subgraph2 = SubgraphCallable( { "_2": (subgraph, "_0", "_1"), "_3": (subgraph, "_2", "_1"), "_4": (add, "_3", future2), }, "_4", ("_0", "_1"), ) dsk2 = {"e": 1, "f": 2, "g": (subgraph2, "e", "f")} result = await c.get(dsk2, "g", sync=False) assert result == 22 @gen_cluster(client=True) async def test_get_mix_futures_and_SubgraphCallable_dask_dataframe(c, s, a, b): dd = pytest.importorskip("dask.dataframe") import pandas as pd df = pd.DataFrame({"x": range(1, 11)}) ddf = dd.from_pandas(df, npartitions=2).persist() ddf = ddf.map_partitions(lambda x: x) ddf["x"] = ddf["x"].astype("f8") ddf = ddf.map_partitions(lambda x: x) ddf["x"] = ddf["x"].astype("f8") result = await c.compute(ddf) assert result.equals(df.astype("f8")) def test_direct_to_workers(s, loop): with Client(s["address"], loop=loop, direct_to_workers=True) as client: future = client.scatter(1) future.result() resp = client.run_on_scheduler(lambda dask_scheduler: dask_scheduler.events) assert "gather" not in str(resp) @gen_cluster(client=True) async def test_instances(c, s, a, b): assert list(Client._instances) == [c] assert list(Scheduler._instances) == [s] assert set(Worker._instances) == {a, b} @gen_cluster(client=True) async def test_wait_for_workers(c, s, a, b): future = asyncio.ensure_future(c.wait_for_workers(n_workers=3)) await asyncio.sleep(0.22) # 2 chances assert not future.done() w = await Worker(s.address) start = time() await future assert time() < start + 1 await w.close() with pytest.raises(TimeoutError) as info: await c.wait_for_workers(n_workers=10, timeout="1 ms") assert "2/10" in str(info.value).replace(" ", "") assert "1 ms" in str(info.value) @pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows") @pytest.mark.asyncio @pytest.mark.parametrize("Worker", [Worker, Nanny]) async def test_file_descriptors_dont_leak(Worker): pytest.importorskip("pandas") df = dask.datasets.timeseries(freq="10s", dtypes={"x": int, "y": float}) proc = psutil.Process() before = proc.num_fds() async with Scheduler(dashboard_address=":0") as s: async with Worker(s.address), Worker(s.address), Client( s.address, asynchronous=True ): assert proc.num_fds() > before await df.sum().persist() start = time() while proc.num_fds() > before: await asyncio.sleep(0.01) assert time() < start + 10, (before, proc.num_fds()) @gen_test() async def test_dashboard_link_cluster(): class MyCluster(LocalCluster): @property def dashboard_link(self): return "http://foo.com" async with MyCluster( processes=False, asynchronous=True, dashboard_address=":0" ) as cluster: async with Client(cluster, asynchronous=True) as client: assert "http://foo.com" in client._repr_html_() @gen_test() async def test_shutdown(): async with Scheduler(dashboard_address=":0") as s: async with Worker(s.address) as w: async with Client(s.address, asynchronous=True) as c: await c.shutdown() assert s.status == Status.closed assert w.status == Status.closed @pytest.mark.asyncio async def test_shutdown_localcluster(cleanup): async with LocalCluster( n_workers=1, asynchronous=True, processes=False, dashboard_address=":0" ) as lc: async with Client(lc, asynchronous=True) as c: await c.shutdown() assert lc.scheduler.status == Status.closed @gen_test() async def test_config_inherited_by_subprocess(): with dask.config.set(foo=100): async with LocalCluster( n_workers=1, asynchronous=True, processes=True, dashboard_address=":0", ) as lc: async with Client(lc, asynchronous=True) as c: assert await c.submit(dask.config.get, "foo") == 100 @gen_cluster(client=True) async def test_futures_of_sorted(c, s, a, b): pytest.importorskip("dask.dataframe") df = await dask.datasets.timeseries(dtypes={"x": int}).persist() futures = futures_of(df) for k, f in zip(df.__dask_keys__(), futures): assert str(k) in str(f) @gen_cluster(client=True, worker_kwargs={"profile_cycle_interval": "10ms"}) async def test_profile_server(c, s, a, b): for i in range(5): try: x = c.map(slowinc, range(10), delay=0.01, workers=a.address, pure=False) await wait(x) await asyncio.gather( c.run(slowinc, 1, delay=0.5), c.run_on_scheduler(slowdec, 1, delay=0.5) ) p = await c.profile(server=True) # All worker servers assert "slowinc" in str(p) p = await c.profile(scheduler=True) # Scheduler assert "slowdec" in str(p) except AssertionError: if i == 4: raise else: pass else: break @gen_cluster(client=True) async def test_await_future(c, s, a, b): future = c.submit(inc, 1) async def f(): # flake8: noqa result = await future assert result == 2 await f() future = c.submit(div, 1, 0) async def f(): with pytest.raises(ZeroDivisionError): await future await f() @gen_cluster(client=True) async def test_as_completed_async_for(c, s, a, b): futures = c.map(inc, range(10)) ac = as_completed(futures) results = [] async def f(): async for future in ac: result = await future results.append(result) await f() assert set(results) == set(range(1, 11)) @gen_cluster(client=True) async def test_as_completed_async_for_results(c, s, a, b): futures = c.map(inc, range(10)) ac = as_completed(futures, with_results=True) results = [] async def f(): async for future, result in ac: results.append(result) await f() assert set(results) == set(range(1, 11)) assert not s.counters["op"].components[0]["gather"] @gen_cluster(client=True) async def test_as_completed_async_for_cancel(c, s, a, b): x = c.submit(inc, 1) y = c.submit(sleep, 0.3) ac = as_completed([x, y]) async def _(): await asyncio.sleep(0.1) await y.cancel(asynchronous=True) c.loop.add_callback(_) L = [] async def f(): async for future in ac: L.append(future) await f() assert L == [x, y] @gen_test() async def test_async_with(): async with Client(processes=False, dashboard_address=":0", asynchronous=True) as c: assert await c.submit(lambda x: x + 1, 10) == 11 assert c.status == "closed" assert c.cluster.status == Status.closed def test_client_sync_with_async_def(loop): async def ff(): await asyncio.sleep(0.01) return 1 with cluster() as (s, [a, b]): with Client(s["address"], loop=loop) as c: assert sync(loop, ff) == 1 assert c.sync(ff) == 1 @pytest.mark.skip(reason="known intermittent failure") @gen_cluster(client=True) async def test_dont_hold_on_to_large_messages(c, s, a, b): np = pytest.importorskip("numpy") da = pytest.importorskip("dask.array") x = np.random.random(1000000) xr = weakref.ref(x) d = da.from_array(x, chunks=(100000,)) d = d.persist() del x start = time() while xr() is not None: if time() > start + 5: # Help diagnosing from types import FrameType x = xr() if x is not None: del x rc = sys.getrefcount(xr()) refs = gc.get_referrers(xr()) print("refs to x:", rc, refs, gc.isenabled()) frames = [r for r in refs if isinstance(r, FrameType)] for i, f in enumerate(frames): print( "frames #%d:" % i, f.f_code.co_name, f.f_code.co_filename, sorted(f.f_locals), ) pytest.fail("array should have been destroyed") await asyncio.sleep(0.200) @gen_cluster(client=True) async def test_run_scheduler_async_def(c, s, a, b): async def f(dask_scheduler): await asyncio.sleep(0.01) dask_scheduler.foo = "bar" await c.run_on_scheduler(f) assert s.foo == "bar" async def f(dask_worker): await asyncio.sleep(0.01) dask_worker.foo = "bar" await c.run(f) assert a.foo == "bar" assert b.foo == "bar" @gen_cluster(client=True) async def test_run_scheduler_async_def_wait(c, s, a, b): async def f(dask_scheduler): await asyncio.sleep(0.01) dask_scheduler.foo = "bar" await c.run_on_scheduler(f, wait=False) while not hasattr(s, "foo"): await asyncio.sleep(0.01) assert s.foo == "bar" async def f(dask_worker): await asyncio.sleep(0.01) dask_worker.foo = "bar" await c.run(f, wait=False) while not hasattr(a, "foo") or not hasattr(b, "foo"): await asyncio.sleep(0.01) assert a.foo == "bar" assert b.foo == "bar" @pytest.mark.skipif(WINDOWS, reason="frequently kills off the whole test suite") @gen_cluster(client=True, nthreads=[("127.0.0.1", 2)] * 2) async def test_performance_report(c, s, a, b): pytest.importorskip("bokeh") da = pytest.importorskip("dask.array") async def f(stacklevel, mode=None): """ We wrap this in a function so that the assertions aren't in the performanace report itself Also, we want this comment to appear """ x = da.random.random((1000, 1000), chunks=(100, 100)) with tmpfile(extension="html") as fn: async with performance_report( filename=fn, stacklevel=stacklevel, mode=mode ): await c.compute((x + x.T).sum()) with open(fn) as f: data = f.read() return data # Ensure default kwarg maintains backward compatability data = await f(stacklevel=1) assert "Also, we want this comment to appear" in data assert "bokeh" in data assert "random" in data assert "Dask Performance Report" in data assert "x = da.random" in data assert "Threads: 4" in data assert "distributed.scheduler - INFO - Clear task state" in data assert dask.__version__ in data # stacklevel=2 captures code two frames back -- which in this case # is the testing function data = await f(stacklevel=2) assert "async def test_performance_report(c, s, a, b):" in data assert "Dask Performance Report" in data # stacklevel=0 or lower is overridden to stacklevel=1 so we don't see # distributed internals data = await f(stacklevel=0) assert "Also, we want this comment to appear" in data assert "Dask Performance Report" in data data = await f(stacklevel=1, mode="inline") assert "cdn.bokeh.org" not in data data = await f(stacklevel=1, mode="cdn") assert "cdn.bokeh.org" in data @gen_cluster(nthreads=[]) async def test_client_gather_semaphore_loop(s): async with Client(s.address, asynchronous=True) as c: assert c._gather_semaphore._loop is c.loop.asyncio_loop @gen_cluster(client=True) async def test_as_completed_condition_loop(c, s, a, b): seq = c.map(inc, range(5)) ac = as_completed(seq) assert ac.condition._loop == c.loop.asyncio_loop def test_client_connectionpool_semaphore_loop(s, a, b): with Client(s["address"]) as c: assert c.rpc.semaphore._loop is c.loop.asyncio_loop @pytest.mark.slow @gen_cluster(nthreads=[], timeout=60) async def test_mixed_compression(s): pytest.importorskip("lz4") da = pytest.importorskip("dask.array") async with Nanny( s.address, nthreads=1, config={"distributed.comm.compression": None} ): async with Nanny( s.address, nthreads=1, config={"distributed.comm.compression": "lz4"} ): async with Client(s.address, asynchronous=True) as c: await c.get_versions() x = da.ones((10000, 10000)) y = x + x.T await c.compute(y.sum()) @gen_cluster(client=True) async def test_futures_in_subgraphs(c, s, a, b): """Regression test of <https://github.com/dask/distributed/issues/4145>""" dd = pytest.importorskip("dask.dataframe") import pandas as pd ddf = dd.from_pandas( pd.DataFrame( dict( uid=range(50), enter_time=pd.date_range( start="2020-01-01", end="2020-09-01", periods=50, tz="UTC" ), ) ), npartitions=5, ) ddf = ddf[ddf.uid.isin(range(29))].persist() ddf["local_time"] = ddf.enter_time.dt.tz_convert("US/Central") ddf["day"] = ddf.enter_time.dt.day_name() ddf = await c.submit(dd.categorical.categorize, ddf, columns=["day"], index=False) @gen_cluster(client=True) async def test_get_task_metadata(c, s, a, b): # Populate task metadata await c.register_worker_plugin(TaskStateMetadataPlugin()) async with get_task_metadata() as tasks: f = c.submit(slowinc, 1) await f metadata = tasks.metadata assert f.key in metadata assert metadata[f.key] == s.tasks.get(f.key).metadata state = tasks.state assert f.key in state assert state[f.key] == "memory" assert not any(isinstance(p, CollectTaskMetaDataPlugin) for p in s.plugins) @gen_cluster(client=True) async def test_get_task_metadata_multiple(c, s, a, b): # Populate task metadata await c.register_worker_plugin(TaskStateMetadataPlugin()) # Ensure that get_task_metadata only collects metadata for # tasks which are submitted and completed within its context async with get_task_metadata() as tasks1: f1 = c.submit(slowinc, 1) await f1 async with get_task_metadata() as tasks2: f2 = c.submit(slowinc, 2) await f2 metadata1 = tasks1.metadata metadata2 = tasks2.metadata assert len(metadata1) == 2 assert sorted(metadata1.keys()) == sorted([f1.key, f2.key]) assert metadata1[f1.key] == s.tasks.get(f1.key).metadata assert metadata1[f2.key] == s.tasks.get(f2.key).metadata assert len(metadata2) == 1 assert list(metadata2.keys()) == [f2.key] assert metadata2[f2.key] == s.tasks.get(f2.key).metadata @gen_cluster(client=True) async def test_log_event(c, s, a, b): # Log an event from inside a task def foo(): get_worker().log_event("topic1", {"foo": "bar"}) assert not await c.get_events("topic1") await c.submit(foo) events = await c.get_events("topic1") assert len(events) == 1 assert events[0][1] == {"foo": "bar"} # Log an event while on the scheduler def log_scheduler(dask_scheduler): dask_scheduler.log_event("topic2", {"woo": "hoo"}) await c.run_on_scheduler(log_scheduler) events = await c.get_events("topic2") assert len(events) == 1 assert events[0][1] == {"woo": "hoo"} # Log an event from the client process await c.log_event("topic2", ("alice", "bob")) events = await c.get_events("topic2") assert len(events) == 2 assert events[1][1] == ("alice", "bob") @gen_cluster(client=True) async def test_annotations_task_state(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(qux="bar", priority=100): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all( {"qux": "bar", "priority": 100} == ts.annotations for ts in s.tasks.values() ) @pytest.mark.parametrize("fn", ["compute", "persist"]) def test_annotations_compute_time(fn): da = pytest.importorskip("dask.array") @gen_cluster(client=True) async def test(c, s, a, b): x = da.ones(10, chunks=(5,)) with dask.annotate(foo="bar"): # Turn off optimization to avoid rewriting layers and picking up annotations # that way. Instead, we want `compute`/`persist` to be able to pick them up. x = await getattr(c, fn)(x, optimize_graph=False) assert all({"foo": "bar"} == ts.annotations for ts in s.tasks.values()) test() @pytest.mark.xfail(reason="https://github.com/dask/dask/issues/7036") @gen_cluster(client=True) async def test_annotations_survive_optimization(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(foo="bar"): x = da.ones(10, chunks=(5,)) ann = x.__dask_graph__().layers[x.name].annotations assert ann is not None assert ann.get("foo", None) == "bar" (xx,) = dask.optimize(x) ann = xx.__dask_graph__().layers[x.name].annotations assert ann is not None assert ann.get("foo", None) == "bar" @gen_cluster(client=True) async def test_annotations_priorities(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(priority=15): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all("15" in str(ts.priority) for ts in s.tasks.values()) assert all(ts.priority[0] == -15 for ts in s.tasks.values()) assert all({"priority": 15} == ts.annotations for ts in s.tasks.values()) @gen_cluster(client=True) async def test_annotations_workers(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(workers=[a.address]): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all({"workers": (a.address,)} == ts.annotations for ts in s.tasks.values()) assert all({a.address} == ts.worker_restrictions for ts in s.tasks.values()) assert a.data assert not b.data @gen_cluster(client=True) async def test_annotations_retries(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(retries=2): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all(ts.retries == 2 for ts in s.tasks.values()) assert all(ts.annotations == {"retries": 2} for ts in s.tasks.values()) @gen_cluster(client=True) async def test_annotations_blockwise_unpack(c, s, a, b): da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") from dask.array.utils import assert_eq # A flaky doubling function -- need extra args because it is called before # application to establish dtype/meta. scale = varying([ZeroDivisionError("one"), ZeroDivisionError("two"), 2, 2]) def flaky_double(x): return scale() * x # A reliable double function. def reliable_double(x): return 2 * x x = da.ones(10, chunks=(5,)) # The later annotations should not override the earlier annotations with dask.annotate(retries=2): y = x.map_blocks(flaky_double, meta=np.array((), dtype=float)) with dask.annotate(retries=0): z = y.map_blocks(reliable_double, meta=np.array((), dtype=float)) with dask.config.set(optimization__fuse__active=False): z = await c.compute(z) assert_eq(z, np.ones(10) * 4.0) @gen_cluster( client=True, nthreads=[ ("127.0.0.1", 1), ("127.0.0.1", 1, {"resources": {"GPU": 1}}), ], ) async def test_annotations_resources(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(resources={"GPU": 1}): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all([{"GPU": 1} == ts.resource_restrictions for ts in s.tasks.values()]) assert all([{"resources": {"GPU": 1}} == ts.annotations for ts in s.tasks.values()]) @gen_cluster( client=True, nthreads=[ ("127.0.0.1", 1), ("127.0.0.1", 1, {"resources": {"GPU": 1}}), ], ) async def test_annotations_resources_culled(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones((2, 2, 2), chunks=1) with dask.annotate(resources={"GPU": 1}): y = x.map_blocks(lambda x0: x0, meta=x._meta) z = y[0, 0, 0] (z,) = c.compute([z], optimize_graph=False) await z # it worked! @gen_cluster(client=True) async def test_annotations_loose_restrictions(c, s, a, b): da = pytest.importorskip("dask.array") # Eventually fails if allow_other_workers=False with dask.annotate(workers=["fake"], allow_other_workers=True): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all(not ts.worker_restrictions for ts in s.tasks.values()) assert all({"fake"} == ts.host_restrictions for ts in s.tasks.values()) assert all( [ {"workers": ("fake",), "allow_other_workers": True} == ts.annotations for ts in s.tasks.values() ] ) @gen_cluster(client=True) async def test_workers_collection_restriction(c, s, a, b): da = pytest.importorskip("dask.array") future = c.compute(da.arange(10), workers=a.address) await future assert a.data and not b.data @gen_cluster(client=True, nthreads=[("127.0.0.1", 0)]) async def test_get_client_functions_spawn_clusters(c, s, a): # see gh4565 scheduler_addr = c.scheduler.address def f(x): with LocalCluster( n_workers=1, processes=False, dashboard_address=":0", worker_dashboard_address=":0", ) as cluster2: with Client(cluster2) as c1: c2 = get_client() c1_scheduler = c1.scheduler.address c2_scheduler = c2.scheduler.address assert c1_scheduler != c2_scheduler assert c2_scheduler == scheduler_addr await c.gather(c.map(f, range(2))) await a.close() c_default = default_client() assert c is c_default def test_computation_code_walk_frames(): test_function_code = inspect.getsource(test_computation_code_walk_frames) code = Client._get_computation_code() assert test_function_code == code def nested_call(): return Client._get_computation_code() assert nested_call() == inspect.getsource(nested_call) with pytest.raises(TypeError, match="Ignored modules must be a list"): with dask.config.set( {"distributed.diagnostics.computations.ignore-modules": "test_client"} ): code = Client._get_computation_code() with dask.config.set( {"distributed.diagnostics.computations.ignore-modules": ["test_client"]} ): import sys upper_frame_code = inspect.getsource(sys._getframe(1)) code = Client._get_computation_code() assert code == upper_frame_code assert nested_call() == upper_frame_code def test_computation_object_code_dask_compute(client): da = pytest.importorskip("dask.array") x = da.ones((10, 10), chunks=(3, 3)) future = x.sum().compute() y = future test_function_code = inspect.getsource(test_computation_object_code_dask_compute) def fetch_comp_code(dask_scheduler): computations = list(dask_scheduler.computations) assert len(computations) == 1 comp = computations[0] assert len(comp.code) == 1 return comp.code[0] code = client.run_on_scheduler(fetch_comp_code) assert code == test_function_code def test_computation_object_code_not_available(client): np = pytest.importorskip("numpy") pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") df = pd.DataFrame({"a": range(10)}) ddf = dd.from_pandas(df, npartitions=3) result = np.where(ddf.a > 4) def fetch_comp_code(dask_scheduler): computations = list(dask_scheduler.computations) assert len(computations) == 1 comp = computations[0] assert len(comp.code) == 1 return comp.code[0] code = client.run_on_scheduler(fetch_comp_code) assert code == "<Code not available>" @gen_cluster(client=True) async def test_computation_object_code_dask_persist(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones((10, 10), chunks=(3, 3)) future = x.sum().persist() await future test_function_code = inspect.getsource( test_computation_object_code_dask_persist.__wrapped__ ) computations = list(s.computations) assert len(computations) == 1 comp = computations[0] assert len(comp.code) == 1 assert comp.code[0] == test_function_code @gen_cluster(client=True) async def test_computation_object_code_client_submit_simple(c, s, a, b): def func(x): return x fut = c.submit(func, 1) await fut test_function_code = inspect.getsource( test_computation_object_code_client_submit_simple.__wrapped__ ) computations = list(s.computations) assert len(computations) == 1 comp = computations[0] assert len(comp.code) == 1 assert comp.code[0] == test_function_code @gen_cluster(client=True) async def test_computation_object_code_client_submit_list_comp(c, s, a, b): def func(x): return x futs = [c.submit(func, x) for x in range(10)] await c.gather(futs) test_function_code = inspect.getsource( test_computation_object_code_client_submit_list_comp.__wrapped__ ) computations = list(s.computations) assert len(computations) == 1 comp = computations[0] # Code is deduplicated assert len(comp.code) == 1 assert comp.code[0] == test_function_code @gen_cluster(client=True) async def test_computation_object_code_client_submit_dict_comp(c, s, a, b): def func(x): return x futs = {x: c.submit(func, x) for x in range(10)} await c.gather(futs) test_function_code = inspect.getsource( test_computation_object_code_client_submit_dict_comp.__wrapped__ ) computations = list(s.computations) assert len(computations) == 1 comp = computations[0] # Code is deduplicated assert len(comp.code) == 1 assert comp.code[0] == test_function_code @gen_cluster(client=True) async def test_computation_object_code_client_map(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones((10, 10), chunks=(3, 3)) future = c.compute(x.sum(), retries=2) y = await future test_function_code = inspect.getsource( test_computation_object_code_client_map.__wrapped__ ) computations = list(s.computations) assert len(computations) == 1 comp = computations[0] assert len(comp.code) == 1 assert comp.code[0] == test_function_code @gen_cluster(client=True) async def test_computation_object_code_client_compute(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones((10, 10), chunks=(3, 3)) future = c.compute(x.sum(), retries=2) y = await future test_function_code = inspect.getsource( test_computation_object_code_client_compute.__wrapped__ ) computations = list(s.computations) assert len(computations) == 1 comp = computations[0] assert len(comp.code) == 1 assert comp.code[0] == test_function_code @gen_cluster(client=True, Worker=Nanny) async def test_upload_directory(c, s, a, b, tmp_path): from dask.distributed import UploadDirectory files = set(os.listdir()) with open(tmp_path / "foo.py", "w") as f: f.write("x = 123") with open(tmp_path / "bar.py", "w") as f: f.write("from foo import x") plugin = UploadDirectory(tmp_path, restart=True, update_path=True) await c.register_worker_plugin(plugin) [name] = a.plugins assert os.path.split(tmp_path)[-1] in name def f(): import bar return bar.x results = await c.run(f) assert results[a.worker_address] == 123 assert results[b.worker_address] == 123 async with Nanny(s.address, local_directory=tmp_path / "foo", name="foo") as n: results = await c.run(f) assert results[n.worker_address] == 123 assert files == set(os.listdir()) # no change @gen_cluster(client=True) async def test_exception_text(c, s, a, b): def bad(x): raise Exception(x) future = c.submit(bad, 123) await wait(future) ts = s.tasks[future.key] assert isinstance(ts.exception_text, str) assert "123" in ts.exception_text assert "Exception(x)" in ts.traceback_text assert "bad" in ts.traceback_text @gen_cluster(client=True) async def test_async_task(c, s, a, b): async def f(x): return x + 1 future = c.submit(f, 10) result = await future assert result == 11 @gen_cluster(client=True, nthreads=[("", 1)]) async def test_events_subscribe_topic(c, s, a): log = [] def user_event_handler(event): log.append(event) c.subscribe_topic("test-topic", user_event_handler) while not s.event_subscriber["test-topic"]: await asyncio.sleep(0.01) a.log_event("test-topic", {"important": "event"}) while len(log) != 1: await asyncio.sleep(0.01) time_, msg = log[0] assert isinstance(time_, float) assert msg == {"important": "event"} c.unsubscribe_topic("test-topic") while s.event_subscriber["test-topic"]: await asyncio.sleep(0.01) a.log_event("test-topic", {"forget": "me"}) while len(s.events["test-topic"]) == 1: await asyncio.sleep(0.01) assert len(log) == 1 async def async_user_event_handler(event): log.append(event) await asyncio.sleep(0) c.subscribe_topic("test-topic", async_user_event_handler) while not s.event_subscriber["test-topic"]: await asyncio.sleep(0.01) a.log_event("test-topic", {"async": "event"}) while len(log) == 1: await asyncio.sleep(0.01) assert len(log) == 2 time_, msg = log[1] assert isinstance(time_, float) assert msg == {"async": "event"} # Even though the middle event was not subscribed to, the scheduler still # knows about all and we can retrieve them all_events = await c.get_events(topic="test-topic") assert len(all_events) == 3 @gen_cluster(client=True, nthreads=[("", 1)]) async def test_events_all_servers_use_same_channel(c, s, a): """Ensure that logs from all server types (scheduler, worker, nanny) and the clients themselves arrive""" log = [] def user_event_handler(event): log.append(event) c.subscribe_topic("test-topic", user_event_handler) while not s.event_subscriber["test-topic"]: await asyncio.sleep(0.01) async with Nanny(s.address) as n: a.log_event("test-topic", "worker") n.log_event("test-topic", "nanny") s.log_event("test-topic", "scheduler") await c.log_event("test-topic", "client") while not len(log) == 4 == len(set(log)): await asyncio.sleep(0.1) @gen_cluster(client=True, nthreads=[]) async def test_events_unsubscribe_raises_if_unknown(c, s): with pytest.raises(ValueError, match="No event handler known for topic unknown"): c.unsubscribe_topic("unknown") @gen_cluster(client=True) async def test_log_event_warn(c, s, a, b): def foo(): get_worker().log_event(["foo", "warn"], "Hello!") with pytest.warns(Warning, match="Hello!"): await c.submit(foo) @gen_cluster(client=True) async def test_log_event_warn_dask_warns(c, s, a, b): from dask.distributed import warn def foo(): warn("Hello!") with pytest.warns(Warning, match="Hello!"): await c.submit(foo) @gen_cluster(client=True, Worker=Nanny) async def test_print(c, s, a, b, capsys): from dask.distributed import print def foo(): print("Hello!", 123, sep=":") await c.submit(foo) out, err = capsys.readouterr() assert "Hello!:123" in out @gen_cluster(client=True, Worker=Nanny) async def test_print_non_msgpack_serializable(c, s, a, b, capsys): from dask.distributed import print def foo(): print(object()) await c.submit(foo) out, err = capsys.readouterr() assert "<object object at" in out def test_print_simple(capsys): from dask.distributed import print print("Hello!", 123, sep=":") out, err = capsys.readouterr() assert "Hello!:123" in out
datastore.py
# Copyright 2021 The Feast Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import itertools import logging from datetime import datetime from multiprocessing.pool import ThreadPool from queue import Queue from threading import Lock, Thread from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple from pydantic import PositiveInt, StrictStr from pydantic.typing import Literal from feast import Entity, utils from feast.errors import FeastProviderLoginError from feast.feature_view import FeatureView from feast.infra.infra_object import DATASTORE_INFRA_OBJECT_CLASS_TYPE, InfraObject from feast.infra.online_stores.helpers import compute_entity_id from feast.infra.online_stores.online_store import OnlineStore from feast.protos.feast.core.DatastoreTable_pb2 import ( DatastoreTable as DatastoreTableProto, ) from feast.protos.feast.core.InfraObject_pb2 import InfraObject as InfraObjectProto from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto from feast.protos.feast.types.Value_pb2 import Value as ValueProto from feast.repo_config import FeastConfigBaseModel, RepoConfig from feast.usage import log_exceptions_and_usage, tracing_span LOGGER = logging.getLogger(__name__) try: from google.auth.exceptions import DefaultCredentialsError from google.cloud import datastore from google.cloud.datastore.client import Key except ImportError as e: from feast.errors import FeastExtrasDependencyImportError raise FeastExtrasDependencyImportError("gcp", str(e)) ProtoBatch = Sequence[ Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]] ] class DatastoreOnlineStoreConfig(FeastConfigBaseModel): """ Online store config for GCP Datastore """ type: Literal["datastore"] = "datastore" """ Online store type selector""" project_id: Optional[StrictStr] = None """ (optional) GCP Project Id """ namespace: Optional[StrictStr] = None """ (optional) Datastore namespace """ write_concurrency: Optional[PositiveInt] = 40 """ (optional) Amount of threads to use when writing batches of feature rows into Datastore""" write_batch_size: Optional[PositiveInt] = 50 """ (optional) Amount of feature rows per batch being written into Datastore""" class DatastoreOnlineStore(OnlineStore): """ OnlineStore is an object used for all interaction between Feast and the service used for offline storage of features. """ _client: Optional[datastore.Client] = None @log_exceptions_and_usage(online_store="datastore") def update( self, config: RepoConfig, tables_to_delete: Sequence[FeatureView], tables_to_keep: Sequence[FeatureView], entities_to_delete: Sequence[Entity], entities_to_keep: Sequence[Entity], partial: bool, ): online_config = config.online_store assert isinstance(online_config, DatastoreOnlineStoreConfig) client = self._get_client(online_config) feast_project = config.project for table in tables_to_keep: key = client.key("Project", feast_project, "Table", table.name) entity = datastore.Entity( key=key, exclude_from_indexes=("created_ts", "event_ts", "values") ) entity.update({"created_ts": datetime.utcnow()}) client.put(entity) for table in tables_to_delete: _delete_all_values( client, client.key("Project", feast_project, "Table", table.name) ) # Delete the table metadata datastore entity key = client.key("Project", feast_project, "Table", table.name) client.delete(key) def teardown( self, config: RepoConfig, tables: Sequence[FeatureView], entities: Sequence[Entity], ): online_config = config.online_store assert isinstance(online_config, DatastoreOnlineStoreConfig) client = self._get_client(online_config) feast_project = config.project for table in tables: _delete_all_values( client, client.key("Project", feast_project, "Table", table.name) ) # Delete the table metadata datastore entity key = client.key("Project", feast_project, "Table", table.name) client.delete(key) def _get_client(self, online_config: DatastoreOnlineStoreConfig): if not self._client: self._client = _initialize_client( online_config.project_id, online_config.namespace ) return self._client @log_exceptions_and_usage(online_store="datastore") def online_write_batch( self, config: RepoConfig, table: FeatureView, data: List[ Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]] ], progress: Optional[Callable[[int], Any]], ) -> None: online_config = config.online_store assert isinstance(online_config, DatastoreOnlineStoreConfig) client = self._get_client(online_config) write_concurrency = online_config.write_concurrency write_batch_size = online_config.write_batch_size feast_project = config.project pool = ThreadPool(processes=write_concurrency) pool.map( lambda b: self._write_minibatch(client, feast_project, table, b, progress), self._to_minibatches(data, batch_size=write_batch_size), ) @staticmethod def _to_minibatches(data: ProtoBatch, batch_size) -> Iterator[ProtoBatch]: """ Split data into minibatches, making sure we stay under GCP datastore transaction size limits. """ iterable = iter(data) while True: batch = list(itertools.islice(iterable, batch_size)) if len(batch) > 0: yield batch else: break @staticmethod def _write_minibatch( client, project: str, table: FeatureView, data: Sequence[ Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]] ], progress: Optional[Callable[[int], Any]], ): entities = [] for entity_key, features, timestamp, created_ts in data: document_id = compute_entity_id(entity_key) key = client.key( "Project", project, "Table", table.name, "Row", document_id, ) entity = datastore.Entity( key=key, exclude_from_indexes=("created_ts", "event_ts", "values") ) content_entity = datastore.Entity( exclude_from_indexes=tuple(features.keys()) ) for k, v in features.items(): content_entity[k] = v.SerializeToString() entity["key"] = entity_key.SerializeToString() entity["values"] = content_entity entity["event_ts"] = utils.make_tzaware(timestamp) entity["created_ts"] = ( utils.make_tzaware(created_ts) if created_ts is not None else None ) entities.append(entity) with client.transaction(): client.put_multi(entities) if progress: progress(len(entities)) @log_exceptions_and_usage(online_store="datastore") def online_read( self, config: RepoConfig, table: FeatureView, entity_keys: List[EntityKeyProto], requested_features: Optional[List[str]] = None, ) -> List[Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]]]: online_config = config.online_store assert isinstance(online_config, DatastoreOnlineStoreConfig) client = self._get_client(online_config) feast_project = config.project keys: List[Key] = [] result: List[Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]]] = [] for entity_key in entity_keys: document_id = compute_entity_id(entity_key) key = client.key( "Project", feast_project, "Table", table.name, "Row", document_id ) keys.append(key) # NOTE: get_multi doesn't return values in the same order as the keys in the request. # Also, len(values) can be less than len(keys) in the case of missing values. with tracing_span(name="remote_call"): values = client.get_multi(keys) values_dict = {v.key: v for v in values} if values is not None else {} for key in keys: if key in values_dict: value = values_dict[key] res = {} for feature_name, value_bin in value["values"].items(): val = ValueProto() val.ParseFromString(value_bin) res[feature_name] = val result.append((value["event_ts"], res)) else: result.append((None, None)) return result def _delete_all_values(client, key): """ Delete all data under the key path in datastore. Creates and uses a queue of lists of entity keys, which are batch deleted by multiple threads. """ class AtomicCounter(object): # for tracking how many deletions have already occurred; not used outside this method def __init__(self): self.value = 0 self.lock = Lock() def increment(self): with self.lock: self.value += 1 BATCH_SIZE = 500 # Dec 2021: delete_multi has a max size of 500: https://cloud.google.com/datastore/docs/concepts/limits NUM_THREADS = 3 deletion_queue = Queue() status_info_counter = AtomicCounter() def worker(shared_counter): while True: client.delete_multi(deletion_queue.get()) shared_counter.increment() LOGGER.debug( f"batch deletions completed: {shared_counter.value} ({shared_counter.value * BATCH_SIZE} total entries) & outstanding queue size: {deletion_queue.qsize()}" ) deletion_queue.task_done() for _ in range(NUM_THREADS): Thread(target=worker, args=(status_info_counter,), daemon=True).start() query = client.query(kind="Row", ancestor=key) while True: entities = list(query.fetch(limit=BATCH_SIZE)) if not entities: break deletion_queue.put([entity.key for entity in entities]) deletion_queue.join() def _initialize_client( project_id: Optional[str], namespace: Optional[str] ) -> datastore.Client: try: client = datastore.Client(project=project_id, namespace=namespace,) return client except DefaultCredentialsError as e: raise FeastProviderLoginError( str(e) + '\nIt may be necessary to run "gcloud auth application-default login" if you would like to use your ' "local Google Cloud account " ) class DatastoreTable(InfraObject): """ A Datastore table managed by Feast. Attributes: project: The Feast project of the table. name: The name of the table. project_id (optional): The GCP project id. namespace (optional): Datastore namespace. """ project: str project_id: Optional[str] namespace: Optional[str] def __init__( self, project: str, name: str, project_id: Optional[str] = None, namespace: Optional[str] = None, ): super().__init__(name) self.project = project self.project_id = project_id self.namespace = namespace def to_infra_object_proto(self) -> InfraObjectProto: datastore_table_proto = self.to_proto() return InfraObjectProto( infra_object_class_type=DATASTORE_INFRA_OBJECT_CLASS_TYPE, datastore_table=datastore_table_proto, ) def to_proto(self) -> Any: datastore_table_proto = DatastoreTableProto() datastore_table_proto.project = self.project datastore_table_proto.name = self.name if self.project_id: datastore_table_proto.project_id.value = self.project_id if self.namespace: datastore_table_proto.namespace.value = self.namespace return datastore_table_proto @staticmethod def from_infra_object_proto(infra_object_proto: InfraObjectProto) -> Any: datastore_table = DatastoreTable( project=infra_object_proto.datastore_table.project, name=infra_object_proto.datastore_table.name, ) # Distinguish between null and empty string, since project_id and namespace are StringValues. if infra_object_proto.datastore_table.HasField("project_id"): datastore_table.project_id = ( infra_object_proto.datastore_table.project_id.value ) if infra_object_proto.datastore_table.HasField("namespace"): datastore_table.namespace = ( infra_object_proto.datastore_table.namespace.value ) return datastore_table @staticmethod def from_proto(datastore_table_proto: DatastoreTableProto) -> Any: datastore_table = DatastoreTable( project=datastore_table_proto.project, name=datastore_table_proto.name, ) # Distinguish between null and empty string, since project_id and namespace are StringValues. if datastore_table_proto.HasField("project_id"): datastore_table.project_id = datastore_table_proto.project_id.value if datastore_table_proto.HasField("namespace"): datastore_table.namespace = datastore_table_proto.namespace.value return datastore_table def update(self): client = _initialize_client(self.project_id, self.namespace) key = client.key("Project", self.project, "Table", self.name) entity = datastore.Entity( key=key, exclude_from_indexes=("created_ts", "event_ts", "values") ) entity.update({"created_ts": datetime.utcnow()}) client.put(entity) def teardown(self): client = _initialize_client(self.project_id, self.namespace) key = client.key("Project", self.project, "Table", self.name) _delete_all_values(client, key) # Delete the table metadata datastore entity client.delete(key)
test_user_secrets.py
import json import os import threading import unittest from http.server import BaseHTTPRequestHandler, HTTPServer from test.support import EnvironmentVarGuard from urllib.parse import urlparse from datetime import datetime, timedelta import mock from google.auth.exceptions import DefaultCredentialsError from google.cloud import bigquery from kaggle_secrets import (_KAGGLE_URL_BASE_ENV_VAR_NAME, _KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME, CredentialError, UserSecretsClient, BackendError) _TEST_JWT = 'test-secrets-key' class UserSecretsHTTPHandler(BaseHTTPRequestHandler): def set_request(self): raise NotImplementedError() def get_response(self): raise NotImplementedError() def do_HEAD(s): s.send_response(200) def do_POST(s): s.set_request() s.send_response(200) s.send_header("Content-type", "application/json") s.end_headers() s.wfile.write(json.dumps(s.get_response()).encode("utf-8")) class TestUserSecrets(unittest.TestCase): SERVER_ADDRESS = urlparse(os.getenv(_KAGGLE_URL_BASE_ENV_VAR_NAME)) def _test_client(self, client_func, expected_path, expected_body, secret=None, success=True): _request = {} class AccessTokenHandler(UserSecretsHTTPHandler): def set_request(self): _request['path'] = self.path content_len = int(self.headers.get('Content-Length')) _request['body'] = json.loads(self.rfile.read(content_len)) _request['headers'] = self.headers def get_response(self): if success: return {'result': {'secret': secret, 'secretType': 'refreshToken', 'secretProvider': 'google', 'expiresInSeconds': 3600}, 'wasSuccessful': "true"} else: return {'wasSuccessful': "false"} env = EnvironmentVarGuard() env.set(_KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME, _TEST_JWT) with env: with HTTPServer((self.SERVER_ADDRESS.hostname, self.SERVER_ADDRESS.port), AccessTokenHandler) as httpd: threading.Thread(target=httpd.serve_forever).start() try: client_func() finally: httpd.shutdown() path, headers, body = _request['path'], _request['headers'], _request['body'] self.assertEqual( path, expected_path, msg="Fake server did not receive the right request from the UserSecrets client.") self.assertEqual( body, expected_body, msg="Fake server did not receive the right body from the UserSecrets client.") def test_no_token_fails(self): env = EnvironmentVarGuard() env.unset(_KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME) with env: with self.assertRaises(CredentialError): client = UserSecretsClient() @mock.patch('kaggle_secrets.datetime') def test_get_access_token_succeeds(self, mock_dt): secret = '12345' now = datetime(1993, 4, 24) mock_dt.utcnow = mock.Mock(return_value=now) def call_get_access_token(): client = UserSecretsClient() secret_response = client.get_bigquery_access_token() self.assertEqual(secret_response, (secret, now + timedelta(seconds=3600))) self._test_client(call_get_access_token, '/requests/GetUserSecretRequest', {'Target': 1, 'JWE': _TEST_JWT}, secret=secret) def test_get_access_token_handles_unsuccessful(self): def call_get_access_token(): client = UserSecretsClient() with self.assertRaises(BackendError): client.get_bigquery_access_token() self._test_client(call_get_access_token, '/requests/GetUserSecretRequest', {'Target': 1, 'JWE': _TEST_JWT}, success=False)
dev_test_cex_full.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # File: dev_test_cex_full.py # # Part of ‘UNICORN Binance WebSocket API’ # Project website: https://github.com/LUCIT-Systems-and-Development/unicorn-binance-websocket-api # Documentation: https://lucit-systems-and-development.github.io/unicorn-binance-websocket-api # PyPI: https://pypi.org/project/unicorn-binance-websocket-api/ # # Author: LUCIT Systems and Development # # Copyright (c) 2019-2022, LUCIT Systems and Development (https://www.lucit.tech) and Oliver Zehentleitner # All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing 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 MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. from unicorn_binance_websocket_api.manager import BinanceWebSocketApiManager import logging import os import time import threading logging.getLogger("unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager") logging.basicConfig(level=logging.DEBUG, filename=os.path.basename(__file__) + '.log', format="{asctime} [{levelname:8}] {process} {thread} {module}: {message}", style="{") def print_stream_data_from_stream_buffer(binance_websocket_api_manager): while True: if binance_websocket_api_manager.is_manager_stopping(): exit(0) oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer() if oldest_stream_data_from_stream_buffer is False: time.sleep(0.01) else: try: print(oldest_stream_data_from_stream_buffer) except Exception: # not able to process the data? write it back to the stream_buffer binance_websocket_api_manager.add_to_stream_buffer(oldest_stream_data_from_stream_buffer) # create instance of BinanceWebSocketApiManager and provide the function for stream processing binance_websocket_api_manager = BinanceWebSocketApiManager() # start a worker process to process to move the received stream_data from the stream_buffer to a print function worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer, args=(binance_websocket_api_manager,)) worker_thread.start() print("testing ws/ single streams") print("\r\n========================================== Starting ticker all ========================================\r\n") ticker_all_stream_id = binance_websocket_api_manager.create_stream(["arr"], ["!ticker"]) time.sleep(6) binance_websocket_api_manager.stop_stream(ticker_all_stream_id) time.sleep(2) print("\r\n=========================================== Stopped ticker all ========================================\r\n") print("\r\n========================================= Starting !miniticker ========================================\r\n") miniticker_stream_id = binance_websocket_api_manager.create_stream(["arr"], ["!miniTicker"]) time.sleep(5) binance_websocket_api_manager.stop_stream(miniticker_stream_id) time.sleep(2) print("\r\n======================================== Stopped !miniticker =========================================\r\n") print("\r\n========================================== Starting !userData ========================================\r\n") userdata_stream_id = binance_websocket_api_manager.create_stream(["arr"], ["!userData"]) time.sleep(5) binance_websocket_api_manager.stop_stream(userdata_stream_id) time.sleep(2) print("\r\n========================================== Stopped !userData ==========================================\r\n") print("\r\n\r\nTesting multi streams with just one market") print("\r\n========================================== Starting aggTrade ==========================================\r\n") markets = {'bnbbtc'} aggtrade_stream_id = binance_websocket_api_manager.create_stream(["aggTrade"], markets) time.sleep(5) binance_websocket_api_manager.stop_stream(aggtrade_stream_id) time.sleep(2) print("\r\n=========================================== Stopped aggTrade ==========================================\r\n") print("\r\n====================================== Starting trade and kline_1m ====================================\r\n") trade_stream_id = binance_websocket_api_manager.create_stream(["trade"], markets) kline_1m_stream_id = binance_websocket_api_manager.create_stream(["kline_1m"], markets) time.sleep(5) binance_websocket_api_manager.stop_stream(trade_stream_id) binance_websocket_api_manager.stop_stream(kline_1m_stream_id) time.sleep(2) print("\r\n====================================== Stopped trade and kline_1m =====================================\r\n") print("\r\n======================================== Starting ticker BNB/BTC ======================================\r\n") ticker_bnbbtc_stream_id = binance_websocket_api_manager.create_stream(["ticker"], markets) time.sleep(5) binance_websocket_api_manager.stop_stream(ticker_bnbbtc_stream_id) time.sleep(2) print("\r\n======================================== Stopped ticker BNB/BTC =======================================\r\n") print("\r\n========================================== Starting miniticker ========================================\r\n") miniticker_stream_id = binance_websocket_api_manager.create_stream(["miniTicker"], markets) time.sleep(5) binance_websocket_api_manager.stop_stream(miniticker_stream_id) time.sleep(2) print("\r\n========================================= Stopped miniticker =========================================\r\n") print("\r\n========================================== Starting kline_5m ==========================================\r\n") kline_5m_stream_id = binance_websocket_api_manager.create_stream(["kline_5m"], markets) time.sleep(5) binance_websocket_api_manager.stop_stream(kline_5m_stream_id) time.sleep(2) print("\r\n========================================= Stopped kline_5m ===========================================\r\n") print("\r\n=========================================== Starting depth10 ===========================================\r\n") depth5_stream_id = binance_websocket_api_manager.create_stream(["depth10"], markets) time.sleep(5) binance_websocket_api_manager.stop_stream(depth5_stream_id) time.sleep(2) print("\r\n========================================== Stopped depth5 ============================================\r\n") print("\r\n========================================== Starting depth =============================================\r\n") depth_stream_id = binance_websocket_api_manager.create_stream(["depth"], markets) time.sleep(4) binance_websocket_api_manager.stop_stream(depth_stream_id) time.sleep(2) print("\r\n============================================ Stopped depth ===========================================\r\n") print("\r\n\r\nTesting multi markets with one stream_type") markets = {'xrpusdt', 'rvnbtc', 'ltcusdt', 'adausdt', 'eosusdt', 'neousdt', 'btcusdt', 'bnbusdt'} print("\r\n========================================== Starting aggTrade ==========================================\r\n") aggtrade_stream_id = binance_websocket_api_manager.create_stream(["aggTrade"], markets) time.sleep(3) binance_websocket_api_manager.stop_stream(aggtrade_stream_id) time.sleep(2) print("\r\n=========================================== Stopped aggTrade ==========================================\r\n") print("\r\n====================================== Starting trade and kline_1m ====================================\r\n") trade_stream_id = binance_websocket_api_manager.create_stream(["trade"], markets) kline_1m_stream_id = binance_websocket_api_manager.create_stream(["kline_1m"], markets) time.sleep(3) binance_websocket_api_manager.stop_stream(trade_stream_id) binance_websocket_api_manager.stop_stream(kline_1m_stream_id) time.sleep(2) print("\r\n====================================== Stopped trade and kline_1m =====================================\r\n") print("\r\n======================================= Starting ticker ===============================================\r\n") ticker_bnbbtc_stream_id = binance_websocket_api_manager.create_stream(["ticker"], markets) time.sleep(4) binance_websocket_api_manager.stop_stream(ticker_bnbbtc_stream_id) time.sleep(2) print("\r\n========================================= Stopped ticker ==============================================\r\n") print("\r\n========================================== Starting miniticker ========================================\r\n") miniticker_stream_id = binance_websocket_api_manager.create_stream(["miniTicker"], markets) time.sleep(4) binance_websocket_api_manager.stop_stream(miniticker_stream_id) time.sleep(2) print("\r\n========================================== Stopped miniticker ========================================\r\n") print("\r\n========================================== Starting kline_5m ==========================================\r\n") kline_5m_stream_id = binance_websocket_api_manager.create_stream(["kline_5m"], markets) time.sleep(4) binance_websocket_api_manager.stop_stream(kline_5m_stream_id) time.sleep(2) print("\r\n========================================= Stopped kline_5m ===========================================\r\n") print("\r\n=========================================== Starting depth5 ===========================================\r\n") depth5_stream_id = binance_websocket_api_manager.create_stream(["depth5"], markets) time.sleep(4) binance_websocket_api_manager.stop_stream(depth5_stream_id) time.sleep(2) print("\r\n========================================== Stopped depth5 ============================================\r\n") print("\r\n========================================== Starting depth =============================================\r\n") depth_stream_id = binance_websocket_api_manager.create_stream(["depth"], markets) time.sleep(4) binance_websocket_api_manager.stop_stream(depth_stream_id) time.sleep(2) print("\r\n============================================ Stopped depth ===========================================\r\n") print("\r\n=================================== Starting multi multi socket =======================================\r\n") channels = {'trade', 'kline_1', 'kline_5', 'kline_15', 'kline_30', 'kline_1h', 'kline_12h', 'kline_1w', 'miniTicker', 'depth20', '!miniTicker', '!ticker'} multi_multi_stream_id = binance_websocket_api_manager.create_stream(channels, markets) time.sleep(4) binance_websocket_api_manager.stop_stream(multi_multi_stream_id) time.sleep(2) print("\r\n================================== Stopped multi multi socket ========================================\r\n") # print summary binance_websocket_api_manager.print_summary() print("\r\n=============================== Stopping BinanceWebSocketManager ======================================\r\n") binance_websocket_api_manager.stop_manager_with_all_streams() time.sleep(7) stream_list = binance_websocket_api_manager.get_stream_list() for stream_id in stream_list: binance_websocket_api_manager.print_stream_info(stream_id) time.sleep(3.5) print("finished!")
word2vec.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. # ============================================================================== """Multi-threaded word2vec mini-batched skip-gram model. Trains the model described in: (Mikolov, et. al.) Efficient Estimation of Word Representations in Vector Space ICLR 2013. http://arxiv.org/abs/1301.3781 This model does traditional minibatching. The key ops used are: * placeholder for feeding in tensors for each example. * embedding_lookup for fetching rows from the embedding matrix. * sigmoid_cross_entropy_with_logits to calculate the loss. * GradientDescentOptimizer for optimizing the loss. * skipgram custom op that does input processing. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import threading import time from six.moves import xrange # pylint: disable=redefined-builtin import numpy as np import tensorflow as tf word2vec = tf.load_op_library(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'word2vec_ops.so')) flags = tf.app.flags flags.DEFINE_string("save_path", None, "Directory to write the model and " "training summaries.") flags.DEFINE_string("train_data", None, "Training text file. " "E.g., unzipped file http://mattmahoney.net/dc/text8.zip.") flags.DEFINE_string( "eval_data", None, "File consisting of analogies of four tokens." "embedding 2 - embedding 1 + embedding 3 should be close " "to embedding 4." "See README.md for how to get 'questions-words.txt'.") flags.DEFINE_integer("embedding_size", 200, "The embedding dimension size.") flags.DEFINE_integer( "epochs_to_train", 15, "Number of epochs to train. Each epoch processes the training data once " "completely.") flags.DEFINE_float("learning_rate", 0.2, "Initial learning rate.") flags.DEFINE_integer("num_neg_samples", 100, "Negative samples per training example.") flags.DEFINE_integer("batch_size", 16, "Number of training examples processed per step " "(size of a minibatch).") flags.DEFINE_integer("concurrent_steps", 12, "The number of concurrent training steps.") flags.DEFINE_integer("window_size", 5, "The number of words to predict to the left and right " "of the target word.") flags.DEFINE_integer("min_count", 5, "The minimum number of word occurrences for it to be " "included in the vocabulary.") flags.DEFINE_float("subsample", 1e-3, "Subsample threshold for word occurrence. Words that appear " "with higher frequency will be randomly down-sampled. Set " "to 0 to disable.") flags.DEFINE_boolean( "interactive", False, "If true, enters an IPython interactive session to play with the trained " "model. E.g., try model.analogy(b'france', b'paris', b'russia') and " "model.nearby([b'proton', b'elephant', b'maxwell'])") flags.DEFINE_integer("statistics_interval", 5, "Print statistics every n seconds.") flags.DEFINE_integer("summary_interval", 5, "Save training summary to file every n seconds (rounded " "up to statistics interval).") flags.DEFINE_integer("checkpoint_interval", 600, "Checkpoint the model (i.e. save the parameters) every n " "seconds (rounded up to statistics interval).") FLAGS = flags.FLAGS class Options(object): """Options used by our word2vec model.""" def __init__(self): # Model options. # Embedding dimension. self.emb_dim = FLAGS.embedding_size # Training options. # The training text file. self.train_data = FLAGS.train_data # Number of negative samples per example. self.num_samples = FLAGS.num_neg_samples # The initial learning rate. self.learning_rate = FLAGS.learning_rate # Number of epochs to train. After these many epochs, the learning # rate decays linearly to zero and the training stops. self.epochs_to_train = FLAGS.epochs_to_train # Concurrent training steps. self.concurrent_steps = FLAGS.concurrent_steps # Number of examples for one training step. self.batch_size = FLAGS.batch_size # The number of words to predict to the left and right of the target word. self.window_size = FLAGS.window_size # The minimum number of word occurrences for it to be included in the # vocabulary. self.min_count = FLAGS.min_count # Subsampling threshold for word occurrence. self.subsample = FLAGS.subsample # How often to print statistics. self.statistics_interval = FLAGS.statistics_interval # How often to write to the summary file (rounds up to the nearest # statistics_interval). self.summary_interval = FLAGS.summary_interval # How often to write checkpoints (rounds up to the nearest statistics # interval). self.checkpoint_interval = FLAGS.checkpoint_interval # Where to write out summaries. self.save_path = FLAGS.save_path if not os.path.exists(self.save_path): os.makedirs(self.save_path) # Eval options. # The text file for eval. self.eval_data = FLAGS.eval_data class Word2Vec(object): """Word2Vec model (Skipgram).""" def __init__(self, options, session): self._options = options self._session = session self._word2id = {} self._id2word = [] self.build_graph() self.build_eval_graph() self.save_vocab() def read_analogies(self): """Reads through the analogy question file. Returns: questions: a [n, 4] numpy array containing the analogy question's word ids. questions_skipped: questions skipped due to unknown words. """ questions = [] questions_skipped = 0 with open(self._options.eval_data, "rb") as analogy_f: for line in analogy_f: if line.startswith(b":"): # Skip comments. continue words = line.strip().lower().split(b" ") ids = [self._word2id.get(w.strip()) for w in words] if None in ids or len(ids) != 4: questions_skipped += 1 else: questions.append(np.array(ids)) print("Eval analogy file: ", self._options.eval_data) print("Questions: ", len(questions)) print("Skipped: ", questions_skipped) self._analogy_questions = np.array(questions, dtype=np.int32) def forward(self, examples, labels): """Build the graph for the forward pass.""" opts = self._options # Declare all variables we need. # Embedding: [vocab_size, emb_dim] init_width = 0.5 / opts.emb_dim emb = tf.Variable( tf.random_uniform( [opts.vocab_size, opts.emb_dim], -init_width, init_width), name="emb") self._emb = emb # Softmax weight: [vocab_size, emb_dim]. Transposed. sm_w_t = tf.Variable( tf.zeros([opts.vocab_size, opts.emb_dim]), name="sm_w_t") # Softmax bias: [vocab_size]. sm_b = tf.Variable(tf.zeros([opts.vocab_size]), name="sm_b") # Global step: scalar, i.e., shape []. self.global_step = tf.Variable(0, name="global_step") # Nodes to compute the nce loss w/ candidate sampling. labels_matrix = tf.reshape( tf.cast(labels, dtype=tf.int64), [opts.batch_size, 1]) # Negative sampling. sampled_ids, _, _ = (tf.nn.fixed_unigram_candidate_sampler( true_classes=labels_matrix, num_true=1, num_sampled=opts.num_samples, unique=True, range_max=opts.vocab_size, distortion=0.75, unigrams=opts.vocab_counts.tolist())) # Embeddings for examples: [batch_size, emb_dim] example_emb = tf.nn.embedding_lookup(emb, examples) # Weights for labels: [batch_size, emb_dim] true_w = tf.nn.embedding_lookup(sm_w_t, labels) # Biases for labels: [batch_size, 1] true_b = tf.nn.embedding_lookup(sm_b, labels) # Weights for sampled ids: [num_sampled, emb_dim] sampled_w = tf.nn.embedding_lookup(sm_w_t, sampled_ids) # Biases for sampled ids: [num_sampled, 1] sampled_b = tf.nn.embedding_lookup(sm_b, sampled_ids) # True logits: [batch_size, 1] true_logits = tf.reduce_sum(tf.multiply(example_emb, true_w), 1) + true_b # Sampled logits: [batch_size, num_sampled] # We replicate sampled noise labels for all examples in the batch # using the matmul. sampled_b_vec = tf.reshape(sampled_b, [opts.num_samples]) sampled_logits = tf.matmul(example_emb, sampled_w, transpose_b=True) + sampled_b_vec return true_logits, sampled_logits def nce_loss(self, true_logits, sampled_logits): """Build the graph for the NCE loss.""" # cross-entropy(logits, labels) opts = self._options true_xent = tf.nn.sigmoid_cross_entropy_with_logits( labels=tf.ones_like(true_logits), logits=true_logits) sampled_xent = tf.nn.sigmoid_cross_entropy_with_logits( labels=tf.zeros_like(sampled_logits), logits=sampled_logits) # NCE-loss is the sum of the true and noise (sampled words) # contributions, averaged over the batch. nce_loss_tensor = (tf.reduce_sum(true_xent) + tf.reduce_sum(sampled_xent)) / opts.batch_size return nce_loss_tensor def optimize(self, loss): """Build the graph to optimize the loss function.""" # Optimizer nodes. # Linear learning rate decay. opts = self._options words_to_train = float(opts.words_per_epoch * opts.epochs_to_train) lr = opts.learning_rate * tf.maximum( 0.0001, 1.0 - tf.cast(self._words, tf.float32) / words_to_train) self._lr = lr optimizer = tf.train.GradientDescentOptimizer(lr) train = optimizer.minimize(loss, global_step=self.global_step, gate_gradients=optimizer.GATE_NONE) self._train = train def build_eval_graph(self): """Build the eval graph.""" # Eval graph # Each analogy task is to predict the 4th word (d) given three # words: a, b, c. E.g., a=italy, b=rome, c=france, we should # predict d=paris. # The eval feeds three vectors of word ids for a, b, c, each of # which is of size N, where N is the number of analogies we want to # evaluate in one batch. analogy_a = tf.placeholder(dtype=tf.int32) # [N] analogy_b = tf.placeholder(dtype=tf.int32) # [N] analogy_c = tf.placeholder(dtype=tf.int32) # [N] # Normalized word embeddings of shape [vocab_size, emb_dim]. nemb = tf.nn.l2_normalize(self._emb, 1) # Each row of a_emb, b_emb, c_emb is a word's embedding vector. # They all have the shape [N, emb_dim] a_emb = tf.gather(nemb, analogy_a) # a's embs b_emb = tf.gather(nemb, analogy_b) # b's embs c_emb = tf.gather(nemb, analogy_c) # c's embs # We expect that d's embedding vectors on the unit hyper-sphere is # near: c_emb + (b_emb - a_emb), which has the shape [N, emb_dim]. target = c_emb + (b_emb - a_emb) # Compute cosine distance between each pair of target and vocab. # dist has shape [N, vocab_size]. dist = tf.matmul(target, nemb, transpose_b=True) # For each question (row in dist), find the top 4 words. _, pred_idx = tf.nn.top_k(dist, 4) # Nodes for computing neighbors for a given word according to # their cosine distance. nearby_word = tf.placeholder(dtype=tf.int32) # word id nearby_emb = tf.gather(nemb, nearby_word) nearby_dist = tf.matmul(nearby_emb, nemb, transpose_b=True) nearby_val, nearby_idx = tf.nn.top_k(nearby_dist, min(1000, self._options.vocab_size)) # Nodes in the construct graph which are used by training and # evaluation to run/feed/fetch. self._analogy_a = analogy_a self._analogy_b = analogy_b self._analogy_c = analogy_c self._analogy_pred_idx = pred_idx self._nearby_word = nearby_word self._nearby_val = nearby_val self._nearby_idx = nearby_idx def build_graph(self): """Build the graph for the full model.""" opts = self._options # The training data. A text file. (words, counts, words_per_epoch, self._epoch, self._words, examples, labels) = word2vec.skipgram_word2vec(filename=opts.train_data, batch_size=opts.batch_size, window_size=opts.window_size, min_count=opts.min_count, subsample=opts.subsample) (opts.vocab_words, opts.vocab_counts, opts.words_per_epoch) = self._session.run([words, counts, words_per_epoch]) opts.vocab_size = len(opts.vocab_words) print("Data file: ", opts.train_data) print("Vocab size: ", opts.vocab_size - 1, " + UNK") print("Words per epoch: ", opts.words_per_epoch) self._examples = examples self._labels = labels self._id2word = opts.vocab_words for i, w in enumerate(self._id2word): self._word2id[w] = i true_logits, sampled_logits = self.forward(examples, labels) loss = self.nce_loss(true_logits, sampled_logits) tf.summary.scalar("NCE loss", loss) self._loss = loss self.optimize(loss) # Properly initialize all variables. tf.global_variables_initializer().run() self.saver = tf.train.Saver() def save_vocab(self): """Save the vocabulary to a file so the model can be reloaded.""" opts = self._options with open(os.path.join(opts.save_path, "vocab.txt"), "w") as f: for i in xrange(opts.vocab_size): vocab_word = tf.compat.as_text(opts.vocab_words[i]).encode("utf-8") f.write("%s %d\n" % (vocab_word, opts.vocab_counts[i])) def _train_thread_body(self): initial_epoch, = self._session.run([self._epoch]) while True: _, epoch = self._session.run([self._train, self._epoch]) if epoch != initial_epoch: break def train(self): """Train the model.""" opts = self._options initial_epoch, initial_words = self._session.run([self._epoch, self._words]) summary_op = tf.summary.merge_all() summary_writer = tf.summary.FileWriter(opts.save_path, self._session.graph) workers = [] for _ in xrange(opts.concurrent_steps): t = threading.Thread(target=self._train_thread_body) t.start() workers.append(t) last_words, last_time, last_summary_time = initial_words, time.time(), 0 last_checkpoint_time = 0 while True: time.sleep(opts.statistics_interval) # Reports our progress once a while. (epoch, step, loss, words, lr) = self._session.run( [self._epoch, self.global_step, self._loss, self._words, self._lr]) now = time.time() last_words, last_time, rate = words, now, (words - last_words) / ( now - last_time) print("Epoch %4d Step %8d: lr = %5.3f loss = %6.2f words/sec = %8.0f\r" % (epoch, step, lr, loss, rate), end="") sys.stdout.flush() if now - last_summary_time > opts.summary_interval: summary_str = self._session.run(summary_op) summary_writer.add_summary(summary_str, step) last_summary_time = now if now - last_checkpoint_time > opts.checkpoint_interval: self.saver.save(self._session, os.path.join(opts.save_path, "model.ckpt"), global_step=step.astype(int)) last_checkpoint_time = now if epoch != initial_epoch: break for t in workers: t.join() return epoch def _predict(self, analogy): """Predict the top 4 answers for analogy questions.""" idx, = self._session.run([self._analogy_pred_idx], { self._analogy_a: analogy[:, 0], self._analogy_b: analogy[:, 1], self._analogy_c: analogy[:, 2] }) return idx def eval(self): """Evaluate analogy questions and reports accuracy.""" # How many questions we get right at precision@1. correct = 0 try: total = self._analogy_questions.shape[0] except AttributeError as e: raise AttributeError("Need to read analogy questions.") start = 0 while start < total: limit = start + 2500 sub = self._analogy_questions[start:limit, :] idx = self._predict(sub) start = limit for question in xrange(sub.shape[0]): for j in xrange(4): if idx[question, j] == sub[question, 3]: # Bingo! We predicted correctly. E.g., [italy, rome, france, paris]. correct += 1 break elif idx[question, j] in sub[question, :3]: # We need to skip words already in the question. continue else: # The correct label is not the precision@1 break print() print("Eval %4d/%d accuracy = %4.1f%%" % (correct, total, correct * 100.0 / total)) def analogy(self, w0, w1, w2): """Predict word w3 as in w0:w1 vs w2:w3.""" wid = np.array([[self._word2id.get(w, 0) for w in [w0, w1, w2]]]) idx = self._predict(wid) for c in [self._id2word[i] for i in idx[0, :]]: if c not in [w0, w1, w2]: print(c) return print("unknown") def nearby(self, words, num=20): """Prints out nearby words given a list of words.""" ids = np.array([self._word2id.get(x, 0) for x in words]) vals, idx = self._session.run( [self._nearby_val, self._nearby_idx], {self._nearby_word: ids}) for i in xrange(len(words)): print("\n%s\n=====================================" % (words[i])) for (neighbor, distance) in zip(idx[i, :num], vals[i, :num]): print("%-20s %6.4f" % (self._id2word[neighbor], distance)) def _start_shell(local_ns=None): # An interactive shell is useful for debugging/development. import IPython user_ns = {} if local_ns: user_ns.update(local_ns) user_ns.update(globals()) IPython.start_ipython(argv=[], user_ns=user_ns) def main(_): """Train a word2vec model.""" if not FLAGS.train_data or not FLAGS.eval_data or not FLAGS.save_path: print("--train_data --eval_data and --save_path must be specified.") sys.exit(1) opts = Options() with tf.Graph().as_default(), tf.Session() as session: with tf.device("/cpu:0"): model = Word2Vec(opts, session) model.read_analogies() # Read analogy questions for _ in xrange(opts.epochs_to_train): model.train() # Process one epoch model.eval() # Eval analogies. # Perform a final save. model.saver.save(session, os.path.join(opts.save_path, "model.ckpt"), global_step=model.global_step) if FLAGS.interactive: # E.g., # [0]: model.analogy(b'france', b'paris', b'russia') # [1]: model.nearby([b'proton', b'elephant', b'maxwell']) _start_shell(locals()) if __name__ == "__main__": tf.app.run()
servo_ball_nosocket.py
#!/usr/bin/env python # coding=utf-8 from __future__ import division import cv2 import Adafruit_PCA9685 import time import numpy as np import threading pwm = Adafruit_PCA9685.PCA9685() pwm.set_pwm_freq(60) pwm.set_pwm(14, 0, 580) pwm.set_pwm(15, 0, 580) time.sleep(1) cap = cv2.VideoCapture(0) hsv_min = np.array([45,43,46]) hsv_max = np.array([77,255,255]) x = 0 thisError_x = 500 lastError_x = 100 thisError_y = 500 lastError_y = 100 Y_P = 425 X_P = 425 flag = 0 y = 0 def xx(X_P, Y_P): pwm.set_pwm(14, 0, 650 - X_P) pwm.set_pwm(15, 0, 650 - Y_P) while 1: ret, frame = cap.read() if False == ret: print("read image from video failed!") break; frame = cv2.GaussianBlur(frame, (5, 5), 0) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, hsv_min, hsv_max) mask = cv2.erode(mask, None, iterations = 2) mask = cv2.dilate(mask, None, iterations = 2) mask = cv2.GaussianBlur(mask, (3, 3), 0) res = cv2.bitwise_and(frame ,frame, mask = mask) cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] if 0 < len(cnts): print("target find!") cnt = max(cnts, key = cv2.contourArea) (x, y), radius = cv2.minEnclosingCircle(cnt) cv2.circle(frame, (int(x), int(y)), int(radius), (255, 0, 255), 2) thisError_x = x - 160 thisError_y = y - 120 pwm_x = thisError_x * 3 + 1 * (thisError_x - lastError_x) pwm_y = thisError_y * 3 + 1 * (thisError_y - lastError_y) lastError_x = thisError_x lastError_y = thisError_y XP = pwm_x / 100 YP = pwm_y / 100 X_P = X_P + int(XP) Y_P = Y_P + int(YP) if 670 < X_P: X_P = 650 if 0 > X_P: X_P = 0 if 650 < Y_P: Y_P = 650 if 0 > Y_P: Y_P = 0 print('x', x, X_P) tid = threading.Thread(target = xx, args = (X_P, Y_P,)) tid.setDaemon(True) tid.start() # cv2.imshow("live...", frame) if 119 == cv2.waitKey(5): break cap.release() cv2.destroyAllWindows()
gpsnap.py
#!/usr/bin/env python ''' gpsnap -- snapshot a gpdb array Usage: gpsnap [-Vvlfz?] [-u user] {-crdiI} snapshot_name -c: create a snapshot -r: restore a snapshot -d: delete a snapshot -i: show information on snapshot -I: show detailed info on snapshot -z: use zfs snapshot mechanism -l: list snapshots -v: verbose -V: very verbose -f: force -?: print help ''' import os, sys progname = os.path.split(sys.argv[0])[-1] if sys.version_info < (2,5,0): sys.exit( '''Error %s is supported on Python version 2.5 or greater Please upgrade python installed on this machine.''' % progname) import subprocess, time, datetime, threading, Queue, random, pickle ############ MASTER_DATA_DIRECTORY = os.getenv('MASTER_DATA_DIRECTORY') if not MASTER_DATA_DIRECTORY: sys.exit('MASTER_DATA_DIRECTORY env not defined') # we always connect to localhost for snapshot ... must run on master machine os.putenv('PGHOST', '') os.putenv("PGOPTIONS", '-c gp_session_role=utility') os.putenv('PGDATABASE', 'template1') class __globals__: opt = {} for o in 'vVcrdiIflzu': opt['-' + o] = False opt['-u'] = '' snapname = '' GV = __globals__() ############ def usage(exitarg): print __doc__ sys.exit(exitarg) ############ def humantime(td): d = td.days > 0 and td.days or 0 h = int(td.seconds / 60 / 60) m = int(td.seconds / 60) % 60 s = td.seconds % 60 ret = '' if d: ret = ret + '%dD ' % d if h: ret = ret + '%dh ' % h ret = ret + ('%dm %ds' % (m, s)) return ret ############ def tstamp(): return datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]') ############ def msg(s): print '%s %s' % (tstamp(), s) def vmsg(s): if GV.opt['-v']: msg(s) def vvmsg(s): if GV.opt['-V']: msg(s) ############ def die(s): sys.exit('%s ERROR: %s' % (tstamp(), s)) ############ def strip_trailing_slash(dir): return dir.rstrip('/') if dir else None ############ def ssh(hostname, cmd, input=''): proxy = ['ssh', '-o', 'BatchMode yes', '-o', 'StrictHostKeyChecking no', hostname, '''bash -c 'exec python -c "import os,sys,pickle,subprocess; (prog, cmd, input) = pickle.load(sys.stdin); exec prog" ' '''] prog = """ p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) p.stdin.write(input) p.stdin.close() sys.stdout.write(p.stdout.read()) sys.exit(p.wait())""" vvmsg(' - ssh ' + hostname + ' ' + str(cmd)) p = subprocess.Popen(proxy, stdin=subprocess.PIPE, stdout=subprocess.PIPE) if type(cmd) == type(''): cmd = ['bash', '-c', cmd] pickle.dump( (prog, cmd, input), p.stdin ) p.stdin.close() out = p.stdout.read() rc = p.wait() return (rc, out) ############ def confirm(s): if not GV.opt['-f'] and sys.stdin.isatty(): ok = raw_input('%s\n ... proceed (y/n)? ' % s) print ok = ok.strip().lower() return ok and ok[0] == 'y' return True ############ def parseCommandLine(): import getopt try: (options, args) = getopt.getopt(sys.argv[1:], '?VvlcrdiIfzu:') except Exception, e: usage('Error: ' + str(e)) for (switch, val) in options: if switch == '-?': usage(0) elif switch[1] in 'VvlcrdiIfz': GV.opt[switch] = True elif switch == '-u': GV.opt[switch] = val if GV.opt['-V']: GV.opt['-v'] = True if 1 == reduce(lambda x,y: x+y, [GV.opt['-'+s] and 1 or 0 for s in "crdiI"]): pass else: if not GV.opt['-l']: usage('Error: please specify one of -c / -r / -d / -i / -I') if 1 == len(args): GV.snapname = args[0] import re if not re.match('\A[a-zA-Z0-9][a-zA-Z0-9\-\_\:]*\Z', GV.snapname): usage("\n".join(["Error: invalid snapshot name", "Hint: valid name like 'thursday_2009-03_19:00'"])) else: if not GV.opt['-l']: usage('Error: missing snapshot_name') ############ def run(cmd): vvmsg(cmd) p = os.popen(cmd) out = p.readlines() if GV.opt['-V']: for line in out: vvmsg(line[:-1]) rc = p.close() return (rc, out) def runas(cmd): if GV.opt['-u']: x = ['su', '-', GV.opt['-u'], '-c', 'bash'] vvmsg(" ".join(x)) p = subprocess.Popen(x, stdin=subprocess.PIPE, stdout=subprocess.PIPE) path = os.getenv('PATH') ld_library_path = os.getenv('LD_LIBRARY_PATH') dyld_library_path = os.getenv('DYLD_LIBRARY_PATH') cmd1 = ('export PATH="%s"\n' % path + 'export LD_LIBRARY_PATH="%s"\n' % ld_library_path + 'export DYLD_LIBRARY_PATH="%s"\n' % dyld_library_path) p.stdin.write(cmd1) p.stdin.write(cmd) p.stdin.close() out = p.stdout.readlines() if GV.opt['-V']: for line in out: vvmsg(line[:-1]) return (p.wait(), out) else: return run(cmd) def getZfsMountpoint(hostname, datapath): cmd = "echo hostname $(hostname); zfs list -t filesystem " + datapath (rc, out) = ssh(hostname, cmd) if rc: return (None, None) (hname, mpoint) = (None, None) for line in out.split('\n'): t = map(lambda x: x.strip(), line.split()) if not t: continue if t[0] == 'hostname': hname = t[1]; continue if len(t) != 5: break if datapath.find(t[4]) == 0: mpoint = t[0]; continue return (hname, mpoint) class Segment: def __init__(self, line): row = [x.strip() for x in line.split('|')] (self.content, self.definedprimary, self.dbid, self.isprimary, self.valid, self.hostname, self.port, self.datapath) = row (self.toppath, self.dbdir) = os.path.split(strip_trailing_slash(self.datapath)) def __str__(self): return "|".join([self.content, self.definedprimary, self.dbid, self.isprimary, self.valid, self.hostname, self.port, self.datapath]) class SnapshotMethod: def __init__(self, type, name, seg): (self.type, self.name, self.seg) = (type, name, seg) self.fullname = '' def set_fullname(self,fn): self.fullname = fn def createSnapshot(self): return -1 def deleteSnapshot(self): return -1 def checkSnapshot(self): return (-1, None) def restoreSnapshot(self): return -1 def type(self): return self.type class TgzSnapshot(SnapshotMethod): def __init__(self, name, seg): SnapshotMethod.__init__(self, 'tgz', name, seg) self.prefix = '%s@%s' % (seg.dbdir, self.name) self.tgzname = self.prefix + '.tgz' self.tgzpath = os.path.join(self.seg.toppath, self.tgzname) self.set_fullname( (self.seg.hostname, self.tgzpath) ) def createSnapshot(self): msg('Creating snapshot %s:%s' % self.fullname) cmd = ('cd %s && ' % self.seg.toppath) cmd = cmd + ('rm -f %s && ' % self.tgzname) cmd = cmd + ('({ which gtar > /dev/null && TAR=gtar || TAR=tar; } ; $TAR cfz %s %s)' % (self.tgzname, self.seg.dbdir)) (rc, out) = ssh(self.seg.hostname, cmd) if rc: # some errors occurred ... clean up self.deleteSnapshot() else: msg(' ... created %s:%s' % self.fullname) return rc def deleteSnapshot(self): msg('Deleting snapshot %s:%s' % self.fullname) cmd = 'rm -f %s' % (self.tgzpath) (rc, out) = ssh(self.seg.hostname, cmd) return rc def checkSnapshot(self): msg('Checking snapshot %s:%s' % self.fullname) cmd = ('({ which gtar > /dev/null && TAR=gtar || TAR=tar; } ; $TAR tfz %s > /dev/null && ls -l %s) 2>&1' % (self.tgzpath, self.tgzpath)) (rc, out) = ssh(self.seg.hostname, cmd) lines = out.split('\n') return (rc, lines) def restoreSnapshot(self): msg('Restoring snapshot %s:%s' % self.fullname) cmd = ('rm -rf %s; cd %s && ({ which gtar > /dev/null && TAR=gtar || TAR=tar; } ; $TAR xfz %s) 2> /dev/null' % (self.seg.datapath, self.seg.toppath, self.tgzname)) (rc, out) = ssh(self.seg.hostname, cmd) return rc class ZfsSnapshot(SnapshotMethod): '''Redefine the operations on segments using ZFS snapshots.''' def __init__(self, name, seg): SnapshotMethod.__init__(self, 'zfs', name, seg) (hname, mpoint) = getZfsMountpoint(self.seg.hostname, self.seg.datapath) if not hname or not mpoint: msg('Error: unable to find zfs mountpoint for %s:%s' % (self.seg.hostname, self.seg.datapath)) return None # note: hname is slightly different from self.seg.hostname(). # hname is what the shell 'hostname' command returned. self.set_fullname( (hname, mpoint + '@' + self.name) ) def createSnapshot(self): (hname, sname) = self.fullname cmd = 'zfs snapshot ' + sname (rc, out) = ssh(hname, cmd) if not rc: msg('Created snapshot %s:%s' % self.fullname) return rc def deleteSnapshot(self): (hname, sname) = self.fullname msg('Deleting snapshot of %s:%s' % self.fullname) cmd = 'zfs destroy %s' % (sname) (rc, out) = ssh(hname, cmd) return rc def checkSnapshot(self): (hname, sname) = self.fullname msg('Checking snapshot of %s:%s' % self.fullname) cmd = 'zfs list -t snapshot %s 2>&1' % sname (rc, out) = ssh(hname, cmd) return (rc, out.split('\n')) def restoreSnapshot(self): (hname, sname) = self.fullname msg('Restoring snapshot of %s:%s' % self.fullname) cmd = 'zfs rollback ' + sname (rc, out) = ssh(hname, cmd) return rc ############ def pmap(func, jlist, numThreads = 16): if (numThreads > len(jlist)): numThreads = len(jlist) inq = Queue.Queue(len(jlist)) for i in jlist: inq.put(i) outq = Queue.Queue(len(jlist)) def work(): try: while True: outq.put((None, func(inq.get_nowait()))) except Queue.Empty: pass except: outq.put( (sys.exc_info(), None) ) # drain try: while True: inq.get_nowait() except Queue.Empty: pass thread = [threading.Thread(target=work) for i in xrange(numThreads)] for t in thread: t.start() for t in thread: t.join() ret = [] try: while True: (ex, result) = outq.get_nowait() if ex: raise ex[0], ex[1], ex[2] ret.append(result) except Queue.Empty: pass return ret def test_pmap(): import random, time def p(x): time.sleep(random.random()); print x; return x jlist = [x for x in "abcdefghijklmnopqrstuvwxyz"] return pmap(p, jlist) def ctlpath(dbdir, name): home = "~%s" % GV.opt['-u'] dir = ".gpsnap" fname = "%s@%s.sn2" % (dbdir, name) return (home, dir, fname) ############ class ControlInfo: def __init__(self, name, snapshots, type, etime): (self.name, self.snapshots, self.etime) = (name, snapshots, etime) self.etime = self.etime.replace(microsecond=0) self.type = type; def delete(self, master): fpath = ctlpath(master.dbdir, self.name) fpath = os.path.join(fpath[0], fpath[1], fpath[2]) cmd = 'rm -f %s' % fpath (rc, out) = ssh(master.hostname, cmd) return rc def write(self, master): (home, dir, fname) = ctlpath(master.dbdir, self.name) cmd = ('cd %s && mkdir -p %s && cd %s && cat > %s' % (home, dir, dir, fname)) line = [] line.append('name: ' + self.name) line.append('type: ' + self.type) line.append('etime: ' + str(self.etime)) for i in xrange(len(self.snapshots)): line.append('segment' + str(i) + ': ' + str(self.snapshots[i].seg)) line.append('') (rc, out) = ssh(master.hostname, cmd, '\n'.join(line)) if not rc: msg('Control file at %s:%s/%s/%s' % (master.hostname, home, dir, fname)) return rc @staticmethod def parse(f): dict = {} for line in f: line = line.strip() if len(line) > 0 and line[0] == '#': continue line = line.split(':', 1) if len(line) != 2: continue dict[line[0].strip()] = line[1].strip() if not dict.get('name'): return None if not dict.get('type'): return None if not dict.get('etime'): return None if not dict.get('segment0'): return None segments = [] i = 0 while True: n = dict.get('segment' + str(i)) if not n: break segments.append(Segment(n)) i = i + 1 etime = datetime.datetime.strptime(dict['etime'], '%Y-%m-%d %H:%M:%S') snapshots = mkSnapshots(segments, dict['name'], dict['type']) return ControlInfo(dict['name'], snapshots, dict['type'], etime) @staticmethod def read(name): (toppath, dbdir) = os.path.split(MASTER_DATA_DIRECTORY) (home, dir, fname) = ctlpath(dbdir, name) cmd = ('cd %s && test -d %s && cd %s && test -e %s && cat %s' % (home, dir, dir, fname, fname)) (rc, out) = ssh('localhost', cmd) ctl = ControlInfo.parse(out.split('\n')) return ctl @staticmethod def list(): (toppath, dbdir) = os.path.split(MASTER_DATA_DIRECTORY) fpath = ctlpath(dbdir, '') fpath = os.path.join(fpath[0], fpath[1], '*@*.sn2') p = os.popen('''bash -c 'ls -1 %s 2> /dev/null' ''' % fpath) out = p.readlines() p.close() ret = [] for fpath in out: fpath = fpath.strip() f = None try: f = open(fpath); x = ControlInfo.parse(f) if x: ret.append(x) except IOError: pass finally: f and f.close() return ret def mkSnapshots(segments, name, type): segments = segments[:] random.shuffle(segments) if type == 'zfs': snapshots = pmap(lambda s: ZfsSnapshot(name, s), segments) else: snapshots = map(lambda s: TgzSnapshot(name, s), segments) htab = {} for (fn, s) in map(lambda s: (s.fullname, s), snapshots): htab[fn] = s return map(lambda k: htab[k], htab.keys()) ############ def pstop(segments): def action(hostname): cmd = "ps -ef | grep postgres | grep -v grep | awk '{print $2}' | xargs pstop" (rc, out) = ssh(hostname, cmd) return rc masters = filter(lambda s: s.content == '-1', segments) segments = filter(lambda s: s.content != '-1', segments) vmsg('Suspending Masters') pmap(lambda s: action(s.hostname), masters) vmsg('Suspending Segments') pmap(lambda s: action(s.hostname), segments) msg('GPDB suspended.') ############ def prun(segments): def action(hostname): cmd = "ps -ef | grep postgres | grep -v grep | awk '{print $2}' | xargs prun" (rc, out) = ssh(hostname, cmd) return rc masters = filter(lambda s: s.content == '-1', segments) segments = filter(lambda s: s.content != '-1', segments) vmsg('Resuming Segments') pmap(lambda s: action(s.hostname), segments) vmsg('Resuming Masters') pmap(lambda s: action(s.hostname), masters) msg('GPDB resumed.') ############ def createSnapshot(name): ctlInfo = ControlInfo.read(name) if ctlInfo: die("Snapshot '%s' exists." % name) # need gp_configuration print 'Create a %s snapshot.' % (GV.opt['-z'] and 'zfs' or 'tgz') print 'Retrieving gp_configuration ... ' stime = datetime.datetime.now() CMD = ("python %s -f -d %s %s" % (os.path.join(sys.path[0], 'gpgetconfig.py'), MASTER_DATA_DIRECTORY, GV.opt['-u'] and '-u ' + GV.opt['-u'] or '')) (rc, out) = runas(CMD) if rc: die("Unable to retrieve gp_configuration") vvmsg(out) out = filter(lambda x: x.find('[gpgetconfig]') == 0, out) segments = [Segment(line.split(']', 1)[1]) for line in out] # shut it down suspend = GV.opt['-z'] if suspend: if not confirm('This will suspend the database.'): die('Aborted by user.') vmsg('Suspending gpdb ...') pstop(segments) else: if not confirm('This will shutdown the database'): die('Aborted by user.') vmsg("Stopping gpdb ...") runas('gpstop -af') try: # make the snapshots objects snapshots = mkSnapshots(segments, name, GV.opt['-z'] and 'zfs' or 'tgz') # take the snapshots in parallel erows = filter(lambda (s, rc): rc, pmap(lambda s: (s, s.createSnapshot()), snapshots)) # if error -> rollback if erows: emsg = (["Create failed:"] + [" unable to create %s:%s" % s.fullname for (s, rc) in erows]) # delete the snapshots map(lambda s: (s, s.deleteSnapshot()), snapshots) #pmap(lambda s: (s, s.deleteSnapshot()), snapshots) die("\n".join(emsg)) # create control file etime = datetime.datetime.now() ctlInfo = ControlInfo(name, snapshots, GV.opt['-z'] and 'zfs' or 'tgz', etime) # write the control file to the masters masters = filter(lambda s: s.content == '-1', segments) erows = filter(lambda (m, rc): rc, [(m, ctlInfo.write(m)) for m in masters]) # if error -> rollback if erows: emsg = (["Create failed:"] + [" cannot create control file %s:%s" % (m.hostname, "/".join(ctlpath(m.dbdir, name))) for (m, rc) in erows]) # delete the snapshots pmap(lambda s: (s, s.deleteSnapshot()), snapshots) pmap(lambda m: (m, ctlInfo.delete(m)), masters) die("\n".join(emsg)) msg("Created. Elapsed %s." % humantime(etime - stime)) finally: if suspend: prun(segments) ############ def restoreSnapshot(name): ctlInfo = ControlInfo.read(name) if not ctlInfo: die("Unable to find snapshot '%s'" % name) if not confirm("Restore snapshot '%s'.\nThis will shutdown the database." % name): die("Aborted by user.") stime = datetime.datetime.now() # shut it down runas('gpstop -af') snapshots = ctlInfo.snapshots[:] random.shuffle(snapshots) erows = filter(lambda (s,(rc,lines)): rc, pmap(lambda s: (s, s.checkSnapshot()), snapshots)) if erows: emsg = (["Snapshot failure"] + [" Bad/missing snapshot of %s:%s" % s.fullname for (s, rc) in erows]) die("\n".join(emsg)) if not confirm("\n".join(["\nContinue to *DELETE* database and restore snapshot.", "THIS IS THE POINT OF NO RETURN."])): die("Aborted by user.") erows = filter(lambda (s,rc): rc, pmap(lambda s: (s, s.restoreSnapshot()), snapshots)) if erows: emsg = (["Restore failed:"] + [" unable to restore %s:%s" % s.fullname for (s, rc) in erows]) die("\n".join(emsg)) etime = datetime.datetime.now() msg("Restored. Elapsed %s." % humantime(etime - stime)) ############ def infoSnapshot(name): ctlInfo = ControlInfo.read(name) if not ctlInfo: die("Unable to find snapshot '%s'" % name) msg('Snapshot name: ' + ctlInfo.name) msg('Created : ' + str(ctlInfo.etime)) msg('Atoms : %s:%s' % ctlInfo.snapshots[0].fullname) for s in ctlInfo.snapshots[1:]: msg(" %s:%s" % s.fullname) return ctlInfo ############ def infoSnapshotDetailed(name): ctlInfo = infoSnapshot(name) msg('') msg('Obtaining for detailed info ...') snapshots = ctlInfo.snapshots[:] random.shuffle(snapshots) erows = [] for (s, (rc, lines)) in pmap(lambda s: (s, s.checkSnapshot()), snapshots): if rc: erows.append( (s, (rc, lines))) else: for x in lines: msg(' [%s:%s info] ' % s.fullname + x.strip()) for (s, (rc, lines)) in erows: for x in lines: msg(' [%s:%s error] ' % s.fullname + x.strip()) if erows: die("Error(s) detected. Snapshot is not valid.") ############ def deleteSnapshot(name): ctlInfo = ControlInfo.read(name) if not ctlInfo: msg("Snapshot '%s' does not exist" % name) return # assume there isn't any snapshots available if not confirm("Delete snapshot '%s'" % name): die("Aborted by user.") stime = datetime.datetime.now() snapshots = ctlInfo.snapshots[:] random.shuffle(snapshots) erows = filter(lambda (s,rc): rc, pmap(lambda s: (s, s.deleteSnapshot()), snapshots)) if erows: emsg = (["Delete failed:"] + [" unable to delete %s:%s" % s.fullname for (s, rc) in erows]) die("\n".join(emsg)) master_snapshots = filter(lambda s: s.seg.content == '-1', snapshots) pmap(lambda m: (m.seg, ctlInfo.delete(m.seg)), master_snapshots) etime = datetime.datetime.now() msg("Deleted. Elapsed %s." % humantime(etime - stime)) ############ def listSnapshots(name): ctlInfoList = ControlInfo.list() if not ctlInfoList: msg("No snapshot exists") return ctlInfoList.sort(lambda x,y: x.etime > y.etime) for i in ctlInfoList: if not name or name == i.name: print '%s %s %s' % (i.type, str(i.etime), i.name) ############ def main(): global MASTER_DATA_DIRECTORY MASTER_DATA_DIRECTORY = strip_trailing_slash(MASTER_DATA_DIRECTORY) parseCommandLine() if GV.opt['-c']: createSnapshot(GV.snapname) elif GV.opt['-r']: restoreSnapshot(GV.snapname) elif GV.opt['-d']: deleteSnapshot(GV.snapname) elif GV.opt['-i']: infoSnapshot(GV.snapname) elif GV.opt['-I']: infoSnapshotDetailed(GV.snapname) elif GV.opt['-l']: listSnapshots(GV.snapname) else: usage('Error: invalid flags and/or arguments') if __name__ == '__main__': main()
server.py
from waitress import serve from flask import Flask, request, jsonify import logging import threading import http import base64 import json import opentracing class DriverServer(object): trace_context = None trace_context_dict = None final_error = None output_completed = False def __init__(self, tracer): self.tracer = tracer self.input_completed = threading.Event() self.final_event = threading.Event() self.stop_event = threading.Event() self.thread = threading.Thread(target=self.run, args=()) self.thread.daemon = True self.thread.start() def wait_for_input_completed_signal(self): self.input_completed.wait() def signal_output_completed(self): if self.final_event.is_set(): logging.warning("signal_output_completed: final_event already set") return self.output_completed = True self.final_event.set() def signal_final_error(self, error_message): if self.final_event.is_set(): logging.warning("signal_final_error: final_event already set") return self.final_error = '%s' % error_message self.final_event.set() def run(self): app = Flask(__name__) app.add_url_rule('/start', view_func=self.start_handler, methods=["PUT"]) app.add_url_rule('/status', view_func=self.status_handler, methods=["GET"]) app.add_url_rule('/stop', view_func=self.stop_handler, methods=["PUT"]) serve( app, host="0.0.0.0", port=8888, channel_timeout=100000, threads=3, ) def start_handler(self): logging.info("received start signal") span_context = self.tracer.extract( format=opentracing.propagation.Format.HTTP_HEADERS, carrier=dict(request.headers) ) with self.tracer.start_active_span( 'start_handler', child_of=span_context, tags={ opentracing.ext.tags.SPAN_KIND: opentracing.ext.tags.SPAN_KIND_RPC_SERVER, } ): trace_context_string = request.headers['X-DLTK-RootContext'] if trace_context_string: trace_context_bytes = trace_context_string.encode() trace_context_bytes = base64.b64decode(trace_context_bytes) trace_context_dict = json.loads(trace_context_bytes) trace_context = opentracing.tracer.extract( format=opentracing.propagation.Format.TEXT_MAP, carrier=trace_context_dict ) with self.tracer.start_active_span( 'signal_start', tags={ opentracing.ext.tags.SPAN_KIND: opentracing.ext.tags.SPAN_KIND_PRODUCER, } ) as scope: self.trace_context_dict = {} opentracing.tracer.inject( span_context=scope.span, format=opentracing.propagation.Format.TEXT_MAP, carrier=self.trace_context_dict ) # self.trace_context self.input_completed.set() return '', http.HTTPStatus.OK def status_handler(self): span_context = self.tracer.extract( format=opentracing.propagation.Format.HTTP_HEADERS, carrier=dict(request.headers) ) with self.tracer.start_active_span( 'status_handler', child_of=span_context, tags={ opentracing.ext.tags.SPAN_KIND: opentracing.ext.tags.SPAN_KIND_RPC_SERVER, } ): if self.final_event.is_set(): if self.output_completed: logging.info("reporting status to Splunk: %s" % "completed") return jsonify({ "status": "completed", }) if self.final_error: logging.info("reporting status to Splunk: %s" % "error") return jsonify({ "status": "error", "error": self.final_error, }) logging.info("reporting status to Splunk: %s" % "error") return jsonify({ "status": "error", "error": "unknown", }) logging.info("reporting status to Splunk: %s" % "running") return jsonify({ "status": "running", }) def stop_handler(self): logging.info("received stop signal") span_context = self.tracer.extract( format=opentracing.propagation.Format.HTTP_HEADERS, carrier=dict(request.headers) ) with self.tracer.start_active_span( 'stop_handler', child_of=span_context, tags={ opentracing.ext.tags.SPAN_KIND: opentracing.ext.tags.SPAN_KIND_RPC_SERVER, } ): self.stop_event.set() return '', http.HTTPStatus.OK def wait_for_stop_signal(self): logging.info("wait_for_stop_signal...") self.stop_event.wait()
network_monitor.py
#!c:\\python\\python.exe import threading import getopt import time import sys import os # noinspection PyUnresolvedReferences import pcapy import impacket import impacket.ImpactDecoder from boofuzz import pedrpc from boofuzz import helpers MAX_PACKET_LENGTH = 65535 # Max packet length for IP capture def log_error(message=None): try: sys.stderr.write("ERR> %s\n" % message) or sys.exit(1) except Exception, e: print e sys.exit(1) def get_ifs(): """ Get a list of network interfaces on the system. :rtype : list[str] :return: List of network interfaces. """ ifs = [] for index, pcapy_device in enumerate(pcapy.findalldevs()): ifs.append(pcapy_device) return ifs def create_usage(ifs): """ Return usage string. :type ifs: list[str] :param ifs: List of network interfaces to include in help text. :rtype : str :return: Usage text. """ message = """USAGE: network_monitor.py [-d|--device DEVICE #] device to sniff on (see list below) [-f|--filter PCAP FILTER] BPF filter string [-P|--log_path PATH] log directory to store pcaps to [-l|--log_level LEVEL] log level: default 1, increase for more verbosity [--port PORT] TCP port to bind this agent to Network Device List: """ for index, pcapy_device in enumerate(ifs): # if we are on windows, try and resolve the device UUID into an IP address. if sys.platform.startswith("win"): import _winreg try: # extract the device UUID and open the TCP/IP parameters key for it. pcapy_device = pcapy_device[pcapy_device.index("{"):pcapy_device.index("}") + 1] subkey = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\%s" % pcapy_device key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey) # if there is a DHCP address snag that, otherwise fall back to the IP address. try: ip = _winreg.QueryValueEx(key, "DhcpIPAddress")[0] except Exception: ip = _winreg.QueryValueEx(key, "IPAddress")[0][0] pcapy_device = pcapy_device + "\t" + ip except Exception: pass message += " [%d] %s\n" % (index, pcapy_device) return message class PcapThread(threading.Thread): def __init__(self, network_monitor, pcap, pcap_save_path): self.network_monitor = network_monitor self.pcap = pcap self.decoder = None self.dumper = self.pcap.dump_open(pcap_save_path) self.active = True self.data_bytes = 0 # register the appropriate decoder. if pcap.datalink() == pcapy.DLT_EN10MB or pcap.datalink() == pcapy.DLT_NULL: self.decoder = impacket.ImpactDecoder.EthDecoder() elif pcap.datalink() == pcapy.DLT_LINUX_SLL: self.decoder = impacket.ImpactDecoder.LinuxSLLDecoder() else: raise Exception threading.Thread.__init__(self) def packet_handler(self, header, data): # add the captured data to the PCAP. self.dumper.dump(header, data) # increment the captured byte count. self.data_bytes += len(data) # log the decoded data at the appropriate log level. self.network_monitor.log(self.decoder.decode(data), 15) def run(self): # process packets while the active flag is raised. while self.active: self.pcap.dispatch(0, self.packet_handler) class NetworkMonitorPedrpcServer(pedrpc.Server): def __init__(self, host, port, monitor_device, bpf_filter="", path="./", level=1): """ @type host: str @param host: Hostname or IP address to bind server to @type port: int @param port: Port to bind server to @type monitor_device: str @param monitor_device: Name of device to capture packets on @type bpf_filter: str @param bpf_filter: BPF filter to apply to the capture @type path: str @param path: (Optional, def="./") Path to save recorded PCAPs to @type level: int @param level: (Optional, def=1) Log output level, increase for more verbosity """ # initialize the PED-RPC server. pedrpc.Server.__init__(self, host, port) self.device = monitor_device self.filter = bpf_filter self.log_path = path self.log_level = level self.pcap = None self.pcap_thread = None # ensure the log path is valid. if not os.access(self.log_path, os.X_OK): self.log("invalid log path: %s" % self.log_path) raise Exception self.log("Network Monitor PED-RPC server initialized:") self.log("\t device: %s" % self.device) self.log("\t filter: %s" % self.filter) self.log("\t log path: %s" % self.log_path) self.log("\t log_level: %d" % self.log_level) self.log("Awaiting requests...") def __stop(self): """ Kill the PCAP thread. """ if self.pcap_thread: self.log("stopping active packet capture thread.", 10) self.pcap_thread.active = False self.pcap_thread = None # noinspection PyMethodMayBeStatic def alive(self): """ Returns True. Useful for PED-RPC clients who want to see if the PED-RPC connection is still alive. """ return True def post_send(self): """ This routine is called after the fuzzer transmits a test case and returns the number of bytes captured by the PCAP thread. @rtype: Integer @return: Number of bytes captured in PCAP thread. """ # grab the number of recorded bytes. data_bytes = self.pcap_thread.data_bytes # stop the packet capture thread. self.__stop() self.log("stopped PCAP thread, snagged %d bytes of data" % data_bytes) return data_bytes def pre_send(self, test_number): """ This routine is called before the fuzzer transmits a test case and spin off a packet capture thread. """ self.log("initializing capture for test case #%d" % test_number) # open the capture device and set the BPF filter. self.pcap = pcapy.open_live(self.device, MAX_PACKET_LENGTH, 1, 100) self.pcap.setfilter(self.filter) # instantiate the capture thread. pcap_log_path = "%s/%d.pcap" % (self.log_path, test_number) self.pcap_thread = PcapThread(self, self.pcap, pcap_log_path) self.pcap_thread.start() def log(self, msg="", level=1): """ If the supplied message falls under the current log level, print the specified message to screen. @type msg: str @param msg: Message to log """ if self.log_level >= level: print "[%s] %s" % (time.strftime("%I:%M.%S"), msg) def retrieve(self, test_number): """ Return the raw binary contents of the PCAP saved for the specified test case number. @type test_number: int @param test_number: Test number to retrieve PCAP for. """ self.log("retrieving PCAP for test case #%d" % test_number) pcap_log_path = "%s/%d.pcap" % (self.log_path, test_number) fh = open(pcap_log_path, "rb") data = fh.read() fh.close() return data def set_filter(self, new_filter): self.log("updating PCAP filter to '%s'" % new_filter) self.filter = new_filter def set_log_path(self, new_log_path): self.log("updating log path to '%s'" % new_log_path) self.log_path = new_log_path def main(): ifs = get_ifs() usage_message = create_usage(ifs) rpc_port = 26001 opts = None # parse command line options. try: opts, args = getopt.getopt(sys.argv[1:], "d:f:P:l:", ["device=", "filter=", "log_path=", "log_level=", "port="]) except getopt.GetoptError: log_error(usage_message) device = None pcap_filter = "" log_path = "./" log_level = 1 for opt, arg in opts: if opt in ("-d", "--device"): device = ifs[int(arg)] if opt in ("-f", "--filter"): pcap_filter = arg if opt in ("-P", "--log_path"): log_path = arg if opt in ("-l", "--log_level"): log_level = int(arg) if opt in "--port": rpc_port = int(arg) if not device: log_error(usage_message) try: servlet = NetworkMonitorPedrpcServer("0.0.0.0", rpc_port, device, pcap_filter, log_path, log_level) t = threading.Thread(target=servlet.serve_forever) t.daemon = True t.start() # Now wait in a way that will not block signals like SIGINT helpers.pause_for_signal() except Exception: pass if __name__ == "__main__": main()
acrobot_a3c.py
'''Example of A3C running on Acrobot environment ''' import argparse import time import threading import tensorflow as tf import gym # import multiprocessing import ac_net import worker PARSER = argparse.ArgumentParser(description=None) PARSER.add_argument('-d', '--device', default='cpu', type=str, help='choose device: cpu/gpu') PARSER.add_argument('-e', '--episodes', default=500, type=int, help='number of episodes') PARSER.add_argument('-w', '--workers', default=4, type=int, help='number of workers') PARSER.add_argument('-l', '--log_dir', default='acrobot_logs', type=str, help='log directory') ARGS = PARSER.parse_args() print ARGS DEVICE = ARGS.device STATE_SIZE = 6 ACTION_SIZE = 3 LEARNING_RATE = 0.0001 GAMMA = 0.99 T_MAX = 5 # NUM_WORKERS = multiprocessing.cpu_count() NUM_WORKERS = ARGS.workers NUM_EPISODES = ARGS.episodes LOG_DIR = ARGS.log_dir N_H1 = 300 N_H2 = 300 def main(): '''Example of A3C running on Acrobot environment''' tf.reset_default_graph() history = [] with tf.device('/{}:0'.format(DEVICE)): sess = tf.Session() global_model = ac_net.AC_Net( STATE_SIZE, ACTION_SIZE, LEARNING_RATE, 'global', n_h1=N_H1, n_h2=N_H2) workers = [] for i in xrange(NUM_WORKERS): env = gym.make('Acrobot-v1') env._max_episode_steps = 3000 workers.append(worker.Worker(env, state_size=STATE_SIZE, action_size=ACTION_SIZE, worker_name='worker_{}'.format(i), global_name='global', lr=LEARNING_RATE, gamma=GAMMA, t_max=T_MAX, sess=sess, history=history, n_h1=N_H1, n_h2=N_H2, logdir=LOG_DIR)) sess.run(tf.global_variables_initializer()) for workeri in workers: worker_work = lambda: workeri.work(NUM_EPISODES) thread = threading.Thread(target=worker_work) thread.start() if __name__ == "__main__": main()
cron_dispatch.py
from flask import Blueprint from multiprocessing.process import Process from backend.incoming.entry_points import every_hour from database.analytics.system_load import EveryHourOTP from requests import post from socket import gethostname cron_dispatch = Blueprint("cron_dispatch", __name__) def start_every_hour(): """ This is the function that should be called by cron directly. This function makes a post request to dispatch_every hour. This is so that the every hour job runs with the same concurrency variables as on_receive. To prevent extraneous and malicious calls to every_hour, a one time password is used. """ password = EveryHourOTP.generate_password() # TODO: switch to https in production when servers have wildcard certificate resp = post("https://%s/dispatch_every_hour/%s" % (gethostname(), password)) resp.raise_for_status() @cron_dispatch.route("/dispatch_every_hour/<one_time_password>", methods=["POST"]) def dispatch_every_hour(one_time_password): """ This is the receiving point of start_every_hour's post request. It checks that the one time password is correct and then dispatches every_hour. """ EveryHourOTP.check_password(one_time_password) Process(target=every_hour).start() return "success"
train.py
from __future__ import print_function import numpy as np from tqdm import tqdm import multiprocessing as mp import math import datetime from absl import app from absl import flags from env import Environment from game import Game from model_mine import Network from config import get_config import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = "2" FLAGS = flags.FLAGS flags.DEFINE_integer('num_agents', 5, 'number of agents') flags.DEFINE_string('baseline', 'avg', 'avg: use average reward as baseline, best: best reward as baseline') flags.DEFINE_integer('num_iter', 100, 'Number of iterations each agent would run') GRADIENTS_CHECK=True def central_agent(config, game, model_weights_queues, experience_queues): network = Network(config, game.input_state_dims, game.action_dim, master=True) network.save_hyperparams(config) start_step = network.restore_ckpt() for step in tqdm(range(start_step, config.max_step), ncols=70, initial=start_step): network.ckpt.step.assign_add(1) if config.model == 'actor_critic': model_weights = network.model.get_weights() elif config.model == 'pure_policy': model_weights = network.policy_model.get_weights() # print(config.num_agents) for i in range(config.num_agents): model_weights_queues[i].put(model_weights) if config.model == 'actor_critic': #assemble experiences from the agents s_batch = [] a_batch = [] r_batch = [] for i in range(config.num_agents): s_batch_agent, a_batch_agent, r_batch_agent = experience_queues[i].get() assert len(s_batch_agent) == config.num_iter, \ (len(s_batch_agent), len(a_batch_agent), len(r_batch_agent)) s_batch += s_batch_agent a_batch += a_batch_agent r_batch += r_batch_agent assert len(s_batch)*config.max_moves == len(a_batch) #used shared RMSProp, i.e., shared g """value_loss, entropy, actor_gradients, critic_gradients = network.actor_critic_train(np.array(s_batch), np.array(a_batch), np.array(r_batch).astype(np.float32), config.entropy_weight)""" actions = np.eye(game.action_dim, dtype=np.float32)[np.array(a_batch)]# batch_size * action_dim value_loss, policy_loss, entropy, actor_gradients, critic_gradients = network.actor_critic_train(np.array(s_batch), actions, np.array(r_batch).astype(np.float32), config.entropy_weight) if GRADIENTS_CHECK: for g in range(len(actor_gradients)): assert np.any(np.isnan(actor_gradients[g])) == False, ('actor_gradients', s_batch, a_batch, r_batch) for g in range(len(critic_gradients)): assert np.any(np.isnan(critic_gradients[g])) == False, ('critic_gradients', s_batch, a_batch, r_batch) if step % config.save_step == config.save_step - 1: network.save_ckpt(_print=True) #log training information actor_learning_rate = network.lr_schedule(network.actor_optimizer.iterations.numpy()).numpy() avg_value_loss = np.mean(value_loss) avg_policy_loss = np.mean(policy_loss) avg_reward = np.mean(r_batch) avg_entropy = np.mean(entropy) network.inject_summaries({ 'learning rate': actor_learning_rate, 'value loss': avg_value_loss, 'policy loss': avg_policy_loss, 'avg reward': avg_reward, 'avg entropy': avg_entropy }, step) print('lr:%f, value loss:%f, avg reward:%f, avg entropy:%f'%(actor_learning_rate, avg_value_loss, avg_reward, avg_entropy)) elif config.model == 'pure_policy': #assemble experiences from the agents s_batch = [] a_batch = [] r_batch = [] ad_batch = [] for i in range(config.num_agents): s_batch_agent, a_batch_agent, r_batch_agent, ad_batch_agent = experience_queues[i].get() assert len(s_batch_agent) == config.num_iter, \ (len(s_batch_agent), len(a_batch_agent), len(r_batch_agent), len(ad_batch_agent)) s_batch += s_batch_agent a_batch += a_batch_agent r_batch += r_batch_agent ad_batch += ad_batch_agent assert len(s_batch)*config.max_moves == len(a_batch) #used shared RMSProp, i.e., shared g #entropy, gradients = network.policy_train(np.array(s_batch), np.array(a_batch), np.array(ad_batch).astype(np.float32), config.entropy_weight) # a_batch is like [[np.array([3]), np.array([5]),...], [np.array([2]), np.array([6]),...], ...] # for example, if action_dim=3, a_batch[0]=[np.array([0]), np.array([2]),np.array([1])], #then, np.eye(game.action_dim, dtype=np.float32)[np.array(a_batch[i])] would be # [[1, 0, 0], # [0, 0, 1], # [0, 1, 0]] actions = [] for i in range(len(a_batch)): actions.append(np.eye(game.action_dim, dtype=np.float32)[np.array(a_batch[i])].reshape(-1)) actions = np.array(actions) entropy, gradients, policy_loss = network.policy_train(np.array(s_batch), actions, np.vstack(ad_batch).astype(np.float32), config.entropy_weight) if GRADIENTS_CHECK: for g in range(len(gradients)): assert np.any(np.isnan(gradients[g])) == False, (s_batch, a_batch, r_batch) if step % config.save_step == config.save_step - 1: network.save_ckpt(_print=True) #log training information learning_rate = network.lr_schedule(network.optimizer.iterations.numpy()).numpy() # avg_reward = np.asscalar(np.mean(r_batch)) # avg_advantage = np.asscalar(np.mean(ad_batch)) # avg_entropy = np.asscalar(np.mean(entropy)) # avg_policy_loss = np.asscalar(np.mean(policy_loss)) avg_reward = np.mean(r_batch) avg_advantage = np.mean(ad_batch) avg_entropy = np.mean(entropy) avg_policy_loss = np.mean(policy_loss) network.inject_summaries({ 'learning rate': learning_rate, 'avg reward': avg_reward, 'avg advantage': avg_advantage, 'avg entropy': avg_entropy, 'avg policy loss': avg_policy_loss }, step) print('lr:%f, avg reward:%f, avg advantage:%f, avg entropy:%f'%(learning_rate, avg_reward, avg_advantage, avg_entropy)) """def get_action_prob(logits): softmax = [] max_l = np.max(logits) for l in logits: softmax.append(math.exp(l-max_l)) softmax_sum = sum(softmax) softmax = np.array(softmax)/softmax_sum return softmax""" def agent(agent_id, config, game, tm_subset, model_weights_queue, experience_queue): random_state = np.random.RandomState(seed=agent_id) network = Network(config, game.input_state_dims, game.action_dim, master=False) # initial synchronization of the model weights from the coordinator model_weights = model_weights_queue.get() if config.model == 'actor_critic': network.model.set_weights(model_weights) elif config.model == 'pure_policy': network.policy_model.set_weights(model_weights) idx = 0 s_batch = [] a_batch = [] r_batch = [] if config.model == 'pure_policy': ad_batch = [] run_iteration_idx = 0 num_tms = len(tm_subset) # random_state.shuffle(tm_subset) run_iterations = config.num_iter while True: tm_idx = tm_subset[idx] #state state = game.get_state(tm_idx) s_batch.append(state) # append first then expand dims, because model need ndim=3 state = np.expand_dims(state, 0) # s_batch.append(state) #action if config.model == 'actor_critic': policy = network.actor_predict(state) policy = policy.numpy() policy = np.squeeze(policy) elif config.model == 'pure_policy': policy = network.policy_predict(state) policy = policy.numpy() policy = np.squeeze(policy) assert np.count_nonzero(policy) >= config.max_moves, (policy, state) actions = [] for i in range(config.critical_num + 1): # assert np.abs(np.sum(policy[config.action_dim*i:config.action_dim*(i+1)]) - 1 ) < 0.001 actions.append(random_state.choice(game.action_dim, 1, p=policy[config.action_dim*i:config.action_dim*(i+1)], replace=False)) # print(actions) a_batch.append(actions) #reward reward = game.reward(tm_idx, actions) r_batch.append(reward) if config.model == 'pure_policy': #advantage if config.baseline == 'avg': ad_batch.append(game.advantage(tm_idx, reward)) game.update_baseline(tm_idx, reward) elif config.baseline == 'best': best_actions = policy.argsort()[-game.max_moves:] best_reward = game.reward(tm_idx, best_actions) ad_batch.append(reward - best_reward) run_iteration_idx += 1 if run_iteration_idx >= run_iterations: # Report experience to the coordinator # instead of reporting gradients to the coordiantor if config.model == 'actor_critic': experience_queue.put([s_batch, a_batch, r_batch]) elif config.model == 'pure_policy': experience_queue.put([s_batch, a_batch, r_batch, ad_batch]) #print('report', agent_id) # synchronize the network parameters from the coordinator model_weights = model_weights_queue.get() if config.model == 'actor_critic': network.model.set_weights(model_weights) elif config.model == 'pure_policy': network.policy_model.set_weights(model_weights) del s_batch[:] del a_batch[:] del r_batch[:] if config.model == 'pure_policy': del ad_batch[:] run_iteration_idx = 0 # Update idx idx += 1 # if idx == num_tms: if idx == num_tms - 1:# the current action is for the next state, so the last state do not have reward # game.random_state.shuffle(tm_subset) # we can't shuffle idx = 0 def main(_): config = get_config(FLAGS) or FLAGS print(config.num_iter) env = Environment(config, is_training=True) game = Game(config, env) model_weights_queues = [] experience_queues = [] if FLAGS.num_agents == 0: config.num_agents = mp.cpu_count() - 1 #FLAGS.num_iter = env.tm_cnt//config.num_agents print('agent num: %d, iter num: %d\n'%(config.num_agents, FLAGS.num_iter)) for _ in range(config.num_agents): model_weights_queues.append(mp.Queue(1)) experience_queues.append(mp.Queue(1)) tm_set = np.arange(env.tm_cnt - env.tm_history + 1) tm_subsets = np.array_split(tm_set, config.num_agents) coordinator = mp.Process(target=central_agent, args=(config, game, model_weights_queues, experience_queues)) coordinator.start() agents = [] for i in range(config.num_agents): agents.append(mp.Process(target=agent, args=(i, config, game, tm_subsets[i], model_weights_queues[i], experience_queues[i]))) for i in range(config.num_agents): agents[i].start() ##UnparsedFlagAccessError: Trying to access flag --num_iter before flags were parsed. for i in range(config.num_agents): agents[i].join() coordinator.join() if __name__ == '__main__': app.run(main)
twitch-indicator.py
#!/usr/bin/env python3 import threading import webbrowser import json import urllib.request import gi gi.require_version('AppIndicator3', '0.1') gi.require_version('Notify', '0.7') gi.require_version('Gtk', '3.0') from gi.repository import AppIndicator3 as appindicator # noqa: E402 from gi.repository import GLib, Gio, Notify, GdkPixbuf # noqa: E402 from gi.repository import Gtk as gtk # noqa: E402 TWITCH_BASE_URL = 'https://www.twitch.tv/' TWITCH_API_URL = 'https://api.twitch.tv/helix/' DEFAULT_AVATAR = ('http://static-cdn.jtvnw.net/' 'jtv_user_pictures/xarth/404_user_150x150.png') CLIENT_ID = 'oe77z9pq798tln7ngil0exwr0mun4hj' class Twitch: def fetch_followed_channels(self, username): """Fetch user followed channels and return a list with channel names. """ try: self.followed_channels = [] self.req = urllib.request.Request( f'{TWITCH_API_URL}users?login={username}') self.req.add_header('Client-ID', CLIENT_ID) self.f = urllib.request.urlopen(self.req) self.data = json.loads(self.f.read()) self.req = urllib.request.Request( f'{TWITCH_API_URL}users/follows' f'?from_id={self.data["data"][0]["id"]}') # f'&first=100') self.req.add_header('Client-ID', CLIENT_ID) self.f = urllib.request.urlopen(self.req) self.data = json.loads(self.f.read()) # Return 404 if user does not exist try: if (self.data['status'] == 404): return 404 except KeyError: pass self.pages = int((self.data['total'] - 1) / 100) for page in range(self.pages + 1): if page != 0: self.req = urllib.request.Request( f'{TWITCH_API_URL}users/follows?from_id={username}' f'&client_id={CLIENT_ID}&first=100' f'&after={self.data["cursor"]}') self.req.add_header('Client-ID', CLIENT_ID) self.f = urllib.request.urlopen(self.req) self.data = json.loads(self.f.read()) for channel in self.data['data']: self.followed_channels.append(channel['to_name']) return self.followed_channels except IOError: return None def fetch_live_streams(self, channels): """Fetches live streams data from Twitch, and returns as list of dictionaries. """ try: self.channels_count = len(channels) self.live_streams = [] self.pages = int((self.channels_count - 1) / 75) for page in range(self.pages + 1): self.offset = (page * 75) + 75 if (self.offset % 75 > 0): self.offset = self.channels_count self.channels_offset = channels[(page * 75):self.offset] self.req = urllib.request.Request( f'{TWITCH_API_URL}streams' f'?user_login={"&user_login=".join(self.channels_offset)}') self.req.add_header('Client-ID', CLIENT_ID) self.f = urllib.request.urlopen(self.req) self.data = json.loads(self.f.read()) for stream in self.data['data']: # For some reason sometimes stream status and game is not # present in twitch API. try: self.status = stream['title'] except KeyError: self.status = '' # Show default if channel owner has not set his avatar req = urllib.request.Request( f'{TWITCH_API_URL}users?login={stream["user_name"]}') req.add_header('Client-ID', CLIENT_ID) f = urllib.request.urlopen(req) dataimg = json.loads(f.read()) img = dataimg['data'][0]['profile_image_url'] if img is None: self.response = urllib.request.urlopen(DEFAULT_AVATAR) else: self.response = urllib.request.urlopen(img) self.loader = GdkPixbuf.PixbufLoader.new() self.loader.set_size(32, 32) self.loader.write(self.response.read()) self.loader.close() req = urllib.request.Request( f'{TWITCH_API_URL}games?id={stream["game_id"]}') req.add_header('Client-ID', CLIENT_ID) f = urllib.request.urlopen(req) datagame = json.loads(f.read()) st = { 'name': stream['user_name'], 'game': datagame['data'][0]['name'], 'status': self.status, 'image': img, 'pixbuf': self.loader, 'url': f"{TWITCH_BASE_URL}{stream['user_name']}" } self.live_streams.append(st) return self.live_streams except IOError: return None class Indicator(): SETTINGS_KEY = 'apps.twitch-indicator' LIVE_STREAMS = [] def __init__(self): self.timeout_thread = None # Create applet self.a = appindicator.Indicator.new( 'Twitch indicator', # TODO: hardcoded paths seem wrong '/usr/share/icons/twitch-indicator.svg', appindicator.IndicatorCategory.APPLICATION_STATUS ) self.a.set_status(appindicator.IndicatorStatus.ACTIVE) # Load settings self.settings = Gio.Settings.new(self.SETTINGS_KEY) # Setup menu self.menu = gtk.Menu() self.menuItems = [ gtk.MenuItem(label='Check now'), gtk.SeparatorMenuItem(), gtk.MenuItem(label='Settings'), gtk.MenuItem(label='Quit') ] self.menuItems[0].connect( 'activate', self.refresh_streams_init, [True]) self.menuItems[-2].connect('activate', self.settings_dialog) self.menuItems[-1].connect('activate', self.quit) for i in self.menuItems: self.menu.append(i) self.a.set_menu(self.menu) self.menu.show_all() self.refresh_streams_init(None) def open_link(self, widget, url): """Opens link in a default browser.""" webbrowser.open_new_tab(url) def refresh_streams_init(self, widget, button_activate=False): """Initializes thread for stream refreshing.""" self.t = threading.Thread(target=self.refresh_streams) self.t.daemon = True self.t.start() if (button_activate is False): self.timeout_thread = threading.Timer(self.settings.get_int( 'refresh-interval') * 60, self.refresh_streams_init, [None]) self.timeout_thread.start() def settings_dialog(self, widget): """Shows applet settings dialog.""" self.dialog = gtk.Dialog( 'Settings', None, 0, (gtk.STOCK_CANCEL, gtk.ResponseType.CANCEL, gtk.STOCK_OK, gtk.ResponseType.OK) ) self.builder = gtk.Builder() # TODO: hardcoded paths seem wrong self.builder.add_from_file( '/usr/share/twitch-indicator/twitch-indicator.glade') self.builder.get_object('twitch_username').set_text( self.settings.get_string('twitch-username')) self.builder.get_object('show_notifications').set_active( self.settings.get_boolean('enable-notifications')) self.builder.get_object('refresh_interval').set_value( self.settings.get_int('refresh-interval')) self.box = self.dialog.get_content_area() self.box.add(self.builder.get_object('grid1')) self.response = self.dialog.run() if self.response == gtk.ResponseType.OK: self.settings.set_string( 'twitch-username', self.builder.get_object('twitch_username').get_text()) self.settings.set_boolean( 'enable-notifications', self.builder.get_object('show_notifications').get_active()) self.settings.set_int( 'refresh-interval', self.builder.get_object('refresh_interval').get_value_as_int()) elif self.response == gtk.ResponseType.CANCEL: pass self.dialog.destroy() def disable_menu(self): """Disables check now button.""" self.menu.get_children()[0].set_sensitive(False) self.menu.get_children()[0].set_label('Checking...') def enable_menu(self): """Enables check now button.""" self.menu.get_children()[0].set_sensitive(True) self.menu.get_children()[0].set_label('Check now') def add_streams_menu(self, streams): """Adds streams list to menu.""" # Remove live streams menu if already exists if (len(self.menuItems) > 4): self.menuItems.pop(2) self.menuItems.pop(1) # Create menu self.streams_menu = gtk.Menu() self.menuItems.insert(2, gtk.MenuItem( label=f'Live channels ({len(streams)})')) self.menuItems.insert(3, gtk.SeparatorMenuItem()) self.menuItems[2].set_submenu(self.streams_menu) # Order streams by alphabetical order self.streams_ordered = sorted(streams, key=lambda k: k['name'].lower()) for index, stream in enumerate(self.streams_ordered): self.icon = gtk.Image() self.icon.set_from_pixbuf(stream['pixbuf'].get_pixbuf()) self.menu_entry = gtk.ImageMenuItem( label=f"{stream['name']} - {stream['game']}") self.menu_entry.set_image(self.icon) self.streams_menu.append(self.menu_entry) self.streams_menu.get_children()[index].connect( 'activate', self.open_link, stream['url']) for i in self.streams_menu.get_children(): i.show() # Refresh all menu by removing and re-adding menu items for i in self.menu.get_children(): self.menu.remove(i) for i in self.menuItems: self.menu.append(i) self.menu.show_all() def refresh_streams(self): """Refreshes live streams list. Also pushes notifications when needed. """ GLib.idle_add(self.disable_menu) if (self.settings.get_string('twitch-username') == ''): GLib.idle_add(self.abort_refresh, 'Twitch.tv username is not set', 'Setup your username in settings') return # Create twitch instance and fetch followed channels. self.tw = Twitch() self.followed_channels = self.tw.fetch_followed_channels( self.settings.get_string('twitch-username')) # Does user exist? if self.followed_channels == 404: GLib.idle_add( self.abort_refresh, 'Cannot retrieve followed channels from Twitch.tv', 'User does not exist.') return if self.followed_channels is None: interval = self.settings.get_int('refresh-interval') GLib.idle_add( self.abort_refresh, 'Cannot retrieve channel list from Twitch.tv', f'Retrying in {interval} minutes...') return self.live_streams = self.tw.fetch_live_streams(self.followed_channels) if self.live_streams is None: interval = self.settings.get_int('refresh-interval') GLib.idle_add( self.abort_refresh, 'Cannot retrieve live streams from Twitch.tv', f'Retrying in {interval} minutes...') return # Update menu with live streams GLib.idle_add(self.add_streams_menu, self.live_streams) # Re-enable "Check now" button GLib.idle_add(self.enable_menu) # Don't count the initial list if hasattr(self, 'notify_list'): initial = False else: initial = True # Check which streams were not live before, create separate list for # notifications and update main livestreams list. # We check live streams by URL, because sometimes Twitch API does not # show stream status, which makes notifications appear even if stream # has been live before. self.notify_list = list(self.live_streams) for x in self.LIVE_STREAMS: for y in self.live_streams: if x['url'] == y['url']: self.notify_list[:] = [ d for d in self.notify_list if d.get('url') != y['url'] ] break self.LIVE_STREAMS = self.live_streams # Push notifications of new streams if (self.settings.get_boolean('enable-notifications') and not initial): self.push_notifications(self.notify_list) def abort_refresh(self, message, description): """Updates menu with failure state message.""" # Remove previous message if already exists if (len(self.menuItems) > 4): self.menuItems.pop(2) self.menuItems.pop(1) self.menuItems.insert(2, gtk.MenuItem(label=message)) self.menuItems.insert(3, gtk.SeparatorMenuItem()) self.menuItems[2].set_sensitive(False) # Re-enable "Check now" button self.menuItems[0].set_sensitive(True) self.menuItems[0].set_label('Check now') # Refresh all menu items for i in self.menu.get_children(): self.menu.remove(i) for i in self.menuItems: self.menu.append(i) self.menu.show_all() # Push notification Notify.init('image') self.n = Notify.Notification.new(message, description, 'error').show() def push_notifications(self, streams): """Pushes notifications of every stream, passed as a list of dictionaries. """ try: for stream in streams: self.image = gtk.Image() # Show default if channel owner has not set his avatar if stream['image'] is None: self.response = urllib.request.urlopen(DEFAULT_AVATAR) else: self.response = urllib.request.urlopen(stream['image']) self.loader = GdkPixbuf.PixbufLoader.new() self.loader.write(self.response.read()) self.loader.close() Notify.init('image') self.n = Notify.Notification.new( f"{stream['name']} just went LIVE!", stream['status'], '') self.n.set_icon_from_pixbuf(stream['pixbuf'].get_pixbuf()) self.n.show() except IOError: return def main(self): """Main indicator function.""" gtk.main() def quit(self, item): """Quits the applet.""" self.timeout_thread.cancel() gtk.main_quit() if __name__ == '__main__': gui = Indicator() gui.main()
history_sample(TICKS).py
import time from tcoreapi_mq import * import tcoreapi_mq import threading g_QuoteZMQ = None g_QuoteSession = "" #實時行情回補 def OnRealTimeQuote(symbol): print("商品:", symbol["Symbol"], "成交價:",symbol["TradingPrice"], "開:", symbol["OpeningPrice"], "高:", symbol["HighPrice"], "低:", symbol["LowPrice"]) #行情消息接收 def quote_sub_th(obj,sub_port,filter = ""): socket_sub = obj.context.socket(zmq.SUB) #socket_sub.RCVTIMEO=7000 #ZMQ超時設定 socket_sub.connect("tcp://127.0.0.1:%s" % sub_port) socket_sub.setsockopt_string(zmq.SUBSCRIBE,filter) while(True): message = (socket_sub.recv()[:-1]).decode("utf-8") index = re.search(":",message).span()[1] # filter message = message[index:] message = json.loads(message) #for message in messages: if(message["DataType"]=="REALTIME"): OnRealTimeQuote(message["Quote"]) elif(message["DataType"]=="GREEKS"): OnGreeks(message["Quote"]) elif(message["DataType"]=="TICKS" or message["DataType"]=="1K" or message["DataType"]=="DK" ): #print("@@@@@@@@@@@@@@@@@@@@@@@",message) strQryIndex = "" while(True): s_history = obj.GetHistory(g_QuoteSession, message["Symbol"], message["DataType"], message["StartTime"], message["EndTime"], strQryIndex) historyData = s_history["HisData"] if len(historyData) == 0: break last = "" for data in historyData: last = data #print("歷史行情:Time:%s, Volume:%s, QryIndex:%s" % (data["Time"], data["Volume"], data["QryIndex"])) strQryIndex = last["QryIndex"] return def main(): global g_QuoteZMQ global g_QuoteSession #登入(與 TOUCHANCE zmq 連線用,不可改) g_QuoteZMQ = QuoteAPI("ZMQ","8076c9867a372d2a9a814ae710c256e2") q_data = g_QuoteZMQ.Connect("51237") print("q_data=",q_data) if q_data["Success"] != "OK": print("[quote]connection failed") return g_QuoteSession = q_data["SessionKey"] #查詢指定合约訊息 quoteSymbol = "TC.F.TWF.FITX.HOT" #print("查詢指定合約:",g_QuoteZMQ.QueryInstrumentInfo(g_QuoteSession, quoteSymbol)) #查詢指定類型合約列表 #期貨:Fut #期權:Opt #證券:Sto #print("查詢合約:",g_QuoteZMQ.QueryAllInstrumentInfo(g_QuoteSession,"Fut")) #####################################################################行情################################################ #建立一個行情線程 t2 = threading.Thread(target = quote_sub_th,args=(g_QuoteZMQ,q_data["SubPort"],)) t2.start() #資料週期 type = "TICKS" #起始時間 StrTim = '2021032100' #結束時間 EndTim = '2021032300' #資料頁數 QryInd = '0' #訂閱歷史資料 SubHis = g_QuoteZMQ.SubHistory(g_QuoteSession,quoteSymbol,type,StrTim,EndTim) print("訂閱歷史資料:",SubHis) #等待回補 #獲取回補的資料 i = 0 x = 1 while(1): #等待訂閱回補 QPong = g_QuoteZMQ.Pong(g_QuoteSession) print("第"+str(i*x)+"秒,Pong:",QPong) HisData = g_QuoteZMQ.GetHistory(g_QuoteSession, quoteSymbol, type, StrTim, EndTim, QryInd) if (len(HisData['HisData']) != 0): print("回補成功") i = 0 break print("取得歷史資料:", HisData) i = i + 1 time.sleep(x) f = open("歷史資料(TICKS).txt", 'w') f.close() while (1): # 獲取訂閱成功的全部歷史資料並另存 QPong = g_QuoteZMQ.Pong(g_QuoteSession) print(QPong) HisData = g_QuoteZMQ.GetHistory(g_QuoteSession, quoteSymbol, type, StrTim, EndTim, QryInd) for j in range(50): print("第"+str(j+QryInd)+"筆:") print(HisData['HisData'][j]) f = open("歷史資料(TICKS).txt", 'a') for key in HisData['HisData'][j]: f.write(key + ":" + HisData['HisData'][j][key] + ",") f.write('\n') i = j QryInd = str(int(QryInd) + i) if __name__ == '__main__': main()
script4.py
from multiprocessing import Process, Lock def f(lk, i): lk.acquire() try: print('hello world', i) finally: lk.release() if __name__ == '__main__': lock = Lock() for num in range(10): Process(target=f, args=(lock, num)).start()