source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
manager.py |
class JobManager:
def __init__(self, numworkers=4):
self.active_jobs = {}
self.all_jobs = {}
self.job_queue = Queue()
self.done_queue = SimpleQueue()
self.workers = [
JobWorker(self.job_queue, self.done_queue)
for _ in range(numworkers)
]
for worker in self.workers:
worker.start()
self.cleaner_worker = Thread(target=self._job_cleaner)
self.cleaner_worker.start()
def create_job(self, process, inputs, outputs):
return Job(str(uuid4()), process, [
process.parse_input(input_)
for input_ in inputs
], outputs)
def execute(self, job):
""" Execute the provided job: register it and put it in the
job queue for processing in the workers.
"""
identifier = job.identifier
if identifier in self.active_jobs:
raise Exception(f"Job {identifier} is already registered.")
self.active_jobs[identifier] = job
self.all_jobs[identifier] = job
self.job_queue.put(job)
def get_job(self, job_id):
try:
return self.all_jobs[job_id]
except KeyError:
raise Exception(f"No such job {job_id}")
def pause(self, job_id):
""" Interrupt the referenced job. It can later be resumed.
"""
job = self.get_job(job_id)
job.status = JobStatus.ACCEPTED
job.interrupt()
def resume(self, job_id):
"""
"""
job = self.get_job(job_id)
job.status = JobStatus.ACCEPTED
job.clear_interrupt()
self.job_queue.put(job)
def dismiss(self, job_id):
"""
"""
job = self.get_job(job_id)
job.status = JobStatus.DISMISSED
job.interrupt()
del self.active_jobs[job_id]
def _job_cleaner(self):
while True:
job = self.done_queue.get()
if job is None:
break
if job.error:
job.status = JobStatus.FAILED
else:
job.status = JobStatus.SUCCEEDED
print(f"cleaning job {job.identifier}")
del self.active_jobs[job.identifier]
def shutdown(self):
self.job_queue.join()
for _ in range(len(self.workers)):
self.job_queue.put(None)
self.done_queue.put(None)
for worker in self.workers:
worker.join()
self.cleaner_worker.join()
# manager protocol
def __enter__(self):
return self
def __exit__(self, *args):
self.shutdown()
|
ws_session.py | #!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import asyncio
from threading import Thread
import websockets
from ....util.logger import get_logger
from .session import Session
from .ws_server import WSServer
logger = get_logger(__name__)
class WebSocketSession(Session):
def __init__(self, ip: str, port: int, session_id: int, enums: object):
super().__init__(
session_id=session_id,
enums=enums,
)
self.ip = ip
self.port = port
def start(self) -> None:
self.wsServer = WSServer(enums=self.enums)
start_server = websockets.serve(self.wsServer.process, self.ip, self.port)
self.loop = asyncio.get_event_loop()
self.loop.run_until_complete(start_server)
self.thread = Thread(target=self.loop.run_forever)
self.thread.start()
logger.info("WebSocketSession Started!")
def stop(self) -> None:
self.loop.call_soon_threadsafe(self.loop.stop)
logger.info("WebSocketSession Stop Requested!")
self.thread.join()
logger.info("WebSocketSession Stop Completed!")
async def write(self, data: str, sleep_time: float = 0.001) -> bool:
# await self.wsServer.send_samples(data)
# await asyncio.sleep(sleep_time)
write_success = True
try:
await self.wsServer.send_samples(data)
write_success = True
except websockets.exceptions.ConnectionClosed as e:
logger.warning(e)
write_success = False
await asyncio.sleep(sleep_time)
return write_success
|
phage_per_taxon.py | """
Count the number of phages at the lowest taxonomic level so we can accumulate them later
"""
import os
import sys
import argparse
from multiprocessing import Process, Queue
import gzip
import re
from taxon import taxonomy_hierarchy_as_list, get_taxonomy_db, EntryNotInDatabaseError
__author__ = 'Rob Edwards'
def get_taxonomy(gbkf, q):
""" get the taxonomy array and return it in the queue"""
# read the genbank file and get the taxonomy id
if gbkf.endswith('.gz'):
f = gzip.open(gbkf, 'rt')
else:
f = open(gbkf, 'r')
dbxref = re.compile('/db_xref="taxon:(\d+)"')
tid = 0
for l in f:
if 'taxon' in l:
match = dbxref.search(l)
if match:
tid = int(match.groups()[0])
break
if tid == 0:
sys.stderr.write(f"FATAL: Could not find a tax id in {gbkf}\n")
sys.exit(-1)
f.close()
conn = get_taxonomy_db()
try:
l = taxonomy_hierarchy_as_list(conn, tid)
except EntryNotInDatabaseError as e:
l = ['DELETED TAXONOMY']
l.insert(0, tid)
q.put(l)
def count_phages(phagef, q):
""" Count the phages in the log file"""
# read the phage log file
if phagef.endswith('.gz'):
f = gzip.open(phagef, 'rt')
else:
f = open(phagef, 'r')
inphage = False
phages = 0
for l in f:
if 'Number of potential genes' in l:
inphage = True
if 'PROPHAGE' in l or 'Creating output files' in l:
break
if inphage and 'Kept' in l:
phages+=1
q.put(phages)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=' ')
parser.add_argument('-g', help='genbank source file for the genome', required=True)
parser.add_argument('-l', help='phispy log file', required=True)
parser.add_argument('-v', help='verbose output', action='store_true')
args = parser.parse_args()
# read the genbank file
gbkq = Queue()
g = Process(target=get_taxonomy, args=(args.g, gbkq,))
g.start()
phageq = Queue()
p = Process(target=count_phages, args=(args.l, phageq,))
p.start()
taxonomy = gbkq.get()
phagen = phageq.get()
print("\t".join(map(str, [args.g] + taxonomy + [phagen])))
p.join()
g.join()
|
OSCListener.py | #!/usr/bin/python
# OSCListener.py
#
# by Claude Heintz
# copyright 2014 by Claude Heintz Design
#
# see license included with this distribution or
# https://www.claudeheintzdesign.com/lx/opensource.html
import socket
import threading
import time
from select import select
import math
import struct
class OSCListener:
def __init__(self):
self.listen_thread = None
#########################################
#
# startListening creates the listening socket
# and creates a thread that runs the listen() method
#
#########################################
def startListening(self, port, delegate=None):
self.udpsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udpsocket.bind(('',port))
self.udpsocket.setblocking(False)
self.udpsocket.settimeout(1)
self.delegate = delegate
self.listening = True
if self.listen_thread is None:
self.listen_thread = threading.Thread(target=self.listen)
self.listen_thread.daemon = True
self.listen_thread.start()
#########################################
#
# stopListening sets a flag which will cause the listen loop to end on the next pass
# setting the delegate to None prevents messages from being sent after stopListening
# is called.
#
#########################################
def stopListening(self):
self.delegate = None
self.listening = False
#########################################
#
# listen contains a loop that runs while the self.listening flag is True
# listen uses select to determine if there is data available from the port
# if there is, packetReceived is called
# if not, the thread sleeps for a tenth of a second
#
#########################################
def listen(self):
input = [self.udpsocket]
while self.listening:
inputready,outputready,exceptready = select(input,[],[],0)
if ( len(inputready) == 1 ):
self.data,addr = self.udpsocket.recvfrom(256)
self.msglen = len(self.data)
self.packetReceived()
else:
time.sleep(0.1)
self.udpsocket.close()
self.listen_thread = None
#########################################
#
# packetReceived calls processMessageAt for each complete OSC message
# contained in the packet
#
#########################################
def packetReceived(self):
dataindex = 0
while ( (dataindex >= 0 ) and ( dataindex < self.msglen ) ):
dataindex = self.processMessageAt(dataindex);
#########################################
#
# process message extracts the addressPattern
# and argument list from the OSC message
#
# currently the only supported arguments are floats and integers and strings
#
# returns the index at the end of the complete message
#
#########################################
def processMessageAt(self, si):
oi = 0;
dl = 0;
zl = self.nextZero(si)
#insure that string will terminate with room for 4 bytes of type definition
if zl + 4 < self.msglen:
addressPattern = self.stringFrom(si)
if addressPattern.startswith('/'):
# determine the current index for the type character
tl = self.nextIndexForString(addressPattern,si)
# determine the current index for the data location
dl = self.nextIndexForIndex(self.nextZero(tl))
# if there's space for at least one argument, start a loop extracting
# arguments defined in the type string an adding them to the args list
if dl+4 <= self.msglen:
if self.data[tl] == ',':
tl += 1
args = []
done = False
while ( not done) and ( (dl+4) <= self.msglen ):
if self.data[tl] == '\x00':
done = True
elif self.data[tl] == 'f':
a = struct.unpack_from('>f', self.data, dl)
args.append(float(a[0]))
dl += 4
elif self.data[tl] == 'i':
a = struct.unpack_from('>i', self.data, dl)
args.append(int(a[0]))
elif self.data[tl] == 's':
es = nextZero(dl)
if es <= self.msglen:
a = self.stringFrom(dl)
args.append(a)
dl = nextIndexForIndex(es)
else:
done = True
oi = -1
else: #unrecognized argument don't know length
done = True
oi = -1
tl += 1
# when done with the argument extraction loop, notify the delegate
if self.delegate != None:
self.delegate.receivedOSC(addressPattern, args)
#else:
#print addressPattern
#print self.args
else: #no arguments but an address pattern, notify delegate
oi = -1
if self.delegate != None:
self.delegate.receivedOSC(addressPattern, [])
else:
oi = -1
if oi != -1:
oi = dl #dl could point to another message within the packet
return oi
#########################################
#
# nextZero searches for the next null character in the data starting at index si
#
#########################################
def nextZero(self, si):
i = si
notfound = True
s = ''
while notfound and i<self.msglen:
if self.data[i] == '\x00':
notfound = False
else:
i += 1
return i
#########################################
#
# nextIndexForString determines a 4 byte padded index
# for the length of the string starting from si
#
#########################################
def nextIndexForString(self, s, start):
ml = math.trunc(len(s) / 4) + 1;
return start + (ml*4);
#########################################
#
# nextIndexForIndex determines a 4 byte padded index
# starting from i
#
#########################################
def nextIndexForIndex(self, i):
ml = math.trunc(i / 4) + 1;
return ml*4;
#########################################
#
# extracts a null terminated string starting at index si
#
#########################################
def stringFrom(self, si):
i = si
noterm = True
s = ''
while noterm and i<len(self.data):
if self.data[i] == '\x00':
noterm = False
else:
s += self.data[i]
i += 1
return s
|
_test_multiprocessing.py | #
# Unit tests for the multiprocessing package
#
import unittest
import queue as pyqueue
import contextlib
import time
import io
import itertools
import sys
import os
import gc
import errno
import signal
import array
import socket
import random
import logging
import struct
import operator
import weakref
import test.support
import test.support.script_helper
from test import support
# Skip tests if _multiprocessing wasn't built.
_multiprocessing = test.support.import_module('_multiprocessing')
# Skip tests if sem_open implementation is broken.
test.support.import_module('multiprocessing.synchronize')
# import threading after _multiprocessing to raise a more relevant error
# message: "No module named _multiprocessing". _multiprocessing is not compiled
# without thread support.
import threading
import multiprocessing.connection
import multiprocessing.dummy
import multiprocessing.heap
import multiprocessing.managers
import multiprocessing.pool
import multiprocessing.queues
from multiprocessing import util
try:
from multiprocessing import reduction
HAS_REDUCTION = reduction.HAVE_SEND_HANDLE
except ImportError:
HAS_REDUCTION = False
try:
from multiprocessing.sharedctypes import Value, copy
HAS_SHAREDCTYPES = True
except ImportError:
HAS_SHAREDCTYPES = False
try:
import msvcrt
except ImportError:
msvcrt = None
#
#
#
# Timeout to wait until a process completes
TIMEOUT = 60.0 # seconds
def latin(s):
return s.encode('latin')
def close_queue(queue):
if isinstance(queue, multiprocessing.queues.Queue):
queue.close()
queue.join_thread()
def join_process(process):
# Since multiprocessing.Process has the same API than threading.Thread
# (join() and is_alive(), the support function can be reused
support.join_thread(process, timeout=TIMEOUT)
#
# Constants
#
LOG_LEVEL = util.SUBWARNING
#LOG_LEVEL = logging.DEBUG
DELTA = 0.1
CHECK_TIMINGS = False # making true makes tests take a lot longer
# and can sometimes cause some non-serious
# failures because some calls block a bit
# longer than expected
if CHECK_TIMINGS:
TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.82, 0.35, 1.4
else:
TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.1, 0.1, 0.1
HAVE_GETVALUE = not getattr(_multiprocessing,
'HAVE_BROKEN_SEM_GETVALUE', False)
WIN32 = (sys.platform == "win32")
from multiprocessing.connection import wait
def wait_for_handle(handle, timeout):
if timeout is not None and timeout < 0.0:
timeout = None
return wait([handle], timeout)
try:
MAXFD = os.sysconf("SC_OPEN_MAX")
except:
MAXFD = 256
# To speed up tests when using the forkserver, we can preload these:
PRELOAD = ['__main__', 'test.test_multiprocessing_forkserver']
#
# Some tests require ctypes
#
try:
from ctypes import Structure, c_int, c_double, c_longlong
except ImportError:
Structure = object
c_int = c_double = c_longlong = None
def check_enough_semaphores():
"""Check that the system supports enough semaphores to run the test."""
# minimum number of semaphores available according to POSIX
nsems_min = 256
try:
nsems = os.sysconf("SC_SEM_NSEMS_MAX")
except (AttributeError, ValueError):
# sysconf not available or setting not available
return
if nsems == -1 or nsems >= nsems_min:
return
raise unittest.SkipTest("The OS doesn't support enough semaphores "
"to run the test (required: %d)." % nsems_min)
#
# Creates a wrapper for a function which records the time it takes to finish
#
class TimingWrapper(object):
def __init__(self, func):
self.func = func
self.elapsed = None
def __call__(self, *args, **kwds):
t = time.monotonic()
try:
return self.func(*args, **kwds)
finally:
self.elapsed = time.monotonic() - t
#
# Base class for test cases
#
class BaseTestCase(object):
ALLOWED_TYPES = ('processes', 'manager', 'threads')
def assertTimingAlmostEqual(self, a, b):
if CHECK_TIMINGS:
self.assertAlmostEqual(a, b, 1)
def assertReturnsIfImplemented(self, value, func, *args):
try:
res = func(*args)
except NotImplementedError:
pass
else:
return self.assertEqual(value, res)
# For the sanity of Windows users, rather than crashing or freezing in
# multiple ways.
def __reduce__(self, *args):
raise NotImplementedError("shouldn't try to pickle a test case")
__reduce_ex__ = __reduce__
#
# Return the value of a semaphore
#
def get_value(self):
try:
return self.get_value()
except AttributeError:
try:
return self._Semaphore__value
except AttributeError:
try:
return self._value
except AttributeError:
raise NotImplementedError
#
# Testcases
#
class DummyCallable:
def __call__(self, q, c):
assert isinstance(c, DummyCallable)
q.put(5)
class _TestProcess(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
def test_current(self):
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
current = self.current_process()
authkey = current.authkey
self.assertTrue(current.is_alive())
self.assertTrue(not current.daemon)
self.assertIsInstance(authkey, bytes)
self.assertTrue(len(authkey) > 0)
self.assertEqual(current.ident, os.getpid())
self.assertEqual(current.exitcode, None)
def test_daemon_argument(self):
if self.TYPE == "threads":
self.skipTest('test not appropriate for {}'.format(self.TYPE))
# By default uses the current process's daemon flag.
proc0 = self.Process(target=self._test)
self.assertEqual(proc0.daemon, self.current_process().daemon)
proc1 = self.Process(target=self._test, daemon=True)
self.assertTrue(proc1.daemon)
proc2 = self.Process(target=self._test, daemon=False)
self.assertFalse(proc2.daemon)
@classmethod
def _test(cls, q, *args, **kwds):
current = cls.current_process()
q.put(args)
q.put(kwds)
q.put(current.name)
if cls.TYPE != 'threads':
q.put(bytes(current.authkey))
q.put(current.pid)
def test_process(self):
q = self.Queue(1)
e = self.Event()
args = (q, 1, 2)
kwargs = {'hello':23, 'bye':2.54}
name = 'SomeProcess'
p = self.Process(
target=self._test, args=args, kwargs=kwargs, name=name
)
p.daemon = True
current = self.current_process()
if self.TYPE != 'threads':
self.assertEqual(p.authkey, current.authkey)
self.assertEqual(p.is_alive(), False)
self.assertEqual(p.daemon, True)
self.assertNotIn(p, self.active_children())
self.assertTrue(type(self.active_children()) is list)
self.assertEqual(p.exitcode, None)
p.start()
self.assertEqual(p.exitcode, None)
self.assertEqual(p.is_alive(), True)
self.assertIn(p, self.active_children())
self.assertEqual(q.get(), args[1:])
self.assertEqual(q.get(), kwargs)
self.assertEqual(q.get(), p.name)
if self.TYPE != 'threads':
self.assertEqual(q.get(), current.authkey)
self.assertEqual(q.get(), p.pid)
p.join()
self.assertEqual(p.exitcode, 0)
self.assertEqual(p.is_alive(), False)
self.assertNotIn(p, self.active_children())
close_queue(q)
@classmethod
def _sleep_some(cls):
time.sleep(100)
@classmethod
def _test_sleep(cls, delay):
time.sleep(delay)
def _kill_process(self, meth):
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
p = self.Process(target=self._sleep_some)
p.daemon = True
p.start()
self.assertEqual(p.is_alive(), True)
self.assertIn(p, self.active_children())
self.assertEqual(p.exitcode, None)
join = TimingWrapper(p.join)
self.assertEqual(join(0), None)
self.assertTimingAlmostEqual(join.elapsed, 0.0)
self.assertEqual(p.is_alive(), True)
self.assertEqual(join(-1), None)
self.assertTimingAlmostEqual(join.elapsed, 0.0)
self.assertEqual(p.is_alive(), True)
# XXX maybe terminating too soon causes the problems on Gentoo...
time.sleep(1)
meth(p)
if hasattr(signal, 'alarm'):
# On the Gentoo buildbot waitpid() often seems to block forever.
# We use alarm() to interrupt it if it blocks for too long.
def handler(*args):
raise RuntimeError('join took too long: %s' % p)
old_handler = signal.signal(signal.SIGALRM, handler)
try:
signal.alarm(10)
self.assertEqual(join(), None)
finally:
signal.alarm(0)
signal.signal(signal.SIGALRM, old_handler)
else:
self.assertEqual(join(), None)
self.assertTimingAlmostEqual(join.elapsed, 0.0)
self.assertEqual(p.is_alive(), False)
self.assertNotIn(p, self.active_children())
p.join()
return p.exitcode
def test_terminate(self):
exitcode = self._kill_process(multiprocessing.Process.terminate)
if os.name != 'nt':
self.assertEqual(exitcode, -signal.SIGTERM)
def test_kill(self):
exitcode = self._kill_process(multiprocessing.Process.kill)
if os.name != 'nt':
self.assertEqual(exitcode, -signal.SIGKILL)
def test_cpu_count(self):
try:
cpus = multiprocessing.cpu_count()
except NotImplementedError:
cpus = 1
self.assertTrue(type(cpus) is int)
self.assertTrue(cpus >= 1)
def test_active_children(self):
self.assertEqual(type(self.active_children()), list)
p = self.Process(target=time.sleep, args=(DELTA,))
self.assertNotIn(p, self.active_children())
p.daemon = True
p.start()
self.assertIn(p, self.active_children())
p.join()
self.assertNotIn(p, self.active_children())
@classmethod
def _test_recursion(cls, wconn, id):
wconn.send(id)
if len(id) < 2:
for i in range(2):
p = cls.Process(
target=cls._test_recursion, args=(wconn, id+[i])
)
p.start()
p.join()
def test_recursion(self):
rconn, wconn = self.Pipe(duplex=False)
self._test_recursion(wconn, [])
time.sleep(DELTA)
result = []
while rconn.poll():
result.append(rconn.recv())
expected = [
[],
[0],
[0, 0],
[0, 1],
[1],
[1, 0],
[1, 1]
]
self.assertEqual(result, expected)
@classmethod
def _test_sentinel(cls, event):
event.wait(10.0)
def test_sentinel(self):
if self.TYPE == "threads":
self.skipTest('test not appropriate for {}'.format(self.TYPE))
event = self.Event()
p = self.Process(target=self._test_sentinel, args=(event,))
with self.assertRaises(ValueError):
p.sentinel
p.start()
self.addCleanup(p.join)
sentinel = p.sentinel
self.assertIsInstance(sentinel, int)
self.assertFalse(wait_for_handle(sentinel, timeout=0.0))
event.set()
p.join()
self.assertTrue(wait_for_handle(sentinel, timeout=1))
@classmethod
def _test_close(cls, rc=0, q=None):
if q is not None:
q.get()
sys.exit(rc)
def test_close(self):
if self.TYPE == "threads":
self.skipTest('test not appropriate for {}'.format(self.TYPE))
q = self.Queue()
p = self.Process(target=self._test_close, kwargs={'q': q})
p.daemon = True
p.start()
self.assertEqual(p.is_alive(), True)
# Child is still alive, cannot close
with self.assertRaises(ValueError):
p.close()
q.put(None)
p.join()
self.assertEqual(p.is_alive(), False)
self.assertEqual(p.exitcode, 0)
p.close()
with self.assertRaises(ValueError):
p.is_alive()
with self.assertRaises(ValueError):
p.join()
with self.assertRaises(ValueError):
p.terminate()
p.close()
wr = weakref.ref(p)
del p
gc.collect()
self.assertIs(wr(), None)
close_queue(q)
def test_many_processes(self):
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
sm = multiprocessing.get_start_method()
N = 5 if sm == 'spawn' else 100
# Try to overwhelm the forkserver loop with events
procs = [self.Process(target=self._test_sleep, args=(0.01,))
for i in range(N)]
for p in procs:
p.start()
for p in procs:
join_process(p)
for p in procs:
self.assertEqual(p.exitcode, 0)
procs = [self.Process(target=self._sleep_some)
for i in range(N)]
for p in procs:
p.start()
time.sleep(0.001) # let the children start...
for p in procs:
p.terminate()
for p in procs:
join_process(p)
if os.name != 'nt':
exitcodes = [-signal.SIGTERM]
if sys.platform == 'darwin':
# bpo-31510: On macOS, killing a freshly started process with
# SIGTERM sometimes kills the process with SIGKILL.
exitcodes.append(-signal.SIGKILL)
for p in procs:
self.assertIn(p.exitcode, exitcodes)
def test_lose_target_ref(self):
c = DummyCallable()
wr = weakref.ref(c)
q = self.Queue()
p = self.Process(target=c, args=(q, c))
del c
p.start()
p.join()
for i in range(3):
gc.collect()
self.assertIs(wr(), None)
self.assertEqual(q.get(), 5)
close_queue(q)
@classmethod
def _test_child_fd_inflation(self, evt, q):
q.put(test.support.fd_count())
evt.wait()
def test_child_fd_inflation(self):
# Number of fds in child processes should not grow with the
# number of running children.
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
sm = multiprocessing.get_start_method()
if sm == 'fork':
# The fork method by design inherits all fds from the parent,
# trying to go against it is a lost battle
self.skipTest('test not appropriate for {}'.format(sm))
N = 5
evt = self.Event()
q = self.Queue()
procs = [self.Process(target=self._test_child_fd_inflation, args=(evt, q))
for i in range(N)]
for p in procs:
p.start()
try:
fd_counts = [q.get() for i in range(N)]
self.assertEqual(len(set(fd_counts)), 1, fd_counts)
finally:
evt.set()
for p in procs:
p.join()
close_queue(q)
@classmethod
def _test_wait_for_threads(self, evt):
def func1():
time.sleep(0.5)
evt.set()
def func2():
time.sleep(20)
evt.clear()
threading.Thread(target=func1).start()
threading.Thread(target=func2, daemon=True).start()
def test_wait_for_threads(self):
# A child process should wait for non-daemonic threads to end
# before exiting
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
evt = self.Event()
proc = self.Process(target=self._test_wait_for_threads, args=(evt,))
proc.start()
proc.join()
self.assertTrue(evt.is_set())
@classmethod
def _test_error_on_stdio_flush(self, evt, break_std_streams={}):
for stream_name, action in break_std_streams.items():
if action == 'close':
stream = io.StringIO()
stream.close()
else:
assert action == 'remove'
stream = None
setattr(sys, stream_name, None)
evt.set()
def test_error_on_stdio_flush_1(self):
# Check that Process works with broken standard streams
streams = [io.StringIO(), None]
streams[0].close()
for stream_name in ('stdout', 'stderr'):
for stream in streams:
old_stream = getattr(sys, stream_name)
setattr(sys, stream_name, stream)
try:
evt = self.Event()
proc = self.Process(target=self._test_error_on_stdio_flush,
args=(evt,))
proc.start()
proc.join()
self.assertTrue(evt.is_set())
self.assertEqual(proc.exitcode, 0)
finally:
setattr(sys, stream_name, old_stream)
def test_error_on_stdio_flush_2(self):
# Same as test_error_on_stdio_flush_1(), but standard streams are
# broken by the child process
for stream_name in ('stdout', 'stderr'):
for action in ('close', 'remove'):
old_stream = getattr(sys, stream_name)
try:
evt = self.Event()
proc = self.Process(target=self._test_error_on_stdio_flush,
args=(evt, {stream_name: action}))
proc.start()
proc.join()
self.assertTrue(evt.is_set())
self.assertEqual(proc.exitcode, 0)
finally:
setattr(sys, stream_name, old_stream)
@classmethod
def _sleep_and_set_event(self, evt, delay=0.0):
time.sleep(delay)
evt.set()
def check_forkserver_death(self, signum):
# bpo-31308: if the forkserver process has died, we should still
# be able to create and run new Process instances (the forkserver
# is implicitly restarted).
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
sm = multiprocessing.get_start_method()
if sm != 'forkserver':
# The fork method by design inherits all fds from the parent,
# trying to go against it is a lost battle
self.skipTest('test not appropriate for {}'.format(sm))
from multiprocessing.forkserver import _forkserver
_forkserver.ensure_running()
# First process sleeps 500 ms
delay = 0.5
evt = self.Event()
proc = self.Process(target=self._sleep_and_set_event, args=(evt, delay))
proc.start()
pid = _forkserver._forkserver_pid
os.kill(pid, signum)
# give time to the fork server to die and time to proc to complete
time.sleep(delay * 2.0)
evt2 = self.Event()
proc2 = self.Process(target=self._sleep_and_set_event, args=(evt2,))
proc2.start()
proc2.join()
self.assertTrue(evt2.is_set())
self.assertEqual(proc2.exitcode, 0)
proc.join()
self.assertTrue(evt.is_set())
self.assertIn(proc.exitcode, (0, 255))
def test_forkserver_sigint(self):
# Catchable signal
self.check_forkserver_death(signal.SIGINT)
def test_forkserver_sigkill(self):
# Uncatchable signal
if os.name != 'nt':
self.check_forkserver_death(signal.SIGKILL)
#
#
#
class _UpperCaser(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.child_conn, self.parent_conn = multiprocessing.Pipe()
def run(self):
self.parent_conn.close()
for s in iter(self.child_conn.recv, None):
self.child_conn.send(s.upper())
self.child_conn.close()
def submit(self, s):
assert type(s) is str
self.parent_conn.send(s)
return self.parent_conn.recv()
def stop(self):
self.parent_conn.send(None)
self.parent_conn.close()
self.child_conn.close()
class _TestSubclassingProcess(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def test_subclassing(self):
uppercaser = _UpperCaser()
uppercaser.daemon = True
uppercaser.start()
self.assertEqual(uppercaser.submit('hello'), 'HELLO')
self.assertEqual(uppercaser.submit('world'), 'WORLD')
uppercaser.stop()
uppercaser.join()
def test_stderr_flush(self):
# sys.stderr is flushed at process shutdown (issue #13812)
if self.TYPE == "threads":
self.skipTest('test not appropriate for {}'.format(self.TYPE))
testfn = test.support.TESTFN
self.addCleanup(test.support.unlink, testfn)
proc = self.Process(target=self._test_stderr_flush, args=(testfn,))
proc.start()
proc.join()
with open(testfn, 'r') as f:
err = f.read()
# The whole traceback was printed
self.assertIn("ZeroDivisionError", err)
self.assertIn("test_multiprocessing.py", err)
self.assertIn("1/0 # MARKER", err)
@classmethod
def _test_stderr_flush(cls, testfn):
fd = os.open(testfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
sys.stderr = open(fd, 'w', closefd=False)
1/0 # MARKER
@classmethod
def _test_sys_exit(cls, reason, testfn):
fd = os.open(testfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
sys.stderr = open(fd, 'w', closefd=False)
sys.exit(reason)
def test_sys_exit(self):
# See Issue 13854
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
testfn = test.support.TESTFN
self.addCleanup(test.support.unlink, testfn)
for reason in (
[1, 2, 3],
'ignore this',
):
p = self.Process(target=self._test_sys_exit, args=(reason, testfn))
p.daemon = True
p.start()
join_process(p)
self.assertEqual(p.exitcode, 1)
with open(testfn, 'r') as f:
content = f.read()
self.assertEqual(content.rstrip(), str(reason))
os.unlink(testfn)
for reason in (True, False, 8):
p = self.Process(target=sys.exit, args=(reason,))
p.daemon = True
p.start()
join_process(p)
self.assertEqual(p.exitcode, reason)
#
#
#
def queue_empty(q):
if hasattr(q, 'empty'):
return q.empty()
else:
return q.qsize() == 0
def queue_full(q, maxsize):
if hasattr(q, 'full'):
return q.full()
else:
return q.qsize() == maxsize
class _TestQueue(BaseTestCase):
@classmethod
def _test_put(cls, queue, child_can_start, parent_can_continue):
child_can_start.wait()
for i in range(6):
queue.get()
parent_can_continue.set()
def test_put(self):
MAXSIZE = 6
queue = self.Queue(maxsize=MAXSIZE)
child_can_start = self.Event()
parent_can_continue = self.Event()
proc = self.Process(
target=self._test_put,
args=(queue, child_can_start, parent_can_continue)
)
proc.daemon = True
proc.start()
self.assertEqual(queue_empty(queue), True)
self.assertEqual(queue_full(queue, MAXSIZE), False)
queue.put(1)
queue.put(2, True)
queue.put(3, True, None)
queue.put(4, False)
queue.put(5, False, None)
queue.put_nowait(6)
# the values may be in buffer but not yet in pipe so sleep a bit
time.sleep(DELTA)
self.assertEqual(queue_empty(queue), False)
self.assertEqual(queue_full(queue, MAXSIZE), True)
put = TimingWrapper(queue.put)
put_nowait = TimingWrapper(queue.put_nowait)
self.assertRaises(pyqueue.Full, put, 7, False)
self.assertTimingAlmostEqual(put.elapsed, 0)
self.assertRaises(pyqueue.Full, put, 7, False, None)
self.assertTimingAlmostEqual(put.elapsed, 0)
self.assertRaises(pyqueue.Full, put_nowait, 7)
self.assertTimingAlmostEqual(put_nowait.elapsed, 0)
self.assertRaises(pyqueue.Full, put, 7, True, TIMEOUT1)
self.assertTimingAlmostEqual(put.elapsed, TIMEOUT1)
self.assertRaises(pyqueue.Full, put, 7, False, TIMEOUT2)
self.assertTimingAlmostEqual(put.elapsed, 0)
self.assertRaises(pyqueue.Full, put, 7, True, timeout=TIMEOUT3)
self.assertTimingAlmostEqual(put.elapsed, TIMEOUT3)
child_can_start.set()
parent_can_continue.wait()
self.assertEqual(queue_empty(queue), True)
self.assertEqual(queue_full(queue, MAXSIZE), False)
proc.join()
close_queue(queue)
@classmethod
def _test_get(cls, queue, child_can_start, parent_can_continue):
child_can_start.wait()
#queue.put(1)
queue.put(2)
queue.put(3)
queue.put(4)
queue.put(5)
parent_can_continue.set()
def test_get(self):
queue = self.Queue()
child_can_start = self.Event()
parent_can_continue = self.Event()
proc = self.Process(
target=self._test_get,
args=(queue, child_can_start, parent_can_continue)
)
proc.daemon = True
proc.start()
self.assertEqual(queue_empty(queue), True)
child_can_start.set()
parent_can_continue.wait()
time.sleep(DELTA)
self.assertEqual(queue_empty(queue), False)
# Hangs unexpectedly, remove for now
#self.assertEqual(queue.get(), 1)
self.assertEqual(queue.get(True, None), 2)
self.assertEqual(queue.get(True), 3)
self.assertEqual(queue.get(timeout=1), 4)
self.assertEqual(queue.get_nowait(), 5)
self.assertEqual(queue_empty(queue), True)
get = TimingWrapper(queue.get)
get_nowait = TimingWrapper(queue.get_nowait)
self.assertRaises(pyqueue.Empty, get, False)
self.assertTimingAlmostEqual(get.elapsed, 0)
self.assertRaises(pyqueue.Empty, get, False, None)
self.assertTimingAlmostEqual(get.elapsed, 0)
self.assertRaises(pyqueue.Empty, get_nowait)
self.assertTimingAlmostEqual(get_nowait.elapsed, 0)
self.assertRaises(pyqueue.Empty, get, True, TIMEOUT1)
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1)
self.assertRaises(pyqueue.Empty, get, False, TIMEOUT2)
self.assertTimingAlmostEqual(get.elapsed, 0)
self.assertRaises(pyqueue.Empty, get, timeout=TIMEOUT3)
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT3)
proc.join()
close_queue(queue)
@classmethod
def _test_fork(cls, queue):
for i in range(10, 20):
queue.put(i)
# note that at this point the items may only be buffered, so the
# process cannot shutdown until the feeder thread has finished
# pushing items onto the pipe.
def test_fork(self):
# Old versions of Queue would fail to create a new feeder
# thread for a forked process if the original process had its
# own feeder thread. This test checks that this no longer
# happens.
queue = self.Queue()
# put items on queue so that main process starts a feeder thread
for i in range(10):
queue.put(i)
# wait to make sure thread starts before we fork a new process
time.sleep(DELTA)
# fork process
p = self.Process(target=self._test_fork, args=(queue,))
p.daemon = True
p.start()
# check that all expected items are in the queue
for i in range(20):
self.assertEqual(queue.get(), i)
self.assertRaises(pyqueue.Empty, queue.get, False)
p.join()
close_queue(queue)
def test_qsize(self):
q = self.Queue()
try:
self.assertEqual(q.qsize(), 0)
except NotImplementedError:
self.skipTest('qsize method not implemented')
q.put(1)
self.assertEqual(q.qsize(), 1)
q.put(5)
self.assertEqual(q.qsize(), 2)
q.get()
self.assertEqual(q.qsize(), 1)
q.get()
self.assertEqual(q.qsize(), 0)
close_queue(q)
@classmethod
def _test_task_done(cls, q):
for obj in iter(q.get, None):
time.sleep(DELTA)
q.task_done()
def test_task_done(self):
queue = self.JoinableQueue()
workers = [self.Process(target=self._test_task_done, args=(queue,))
for i in range(4)]
for p in workers:
p.daemon = True
p.start()
for i in range(10):
queue.put(i)
queue.join()
for p in workers:
queue.put(None)
for p in workers:
p.join()
close_queue(queue)
def test_no_import_lock_contention(self):
with test.support.temp_cwd():
module_name = 'imported_by_an_imported_module'
with open(module_name + '.py', 'w') as f:
f.write("""if 1:
import multiprocessing
q = multiprocessing.Queue()
q.put('knock knock')
q.get(timeout=3)
q.close()
del q
""")
with test.support.DirsOnSysPath(os.getcwd()):
try:
__import__(module_name)
except pyqueue.Empty:
self.fail("Probable regression on import lock contention;"
" see Issue #22853")
def test_timeout(self):
q = multiprocessing.Queue()
start = time.monotonic()
self.assertRaises(pyqueue.Empty, q.get, True, 0.200)
delta = time.monotonic() - start
# bpo-30317: Tolerate a delta of 100 ms because of the bad clock
# resolution on Windows (usually 15.6 ms). x86 Windows7 3.x once
# failed because the delta was only 135.8 ms.
self.assertGreaterEqual(delta, 0.100)
close_queue(q)
def test_queue_feeder_donot_stop_onexc(self):
# bpo-30414: verify feeder handles exceptions correctly
if self.TYPE != 'processes':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
class NotSerializable(object):
def __reduce__(self):
raise AttributeError
with test.support.captured_stderr():
q = self.Queue()
q.put(NotSerializable())
q.put(True)
self.assertTrue(q.get(timeout=TIMEOUT))
close_queue(q)
with test.support.captured_stderr():
# bpo-33078: verify that the queue size is correctly handled
# on errors.
q = self.Queue(maxsize=1)
q.put(NotSerializable())
q.put(True)
try:
self.assertEqual(q.qsize(), 1)
except NotImplementedError:
# qsize is not available on all platform as it
# relies on sem_getvalue
pass
# bpo-30595: use a timeout of 1 second for slow buildbots
self.assertTrue(q.get(timeout=1.0))
# Check that the size of the queue is correct
self.assertTrue(q.empty())
close_queue(q)
def test_queue_feeder_on_queue_feeder_error(self):
# bpo-30006: verify feeder handles exceptions using the
# _on_queue_feeder_error hook.
if self.TYPE != 'processes':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
class NotSerializable(object):
"""Mock unserializable object"""
def __init__(self):
self.reduce_was_called = False
self.on_queue_feeder_error_was_called = False
def __reduce__(self):
self.reduce_was_called = True
raise AttributeError
class SafeQueue(multiprocessing.queues.Queue):
"""Queue with overloaded _on_queue_feeder_error hook"""
@staticmethod
def _on_queue_feeder_error(e, obj):
if (isinstance(e, AttributeError) and
isinstance(obj, NotSerializable)):
obj.on_queue_feeder_error_was_called = True
not_serializable_obj = NotSerializable()
# The captured_stderr reduces the noise in the test report
with test.support.captured_stderr():
q = SafeQueue(ctx=multiprocessing.get_context())
q.put(not_serializable_obj)
# Verify that q is still functioning correctly
q.put(True)
self.assertTrue(q.get(timeout=1.0))
# Assert that the serialization and the hook have been called correctly
self.assertTrue(not_serializable_obj.reduce_was_called)
self.assertTrue(not_serializable_obj.on_queue_feeder_error_was_called)
#
#
#
class _TestLock(BaseTestCase):
def test_lock(self):
lock = self.Lock()
self.assertEqual(lock.acquire(), True)
self.assertEqual(lock.acquire(False), False)
self.assertEqual(lock.release(), None)
self.assertRaises((ValueError, threading.ThreadError), lock.release)
def test_rlock(self):
lock = self.RLock()
self.assertEqual(lock.acquire(), True)
self.assertEqual(lock.acquire(), True)
self.assertEqual(lock.acquire(), True)
self.assertEqual(lock.release(), None)
self.assertEqual(lock.release(), None)
self.assertEqual(lock.release(), None)
self.assertRaises((AssertionError, RuntimeError), lock.release)
def test_lock_context(self):
with self.Lock():
pass
class _TestSemaphore(BaseTestCase):
def _test_semaphore(self, sem):
self.assertReturnsIfImplemented(2, get_value, sem)
self.assertEqual(sem.acquire(), True)
self.assertReturnsIfImplemented(1, get_value, sem)
self.assertEqual(sem.acquire(), True)
self.assertReturnsIfImplemented(0, get_value, sem)
self.assertEqual(sem.acquire(False), False)
self.assertReturnsIfImplemented(0, get_value, sem)
self.assertEqual(sem.release(), None)
self.assertReturnsIfImplemented(1, get_value, sem)
self.assertEqual(sem.release(), None)
self.assertReturnsIfImplemented(2, get_value, sem)
def test_semaphore(self):
sem = self.Semaphore(2)
self._test_semaphore(sem)
self.assertEqual(sem.release(), None)
self.assertReturnsIfImplemented(3, get_value, sem)
self.assertEqual(sem.release(), None)
self.assertReturnsIfImplemented(4, get_value, sem)
def test_bounded_semaphore(self):
sem = self.BoundedSemaphore(2)
self._test_semaphore(sem)
# Currently fails on OS/X
#if HAVE_GETVALUE:
# self.assertRaises(ValueError, sem.release)
# self.assertReturnsIfImplemented(2, get_value, sem)
def test_timeout(self):
if self.TYPE != 'processes':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
sem = self.Semaphore(0)
acquire = TimingWrapper(sem.acquire)
self.assertEqual(acquire(False), False)
self.assertTimingAlmostEqual(acquire.elapsed, 0.0)
self.assertEqual(acquire(False, None), False)
self.assertTimingAlmostEqual(acquire.elapsed, 0.0)
self.assertEqual(acquire(False, TIMEOUT1), False)
self.assertTimingAlmostEqual(acquire.elapsed, 0)
self.assertEqual(acquire(True, TIMEOUT2), False)
self.assertTimingAlmostEqual(acquire.elapsed, TIMEOUT2)
self.assertEqual(acquire(timeout=TIMEOUT3), False)
self.assertTimingAlmostEqual(acquire.elapsed, TIMEOUT3)
class _TestCondition(BaseTestCase):
@classmethod
def f(cls, cond, sleeping, woken, timeout=None):
cond.acquire()
sleeping.release()
cond.wait(timeout)
woken.release()
cond.release()
def assertReachesEventually(self, func, value):
for i in range(10):
try:
if func() == value:
break
except NotImplementedError:
break
time.sleep(DELTA)
time.sleep(DELTA)
self.assertReturnsIfImplemented(value, func)
def check_invariant(self, cond):
# this is only supposed to succeed when there are no sleepers
if self.TYPE == 'processes':
try:
sleepers = (cond._sleeping_count.get_value() -
cond._woken_count.get_value())
self.assertEqual(sleepers, 0)
self.assertEqual(cond._wait_semaphore.get_value(), 0)
except NotImplementedError:
pass
def test_notify(self):
cond = self.Condition()
sleeping = self.Semaphore(0)
woken = self.Semaphore(0)
p = self.Process(target=self.f, args=(cond, sleeping, woken))
p.daemon = True
p.start()
self.addCleanup(p.join)
p = threading.Thread(target=self.f, args=(cond, sleeping, woken))
p.daemon = True
p.start()
self.addCleanup(p.join)
# wait for both children to start sleeping
sleeping.acquire()
sleeping.acquire()
# check no process/thread has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(0, get_value, woken)
# wake up one process/thread
cond.acquire()
cond.notify()
cond.release()
# check one process/thread has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(1, get_value, woken)
# wake up another
cond.acquire()
cond.notify()
cond.release()
# check other has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(2, get_value, woken)
# check state is not mucked up
self.check_invariant(cond)
p.join()
def test_notify_all(self):
cond = self.Condition()
sleeping = self.Semaphore(0)
woken = self.Semaphore(0)
# start some threads/processes which will timeout
for i in range(3):
p = self.Process(target=self.f,
args=(cond, sleeping, woken, TIMEOUT1))
p.daemon = True
p.start()
self.addCleanup(p.join)
t = threading.Thread(target=self.f,
args=(cond, sleeping, woken, TIMEOUT1))
t.daemon = True
t.start()
self.addCleanup(t.join)
# wait for them all to sleep
for i in range(6):
sleeping.acquire()
# check they have all timed out
for i in range(6):
woken.acquire()
self.assertReturnsIfImplemented(0, get_value, woken)
# check state is not mucked up
self.check_invariant(cond)
# start some more threads/processes
for i in range(3):
p = self.Process(target=self.f, args=(cond, sleeping, woken))
p.daemon = True
p.start()
self.addCleanup(p.join)
t = threading.Thread(target=self.f, args=(cond, sleeping, woken))
t.daemon = True
t.start()
self.addCleanup(t.join)
# wait for them to all sleep
for i in range(6):
sleeping.acquire()
# check no process/thread has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(0, get_value, woken)
# wake them all up
cond.acquire()
cond.notify_all()
cond.release()
# check they have all woken
self.assertReachesEventually(lambda: get_value(woken), 6)
# check state is not mucked up
self.check_invariant(cond)
def test_notify_n(self):
cond = self.Condition()
sleeping = self.Semaphore(0)
woken = self.Semaphore(0)
# start some threads/processes
for i in range(3):
p = self.Process(target=self.f, args=(cond, sleeping, woken))
p.daemon = True
p.start()
self.addCleanup(p.join)
t = threading.Thread(target=self.f, args=(cond, sleeping, woken))
t.daemon = True
t.start()
self.addCleanup(t.join)
# wait for them to all sleep
for i in range(6):
sleeping.acquire()
# check no process/thread has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(0, get_value, woken)
# wake some of them up
cond.acquire()
cond.notify(n=2)
cond.release()
# check 2 have woken
self.assertReachesEventually(lambda: get_value(woken), 2)
# wake the rest of them
cond.acquire()
cond.notify(n=4)
cond.release()
self.assertReachesEventually(lambda: get_value(woken), 6)
# doesn't do anything more
cond.acquire()
cond.notify(n=3)
cond.release()
self.assertReturnsIfImplemented(6, get_value, woken)
# check state is not mucked up
self.check_invariant(cond)
def test_timeout(self):
cond = self.Condition()
wait = TimingWrapper(cond.wait)
cond.acquire()
res = wait(TIMEOUT1)
cond.release()
self.assertEqual(res, False)
self.assertTimingAlmostEqual(wait.elapsed, TIMEOUT1)
@classmethod
def _test_waitfor_f(cls, cond, state):
with cond:
state.value = 0
cond.notify()
result = cond.wait_for(lambda : state.value==4)
if not result or state.value != 4:
sys.exit(1)
@unittest.skipUnless(HAS_SHAREDCTYPES, 'needs sharedctypes')
def test_waitfor(self):
# based on test in test/lock_tests.py
cond = self.Condition()
state = self.Value('i', -1)
p = self.Process(target=self._test_waitfor_f, args=(cond, state))
p.daemon = True
p.start()
with cond:
result = cond.wait_for(lambda : state.value==0)
self.assertTrue(result)
self.assertEqual(state.value, 0)
for i in range(4):
time.sleep(0.01)
with cond:
state.value += 1
cond.notify()
join_process(p)
self.assertEqual(p.exitcode, 0)
@classmethod
def _test_waitfor_timeout_f(cls, cond, state, success, sem):
sem.release()
with cond:
expected = 0.1
dt = time.monotonic()
result = cond.wait_for(lambda : state.value==4, timeout=expected)
dt = time.monotonic() - dt
# borrow logic in assertTimeout() from test/lock_tests.py
if not result and expected * 0.6 < dt < expected * 10.0:
success.value = True
@unittest.skipUnless(HAS_SHAREDCTYPES, 'needs sharedctypes')
def test_waitfor_timeout(self):
# based on test in test/lock_tests.py
cond = self.Condition()
state = self.Value('i', 0)
success = self.Value('i', False)
sem = self.Semaphore(0)
p = self.Process(target=self._test_waitfor_timeout_f,
args=(cond, state, success, sem))
p.daemon = True
p.start()
self.assertTrue(sem.acquire(timeout=TIMEOUT))
# Only increment 3 times, so state == 4 is never reached.
for i in range(3):
time.sleep(0.01)
with cond:
state.value += 1
cond.notify()
join_process(p)
self.assertTrue(success.value)
@classmethod
def _test_wait_result(cls, c, pid):
with c:
c.notify()
time.sleep(1)
if pid is not None:
os.kill(pid, signal.SIGINT)
def test_wait_result(self):
if isinstance(self, ProcessesMixin) and sys.platform != 'win32':
pid = os.getpid()
else:
pid = None
c = self.Condition()
with c:
self.assertFalse(c.wait(0))
self.assertFalse(c.wait(0.1))
p = self.Process(target=self._test_wait_result, args=(c, pid))
p.start()
self.assertTrue(c.wait(60))
if pid is not None:
self.assertRaises(KeyboardInterrupt, c.wait, 60)
p.join()
class _TestEvent(BaseTestCase):
@classmethod
def _test_event(cls, event):
time.sleep(TIMEOUT2)
event.set()
def test_event(self):
event = self.Event()
wait = TimingWrapper(event.wait)
# Removed temporarily, due to API shear, this does not
# work with threading._Event objects. is_set == isSet
self.assertEqual(event.is_set(), False)
# Removed, threading.Event.wait() will return the value of the __flag
# instead of None. API Shear with the semaphore backed mp.Event
self.assertEqual(wait(0.0), False)
self.assertTimingAlmostEqual(wait.elapsed, 0.0)
self.assertEqual(wait(TIMEOUT1), False)
self.assertTimingAlmostEqual(wait.elapsed, TIMEOUT1)
event.set()
# See note above on the API differences
self.assertEqual(event.is_set(), True)
self.assertEqual(wait(), True)
self.assertTimingAlmostEqual(wait.elapsed, 0.0)
self.assertEqual(wait(TIMEOUT1), True)
self.assertTimingAlmostEqual(wait.elapsed, 0.0)
# self.assertEqual(event.is_set(), True)
event.clear()
#self.assertEqual(event.is_set(), False)
p = self.Process(target=self._test_event, args=(event,))
p.daemon = True
p.start()
self.assertEqual(wait(), True)
p.join()
#
# Tests for Barrier - adapted from tests in test/lock_tests.py
#
# Many of the tests for threading.Barrier use a list as an atomic
# counter: a value is appended to increment the counter, and the
# length of the list gives the value. We use the class DummyList
# for the same purpose.
class _DummyList(object):
def __init__(self):
wrapper = multiprocessing.heap.BufferWrapper(struct.calcsize('i'))
lock = multiprocessing.Lock()
self.__setstate__((wrapper, lock))
self._lengthbuf[0] = 0
def __setstate__(self, state):
(self._wrapper, self._lock) = state
self._lengthbuf = self._wrapper.create_memoryview().cast('i')
def __getstate__(self):
return (self._wrapper, self._lock)
def append(self, _):
with self._lock:
self._lengthbuf[0] += 1
def __len__(self):
with self._lock:
return self._lengthbuf[0]
def _wait():
# A crude wait/yield function not relying on synchronization primitives.
time.sleep(0.01)
class Bunch(object):
"""
A bunch of threads.
"""
def __init__(self, namespace, f, args, n, wait_before_exit=False):
"""
Construct a bunch of `n` threads running the same function `f`.
If `wait_before_exit` is True, the threads won't terminate until
do_finish() is called.
"""
self.f = f
self.args = args
self.n = n
self.started = namespace.DummyList()
self.finished = namespace.DummyList()
self._can_exit = namespace.Event()
if not wait_before_exit:
self._can_exit.set()
threads = []
for i in range(n):
p = namespace.Process(target=self.task)
p.daemon = True
p.start()
threads.append(p)
def finalize(threads):
for p in threads:
p.join()
self._finalizer = weakref.finalize(self, finalize, threads)
def task(self):
pid = os.getpid()
self.started.append(pid)
try:
self.f(*self.args)
finally:
self.finished.append(pid)
self._can_exit.wait(30)
assert self._can_exit.is_set()
def wait_for_started(self):
while len(self.started) < self.n:
_wait()
def wait_for_finished(self):
while len(self.finished) < self.n:
_wait()
def do_finish(self):
self._can_exit.set()
def close(self):
self._finalizer()
class AppendTrue(object):
def __init__(self, obj):
self.obj = obj
def __call__(self):
self.obj.append(True)
class _TestBarrier(BaseTestCase):
"""
Tests for Barrier objects.
"""
N = 5
defaultTimeout = 30.0 # XXX Slow Windows buildbots need generous timeout
def setUp(self):
self.barrier = self.Barrier(self.N, timeout=self.defaultTimeout)
def tearDown(self):
self.barrier.abort()
self.barrier = None
def DummyList(self):
if self.TYPE == 'threads':
return []
elif self.TYPE == 'manager':
return self.manager.list()
else:
return _DummyList()
def run_threads(self, f, args):
b = Bunch(self, f, args, self.N-1)
try:
f(*args)
b.wait_for_finished()
finally:
b.close()
@classmethod
def multipass(cls, barrier, results, n):
m = barrier.parties
assert m == cls.N
for i in range(n):
results[0].append(True)
assert len(results[1]) == i * m
barrier.wait()
results[1].append(True)
assert len(results[0]) == (i + 1) * m
barrier.wait()
try:
assert barrier.n_waiting == 0
except NotImplementedError:
pass
assert not barrier.broken
def test_barrier(self, passes=1):
"""
Test that a barrier is passed in lockstep
"""
results = [self.DummyList(), self.DummyList()]
self.run_threads(self.multipass, (self.barrier, results, passes))
def test_barrier_10(self):
"""
Test that a barrier works for 10 consecutive runs
"""
return self.test_barrier(10)
@classmethod
def _test_wait_return_f(cls, barrier, queue):
res = barrier.wait()
queue.put(res)
def test_wait_return(self):
"""
test the return value from barrier.wait
"""
queue = self.Queue()
self.run_threads(self._test_wait_return_f, (self.barrier, queue))
results = [queue.get() for i in range(self.N)]
self.assertEqual(results.count(0), 1)
close_queue(queue)
@classmethod
def _test_action_f(cls, barrier, results):
barrier.wait()
if len(results) != 1:
raise RuntimeError
def test_action(self):
"""
Test the 'action' callback
"""
results = self.DummyList()
barrier = self.Barrier(self.N, action=AppendTrue(results))
self.run_threads(self._test_action_f, (barrier, results))
self.assertEqual(len(results), 1)
@classmethod
def _test_abort_f(cls, barrier, results1, results2):
try:
i = barrier.wait()
if i == cls.N//2:
raise RuntimeError
barrier.wait()
results1.append(True)
except threading.BrokenBarrierError:
results2.append(True)
except RuntimeError:
barrier.abort()
def test_abort(self):
"""
Test that an abort will put the barrier in a broken state
"""
results1 = self.DummyList()
results2 = self.DummyList()
self.run_threads(self._test_abort_f,
(self.barrier, results1, results2))
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertTrue(self.barrier.broken)
@classmethod
def _test_reset_f(cls, barrier, results1, results2, results3):
i = barrier.wait()
if i == cls.N//2:
# Wait until the other threads are all in the barrier.
while barrier.n_waiting < cls.N-1:
time.sleep(0.001)
barrier.reset()
else:
try:
barrier.wait()
results1.append(True)
except threading.BrokenBarrierError:
results2.append(True)
# Now, pass the barrier again
barrier.wait()
results3.append(True)
def test_reset(self):
"""
Test that a 'reset' on a barrier frees the waiting threads
"""
results1 = self.DummyList()
results2 = self.DummyList()
results3 = self.DummyList()
self.run_threads(self._test_reset_f,
(self.barrier, results1, results2, results3))
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertEqual(len(results3), self.N)
@classmethod
def _test_abort_and_reset_f(cls, barrier, barrier2,
results1, results2, results3):
try:
i = barrier.wait()
if i == cls.N//2:
raise RuntimeError
barrier.wait()
results1.append(True)
except threading.BrokenBarrierError:
results2.append(True)
except RuntimeError:
barrier.abort()
# Synchronize and reset the barrier. Must synchronize first so
# that everyone has left it when we reset, and after so that no
# one enters it before the reset.
if barrier2.wait() == cls.N//2:
barrier.reset()
barrier2.wait()
barrier.wait()
results3.append(True)
def test_abort_and_reset(self):
"""
Test that a barrier can be reset after being broken.
"""
results1 = self.DummyList()
results2 = self.DummyList()
results3 = self.DummyList()
barrier2 = self.Barrier(self.N)
self.run_threads(self._test_abort_and_reset_f,
(self.barrier, barrier2, results1, results2, results3))
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertEqual(len(results3), self.N)
@classmethod
def _test_timeout_f(cls, barrier, results):
i = barrier.wait()
if i == cls.N//2:
# One thread is late!
time.sleep(1.0)
try:
barrier.wait(0.5)
except threading.BrokenBarrierError:
results.append(True)
def test_timeout(self):
"""
Test wait(timeout)
"""
results = self.DummyList()
self.run_threads(self._test_timeout_f, (self.barrier, results))
self.assertEqual(len(results), self.barrier.parties)
@classmethod
def _test_default_timeout_f(cls, barrier, results):
i = barrier.wait(cls.defaultTimeout)
if i == cls.N//2:
# One thread is later than the default timeout
time.sleep(1.0)
try:
barrier.wait()
except threading.BrokenBarrierError:
results.append(True)
def test_default_timeout(self):
"""
Test the barrier's default timeout
"""
barrier = self.Barrier(self.N, timeout=0.5)
results = self.DummyList()
self.run_threads(self._test_default_timeout_f, (barrier, results))
self.assertEqual(len(results), barrier.parties)
def test_single_thread(self):
b = self.Barrier(1)
b.wait()
b.wait()
@classmethod
def _test_thousand_f(cls, barrier, passes, conn, lock):
for i in range(passes):
barrier.wait()
with lock:
conn.send(i)
def test_thousand(self):
if self.TYPE == 'manager':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
passes = 1000
lock = self.Lock()
conn, child_conn = self.Pipe(False)
for j in range(self.N):
p = self.Process(target=self._test_thousand_f,
args=(self.barrier, passes, child_conn, lock))
p.start()
self.addCleanup(p.join)
for i in range(passes):
for j in range(self.N):
self.assertEqual(conn.recv(), i)
#
#
#
class _TestValue(BaseTestCase):
ALLOWED_TYPES = ('processes',)
codes_values = [
('i', 4343, 24234),
('d', 3.625, -4.25),
('h', -232, 234),
('q', 2 ** 33, 2 ** 34),
('c', latin('x'), latin('y'))
]
def setUp(self):
if not HAS_SHAREDCTYPES:
self.skipTest("requires multiprocessing.sharedctypes")
@classmethod
def _test(cls, values):
for sv, cv in zip(values, cls.codes_values):
sv.value = cv[2]
def test_value(self, raw=False):
if raw:
values = [self.RawValue(code, value)
for code, value, _ in self.codes_values]
else:
values = [self.Value(code, value)
for code, value, _ in self.codes_values]
for sv, cv in zip(values, self.codes_values):
self.assertEqual(sv.value, cv[1])
proc = self.Process(target=self._test, args=(values,))
proc.daemon = True
proc.start()
proc.join()
for sv, cv in zip(values, self.codes_values):
self.assertEqual(sv.value, cv[2])
def test_rawvalue(self):
self.test_value(raw=True)
def test_getobj_getlock(self):
val1 = self.Value('i', 5)
lock1 = val1.get_lock()
obj1 = val1.get_obj()
val2 = self.Value('i', 5, lock=None)
lock2 = val2.get_lock()
obj2 = val2.get_obj()
lock = self.Lock()
val3 = self.Value('i', 5, lock=lock)
lock3 = val3.get_lock()
obj3 = val3.get_obj()
self.assertEqual(lock, lock3)
arr4 = self.Value('i', 5, lock=False)
self.assertFalse(hasattr(arr4, 'get_lock'))
self.assertFalse(hasattr(arr4, 'get_obj'))
self.assertRaises(AttributeError, self.Value, 'i', 5, lock='navalue')
arr5 = self.RawValue('i', 5)
self.assertFalse(hasattr(arr5, 'get_lock'))
self.assertFalse(hasattr(arr5, 'get_obj'))
class _TestArray(BaseTestCase):
ALLOWED_TYPES = ('processes',)
@classmethod
def f(cls, seq):
for i in range(1, len(seq)):
seq[i] += seq[i-1]
@unittest.skipIf(c_int is None, "requires _ctypes")
def test_array(self, raw=False):
seq = [680, 626, 934, 821, 150, 233, 548, 982, 714, 831]
if raw:
arr = self.RawArray('i', seq)
else:
arr = self.Array('i', seq)
self.assertEqual(len(arr), len(seq))
self.assertEqual(arr[3], seq[3])
self.assertEqual(list(arr[2:7]), list(seq[2:7]))
arr[4:8] = seq[4:8] = array.array('i', [1, 2, 3, 4])
self.assertEqual(list(arr[:]), seq)
self.f(seq)
p = self.Process(target=self.f, args=(arr,))
p.daemon = True
p.start()
p.join()
self.assertEqual(list(arr[:]), seq)
@unittest.skipIf(c_int is None, "requires _ctypes")
def test_array_from_size(self):
size = 10
# Test for zeroing (see issue #11675).
# The repetition below strengthens the test by increasing the chances
# of previously allocated non-zero memory being used for the new array
# on the 2nd and 3rd loops.
for _ in range(3):
arr = self.Array('i', size)
self.assertEqual(len(arr), size)
self.assertEqual(list(arr), [0] * size)
arr[:] = range(10)
self.assertEqual(list(arr), list(range(10)))
del arr
@unittest.skipIf(c_int is None, "requires _ctypes")
def test_rawarray(self):
self.test_array(raw=True)
@unittest.skipIf(c_int is None, "requires _ctypes")
def test_getobj_getlock_obj(self):
arr1 = self.Array('i', list(range(10)))
lock1 = arr1.get_lock()
obj1 = arr1.get_obj()
arr2 = self.Array('i', list(range(10)), lock=None)
lock2 = arr2.get_lock()
obj2 = arr2.get_obj()
lock = self.Lock()
arr3 = self.Array('i', list(range(10)), lock=lock)
lock3 = arr3.get_lock()
obj3 = arr3.get_obj()
self.assertEqual(lock, lock3)
arr4 = self.Array('i', range(10), lock=False)
self.assertFalse(hasattr(arr4, 'get_lock'))
self.assertFalse(hasattr(arr4, 'get_obj'))
self.assertRaises(AttributeError,
self.Array, 'i', range(10), lock='notalock')
arr5 = self.RawArray('i', range(10))
self.assertFalse(hasattr(arr5, 'get_lock'))
self.assertFalse(hasattr(arr5, 'get_obj'))
#
#
#
class _TestContainers(BaseTestCase):
ALLOWED_TYPES = ('manager',)
def test_list(self):
a = self.list(list(range(10)))
self.assertEqual(a[:], list(range(10)))
b = self.list()
self.assertEqual(b[:], [])
b.extend(list(range(5)))
self.assertEqual(b[:], list(range(5)))
self.assertEqual(b[2], 2)
self.assertEqual(b[2:10], [2,3,4])
b *= 2
self.assertEqual(b[:], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4])
self.assertEqual(b + [5, 6], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6])
self.assertEqual(a[:], list(range(10)))
d = [a, b]
e = self.list(d)
self.assertEqual(
[element[:] for element in e],
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]]
)
f = self.list([a])
a.append('hello')
self.assertEqual(f[0][:], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'hello'])
def test_list_iter(self):
a = self.list(list(range(10)))
it = iter(a)
self.assertEqual(list(it), list(range(10)))
self.assertEqual(list(it), []) # exhausted
# list modified during iteration
it = iter(a)
a[0] = 100
self.assertEqual(next(it), 100)
def test_list_proxy_in_list(self):
a = self.list([self.list(range(3)) for _i in range(3)])
self.assertEqual([inner[:] for inner in a], [[0, 1, 2]] * 3)
a[0][-1] = 55
self.assertEqual(a[0][:], [0, 1, 55])
for i in range(1, 3):
self.assertEqual(a[i][:], [0, 1, 2])
self.assertEqual(a[1].pop(), 2)
self.assertEqual(len(a[1]), 2)
for i in range(0, 3, 2):
self.assertEqual(len(a[i]), 3)
del a
b = self.list()
b.append(b)
del b
def test_dict(self):
d = self.dict()
indices = list(range(65, 70))
for i in indices:
d[i] = chr(i)
self.assertEqual(d.copy(), dict((i, chr(i)) for i in indices))
self.assertEqual(sorted(d.keys()), indices)
self.assertEqual(sorted(d.values()), [chr(i) for i in indices])
self.assertEqual(sorted(d.items()), [(i, chr(i)) for i in indices])
def test_dict_iter(self):
d = self.dict()
indices = list(range(65, 70))
for i in indices:
d[i] = chr(i)
it = iter(d)
self.assertEqual(list(it), indices)
self.assertEqual(list(it), []) # exhausted
# dictionary changed size during iteration
it = iter(d)
d.clear()
self.assertRaises(RuntimeError, next, it)
def test_dict_proxy_nested(self):
pets = self.dict(ferrets=2, hamsters=4)
supplies = self.dict(water=10, feed=3)
d = self.dict(pets=pets, supplies=supplies)
self.assertEqual(supplies['water'], 10)
self.assertEqual(d['supplies']['water'], 10)
d['supplies']['blankets'] = 5
self.assertEqual(supplies['blankets'], 5)
self.assertEqual(d['supplies']['blankets'], 5)
d['supplies']['water'] = 7
self.assertEqual(supplies['water'], 7)
self.assertEqual(d['supplies']['water'], 7)
del pets
del supplies
self.assertEqual(d['pets']['ferrets'], 2)
d['supplies']['blankets'] = 11
self.assertEqual(d['supplies']['blankets'], 11)
pets = d['pets']
supplies = d['supplies']
supplies['water'] = 7
self.assertEqual(supplies['water'], 7)
self.assertEqual(d['supplies']['water'], 7)
d.clear()
self.assertEqual(len(d), 0)
self.assertEqual(supplies['water'], 7)
self.assertEqual(pets['hamsters'], 4)
l = self.list([pets, supplies])
l[0]['marmots'] = 1
self.assertEqual(pets['marmots'], 1)
self.assertEqual(l[0]['marmots'], 1)
del pets
del supplies
self.assertEqual(l[0]['marmots'], 1)
outer = self.list([[88, 99], l])
self.assertIsInstance(outer[0], list) # Not a ListProxy
self.assertEqual(outer[-1][-1]['feed'], 3)
def test_namespace(self):
n = self.Namespace()
n.name = 'Bob'
n.job = 'Builder'
n._hidden = 'hidden'
self.assertEqual((n.name, n.job), ('Bob', 'Builder'))
del n.job
self.assertEqual(str(n), "Namespace(name='Bob')")
self.assertTrue(hasattr(n, 'name'))
self.assertTrue(not hasattr(n, 'job'))
#
#
#
def sqr(x, wait=0.0):
time.sleep(wait)
return x*x
def mul(x, y):
return x*y
def raise_large_valuerror(wait):
time.sleep(wait)
raise ValueError("x" * 1024**2)
def identity(x):
return x
class CountedObject(object):
n_instances = 0
def __new__(cls):
cls.n_instances += 1
return object.__new__(cls)
def __del__(self):
type(self).n_instances -= 1
class SayWhenError(ValueError): pass
def exception_throwing_generator(total, when):
if when == -1:
raise SayWhenError("Somebody said when")
for i in range(total):
if i == when:
raise SayWhenError("Somebody said when")
yield i
class _TestPool(BaseTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.pool = cls.Pool(4)
@classmethod
def tearDownClass(cls):
cls.pool.terminate()
cls.pool.join()
cls.pool = None
super().tearDownClass()
def test_apply(self):
papply = self.pool.apply
self.assertEqual(papply(sqr, (5,)), sqr(5))
self.assertEqual(papply(sqr, (), {'x':3}), sqr(x=3))
def test_map(self):
pmap = self.pool.map
self.assertEqual(pmap(sqr, list(range(10))), list(map(sqr, list(range(10)))))
self.assertEqual(pmap(sqr, list(range(100)), chunksize=20),
list(map(sqr, list(range(100)))))
def test_starmap(self):
psmap = self.pool.starmap
tuples = list(zip(range(10), range(9,-1, -1)))
self.assertEqual(psmap(mul, tuples),
list(itertools.starmap(mul, tuples)))
tuples = list(zip(range(100), range(99,-1, -1)))
self.assertEqual(psmap(mul, tuples, chunksize=20),
list(itertools.starmap(mul, tuples)))
def test_starmap_async(self):
tuples = list(zip(range(100), range(99,-1, -1)))
self.assertEqual(self.pool.starmap_async(mul, tuples).get(),
list(itertools.starmap(mul, tuples)))
def test_map_async(self):
self.assertEqual(self.pool.map_async(sqr, list(range(10))).get(),
list(map(sqr, list(range(10)))))
def test_map_async_callbacks(self):
call_args = self.manager.list() if self.TYPE == 'manager' else []
self.pool.map_async(int, ['1'],
callback=call_args.append,
error_callback=call_args.append).wait()
self.assertEqual(1, len(call_args))
self.assertEqual([1], call_args[0])
self.pool.map_async(int, ['a'],
callback=call_args.append,
error_callback=call_args.append).wait()
self.assertEqual(2, len(call_args))
self.assertIsInstance(call_args[1], ValueError)
def test_map_unplicklable(self):
# Issue #19425 -- failure to pickle should not cause a hang
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
class A(object):
def __reduce__(self):
raise RuntimeError('cannot pickle')
with self.assertRaises(RuntimeError):
self.pool.map(sqr, [A()]*10)
def test_map_chunksize(self):
try:
self.pool.map_async(sqr, [], chunksize=1).get(timeout=TIMEOUT1)
except multiprocessing.TimeoutError:
self.fail("pool.map_async with chunksize stalled on null list")
def test_map_handle_iterable_exception(self):
if self.TYPE == 'manager':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
# SayWhenError seen at the very first of the iterable
with self.assertRaises(SayWhenError):
self.pool.map(sqr, exception_throwing_generator(1, -1), 1)
# again, make sure it's reentrant
with self.assertRaises(SayWhenError):
self.pool.map(sqr, exception_throwing_generator(1, -1), 1)
with self.assertRaises(SayWhenError):
self.pool.map(sqr, exception_throwing_generator(10, 3), 1)
class SpecialIterable:
def __iter__(self):
return self
def __next__(self):
raise SayWhenError
def __len__(self):
return 1
with self.assertRaises(SayWhenError):
self.pool.map(sqr, SpecialIterable(), 1)
with self.assertRaises(SayWhenError):
self.pool.map(sqr, SpecialIterable(), 1)
def test_async(self):
res = self.pool.apply_async(sqr, (7, TIMEOUT1,))
get = TimingWrapper(res.get)
self.assertEqual(get(), 49)
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1)
def test_async_timeout(self):
res = self.pool.apply_async(sqr, (6, TIMEOUT2 + 1.0))
get = TimingWrapper(res.get)
self.assertRaises(multiprocessing.TimeoutError, get, timeout=TIMEOUT2)
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT2)
def test_imap(self):
it = self.pool.imap(sqr, list(range(10)))
self.assertEqual(list(it), list(map(sqr, list(range(10)))))
it = self.pool.imap(sqr, list(range(10)))
for i in range(10):
self.assertEqual(next(it), i*i)
self.assertRaises(StopIteration, it.__next__)
it = self.pool.imap(sqr, list(range(1000)), chunksize=100)
for i in range(1000):
self.assertEqual(next(it), i*i)
self.assertRaises(StopIteration, it.__next__)
def test_imap_handle_iterable_exception(self):
if self.TYPE == 'manager':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
# SayWhenError seen at the very first of the iterable
it = self.pool.imap(sqr, exception_throwing_generator(1, -1), 1)
self.assertRaises(SayWhenError, it.__next__)
# again, make sure it's reentrant
it = self.pool.imap(sqr, exception_throwing_generator(1, -1), 1)
self.assertRaises(SayWhenError, it.__next__)
it = self.pool.imap(sqr, exception_throwing_generator(10, 3), 1)
for i in range(3):
self.assertEqual(next(it), i*i)
self.assertRaises(SayWhenError, it.__next__)
# SayWhenError seen at start of problematic chunk's results
it = self.pool.imap(sqr, exception_throwing_generator(20, 7), 2)
for i in range(6):
self.assertEqual(next(it), i*i)
self.assertRaises(SayWhenError, it.__next__)
it = self.pool.imap(sqr, exception_throwing_generator(20, 7), 4)
for i in range(4):
self.assertEqual(next(it), i*i)
self.assertRaises(SayWhenError, it.__next__)
def test_imap_unordered(self):
it = self.pool.imap_unordered(sqr, list(range(10)))
self.assertEqual(sorted(it), list(map(sqr, list(range(10)))))
it = self.pool.imap_unordered(sqr, list(range(1000)), chunksize=100)
self.assertEqual(sorted(it), list(map(sqr, list(range(1000)))))
def test_imap_unordered_handle_iterable_exception(self):
if self.TYPE == 'manager':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
# SayWhenError seen at the very first of the iterable
it = self.pool.imap_unordered(sqr,
exception_throwing_generator(1, -1),
1)
self.assertRaises(SayWhenError, it.__next__)
# again, make sure it's reentrant
it = self.pool.imap_unordered(sqr,
exception_throwing_generator(1, -1),
1)
self.assertRaises(SayWhenError, it.__next__)
it = self.pool.imap_unordered(sqr,
exception_throwing_generator(10, 3),
1)
expected_values = list(map(sqr, list(range(10))))
with self.assertRaises(SayWhenError):
# imap_unordered makes it difficult to anticipate the SayWhenError
for i in range(10):
value = next(it)
self.assertIn(value, expected_values)
expected_values.remove(value)
it = self.pool.imap_unordered(sqr,
exception_throwing_generator(20, 7),
2)
expected_values = list(map(sqr, list(range(20))))
with self.assertRaises(SayWhenError):
for i in range(20):
value = next(it)
self.assertIn(value, expected_values)
expected_values.remove(value)
def test_make_pool(self):
expected_error = (RemoteError if self.TYPE == 'manager'
else ValueError)
self.assertRaises(expected_error, self.Pool, -1)
self.assertRaises(expected_error, self.Pool, 0)
if self.TYPE != 'manager':
p = self.Pool(3)
try:
self.assertEqual(3, len(p._pool))
finally:
p.close()
p.join()
def test_terminate(self):
result = self.pool.map_async(
time.sleep, [0.1 for i in range(10000)], chunksize=1
)
self.pool.terminate()
join = TimingWrapper(self.pool.join)
join()
# Sanity check the pool didn't wait for all tasks to finish
self.assertLess(join.elapsed, 2.0)
def test_empty_iterable(self):
# See Issue 12157
p = self.Pool(1)
self.assertEqual(p.map(sqr, []), [])
self.assertEqual(list(p.imap(sqr, [])), [])
self.assertEqual(list(p.imap_unordered(sqr, [])), [])
self.assertEqual(p.map_async(sqr, []).get(), [])
p.close()
p.join()
def test_context(self):
if self.TYPE == 'processes':
L = list(range(10))
expected = [sqr(i) for i in L]
with self.Pool(2) as p:
r = p.map_async(sqr, L)
self.assertEqual(r.get(), expected)
p.join()
self.assertRaises(ValueError, p.map_async, sqr, L)
@classmethod
def _test_traceback(cls):
raise RuntimeError(123) # some comment
def test_traceback(self):
# We want ensure that the traceback from the child process is
# contained in the traceback raised in the main process.
if self.TYPE == 'processes':
with self.Pool(1) as p:
try:
p.apply(self._test_traceback)
except Exception as e:
exc = e
else:
self.fail('expected RuntimeError')
p.join()
self.assertIs(type(exc), RuntimeError)
self.assertEqual(exc.args, (123,))
cause = exc.__cause__
self.assertIs(type(cause), multiprocessing.pool.RemoteTraceback)
self.assertIn('raise RuntimeError(123) # some comment', cause.tb)
with test.support.captured_stderr() as f1:
try:
raise exc
except RuntimeError:
sys.excepthook(*sys.exc_info())
self.assertIn('raise RuntimeError(123) # some comment',
f1.getvalue())
# _helper_reraises_exception should not make the error
# a remote exception
with self.Pool(1) as p:
try:
p.map(sqr, exception_throwing_generator(1, -1), 1)
except Exception as e:
exc = e
else:
self.fail('expected SayWhenError')
self.assertIs(type(exc), SayWhenError)
self.assertIs(exc.__cause__, None)
p.join()
@classmethod
def _test_wrapped_exception(cls):
raise RuntimeError('foo')
def test_wrapped_exception(self):
# Issue #20980: Should not wrap exception when using thread pool
with self.Pool(1) as p:
with self.assertRaises(RuntimeError):
p.apply(self._test_wrapped_exception)
p.join()
def test_map_no_failfast(self):
# Issue #23992: the fail-fast behaviour when an exception is raised
# during map() would make Pool.join() deadlock, because a worker
# process would fill the result queue (after the result handler thread
# terminated, hence not draining it anymore).
t_start = time.monotonic()
with self.assertRaises(ValueError):
with self.Pool(2) as p:
try:
p.map(raise_large_valuerror, [0, 1])
finally:
time.sleep(0.5)
p.close()
p.join()
# check that we indeed waited for all jobs
self.assertGreater(time.monotonic() - t_start, 0.9)
def test_release_task_refs(self):
# Issue #29861: task arguments and results should not be kept
# alive after we are done with them.
objs = [CountedObject() for i in range(10)]
refs = [weakref.ref(o) for o in objs]
self.pool.map(identity, objs)
del objs
for i in range(3):
gc.collect()
time.sleep(DELTA) # let threaded cleanup code run
self.assertEqual(set(wr() for wr in refs), {None})
# With a process pool, copies of the objects are returned, check
# they were released too.
self.assertEqual(CountedObject.n_instances, 0)
def raising():
raise KeyError("key")
def unpickleable_result():
return lambda: 42
class _TestPoolWorkerErrors(BaseTestCase):
ALLOWED_TYPES = ('processes', )
def test_async_error_callback(self):
p = multiprocessing.Pool(2)
scratchpad = [None]
def errback(exc):
scratchpad[0] = exc
res = p.apply_async(raising, error_callback=errback)
self.assertRaises(KeyError, res.get)
self.assertTrue(scratchpad[0])
self.assertIsInstance(scratchpad[0], KeyError)
p.close()
p.join()
def test_unpickleable_result(self):
from multiprocessing.pool import MaybeEncodingError
p = multiprocessing.Pool(2)
# Make sure we don't lose pool processes because of encoding errors.
for iteration in range(20):
scratchpad = [None]
def errback(exc):
scratchpad[0] = exc
res = p.apply_async(unpickleable_result, error_callback=errback)
self.assertRaises(MaybeEncodingError, res.get)
wrapped = scratchpad[0]
self.assertTrue(wrapped)
self.assertIsInstance(scratchpad[0], MaybeEncodingError)
self.assertIsNotNone(wrapped.exc)
self.assertIsNotNone(wrapped.value)
p.close()
p.join()
class _TestPoolWorkerLifetime(BaseTestCase):
ALLOWED_TYPES = ('processes', )
def test_pool_worker_lifetime(self):
p = multiprocessing.Pool(3, maxtasksperchild=10)
self.assertEqual(3, len(p._pool))
origworkerpids = [w.pid for w in p._pool]
# Run many tasks so each worker gets replaced (hopefully)
results = []
for i in range(100):
results.append(p.apply_async(sqr, (i, )))
# Fetch the results and verify we got the right answers,
# also ensuring all the tasks have completed.
for (j, res) in enumerate(results):
self.assertEqual(res.get(), sqr(j))
# Refill the pool
p._repopulate_pool()
# Wait until all workers are alive
# (countdown * DELTA = 5 seconds max startup process time)
countdown = 50
while countdown and not all(w.is_alive() for w in p._pool):
countdown -= 1
time.sleep(DELTA)
finalworkerpids = [w.pid for w in p._pool]
# All pids should be assigned. See issue #7805.
self.assertNotIn(None, origworkerpids)
self.assertNotIn(None, finalworkerpids)
# Finally, check that the worker pids have changed
self.assertNotEqual(sorted(origworkerpids), sorted(finalworkerpids))
p.close()
p.join()
def test_pool_worker_lifetime_early_close(self):
# Issue #10332: closing a pool whose workers have limited lifetimes
# before all the tasks completed would make join() hang.
p = multiprocessing.Pool(3, maxtasksperchild=1)
results = []
for i in range(6):
results.append(p.apply_async(sqr, (i, 0.3)))
p.close()
p.join()
# check the results
for (j, res) in enumerate(results):
self.assertEqual(res.get(), sqr(j))
#
# Test of creating a customized manager class
#
from multiprocessing.managers import BaseManager, BaseProxy, RemoteError
class FooBar(object):
def f(self):
return 'f()'
def g(self):
raise ValueError
def _h(self):
return '_h()'
def baz():
for i in range(10):
yield i*i
class IteratorProxy(BaseProxy):
_exposed_ = ('__next__',)
def __iter__(self):
return self
def __next__(self):
return self._callmethod('__next__')
class MyManager(BaseManager):
pass
MyManager.register('Foo', callable=FooBar)
MyManager.register('Bar', callable=FooBar, exposed=('f', '_h'))
MyManager.register('baz', callable=baz, proxytype=IteratorProxy)
class _TestMyManager(BaseTestCase):
ALLOWED_TYPES = ('manager',)
def test_mymanager(self):
manager = MyManager()
manager.start()
self.common(manager)
manager.shutdown()
# bpo-30356: BaseManager._finalize_manager() sends SIGTERM
# to the manager process if it takes longer than 1 second to stop,
# which happens on slow buildbots.
self.assertIn(manager._process.exitcode, (0, -signal.SIGTERM))
def test_mymanager_context(self):
with MyManager() as manager:
self.common(manager)
# bpo-30356: BaseManager._finalize_manager() sends SIGTERM
# to the manager process if it takes longer than 1 second to stop,
# which happens on slow buildbots.
self.assertIn(manager._process.exitcode, (0, -signal.SIGTERM))
def test_mymanager_context_prestarted(self):
manager = MyManager()
manager.start()
with manager:
self.common(manager)
self.assertEqual(manager._process.exitcode, 0)
def common(self, manager):
foo = manager.Foo()
bar = manager.Bar()
baz = manager.baz()
foo_methods = [name for name in ('f', 'g', '_h') if hasattr(foo, name)]
bar_methods = [name for name in ('f', 'g', '_h') if hasattr(bar, name)]
self.assertEqual(foo_methods, ['f', 'g'])
self.assertEqual(bar_methods, ['f', '_h'])
self.assertEqual(foo.f(), 'f()')
self.assertRaises(ValueError, foo.g)
self.assertEqual(foo._callmethod('f'), 'f()')
self.assertRaises(RemoteError, foo._callmethod, '_h')
self.assertEqual(bar.f(), 'f()')
self.assertEqual(bar._h(), '_h()')
self.assertEqual(bar._callmethod('f'), 'f()')
self.assertEqual(bar._callmethod('_h'), '_h()')
self.assertEqual(list(baz), [i*i for i in range(10)])
#
# Test of connecting to a remote server and using xmlrpclib for serialization
#
_queue = pyqueue.Queue()
def get_queue():
return _queue
class QueueManager(BaseManager):
'''manager class used by server process'''
QueueManager.register('get_queue', callable=get_queue)
class QueueManager2(BaseManager):
'''manager class which specifies the same interface as QueueManager'''
QueueManager2.register('get_queue')
SERIALIZER = 'xmlrpclib'
class _TestRemoteManager(BaseTestCase):
ALLOWED_TYPES = ('manager',)
values = ['hello world', None, True, 2.25,
'hall\xe5 v\xe4rlden',
'\u043f\u0440\u0438\u0432\u0456\u0442 \u0441\u0432\u0456\u0442',
b'hall\xe5 v\xe4rlden',
]
result = values[:]
@classmethod
def _putter(cls, address, authkey):
manager = QueueManager2(
address=address, authkey=authkey, serializer=SERIALIZER
)
manager.connect()
queue = manager.get_queue()
# Note that xmlrpclib will deserialize object as a list not a tuple
queue.put(tuple(cls.values))
def test_remote(self):
authkey = os.urandom(32)
manager = QueueManager(
address=(test.support.HOST, 0), authkey=authkey, serializer=SERIALIZER
)
manager.start()
self.addCleanup(manager.shutdown)
p = self.Process(target=self._putter, args=(manager.address, authkey))
p.daemon = True
p.start()
manager2 = QueueManager2(
address=manager.address, authkey=authkey, serializer=SERIALIZER
)
manager2.connect()
queue = manager2.get_queue()
self.assertEqual(queue.get(), self.result)
# Because we are using xmlrpclib for serialization instead of
# pickle this will cause a serialization error.
# Changed on PyPy: passing functions to xmlrpc is broken
#self.assertRaises(Exception, queue.put, time.sleep)
# Make queue finalizer run before the server is stopped
del queue
class _TestManagerRestart(BaseTestCase):
@classmethod
def _putter(cls, address, authkey):
manager = QueueManager(
address=address, authkey=authkey, serializer=SERIALIZER)
manager.connect()
queue = manager.get_queue()
queue.put('hello world')
def test_rapid_restart(self):
authkey = os.urandom(32)
manager = QueueManager(
address=(test.support.HOST, 0), authkey=authkey, serializer=SERIALIZER)
try:
srvr = manager.get_server()
addr = srvr.address
# Close the connection.Listener socket which gets opened as a part
# of manager.get_server(). It's not needed for the test.
srvr.listener.close()
manager.start()
p = self.Process(target=self._putter, args=(manager.address, authkey))
p.start()
p.join()
queue = manager.get_queue()
self.assertEqual(queue.get(), 'hello world')
del queue
finally:
if hasattr(manager, "shutdown"):
manager.shutdown()
manager = QueueManager(
address=addr, authkey=authkey, serializer=SERIALIZER)
try:
manager.start()
self.addCleanup(manager.shutdown)
except OSError as e:
if e.errno != errno.EADDRINUSE:
raise
# Retry after some time, in case the old socket was lingering
# (sporadic failure on buildbots)
time.sleep(1.0)
manager = QueueManager(
address=addr, authkey=authkey, serializer=SERIALIZER)
if hasattr(manager, "shutdown"):
self.addCleanup(manager.shutdown)
#
#
#
SENTINEL = latin('')
class _TestConnection(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
@classmethod
def _echo(cls, conn):
for msg in iter(conn.recv_bytes, SENTINEL):
conn.send_bytes(msg)
conn.close()
def test_connection(self):
conn, child_conn = self.Pipe()
p = self.Process(target=self._echo, args=(child_conn,))
p.daemon = True
p.start()
seq = [1, 2.25, None]
msg = latin('hello world')
longmsg = msg * 10
arr = array.array('i', list(range(4)))
if self.TYPE == 'processes':
self.assertEqual(type(conn.fileno()), int)
self.assertEqual(conn.send(seq), None)
self.assertEqual(conn.recv(), seq)
self.assertEqual(conn.send_bytes(msg), None)
self.assertEqual(conn.recv_bytes(), msg)
if self.TYPE == 'processes':
buffer = array.array('i', [0]*10)
expected = list(arr) + [0] * (10 - len(arr))
self.assertEqual(conn.send_bytes(arr), None)
self.assertEqual(conn.recv_bytes_into(buffer),
len(arr) * buffer.itemsize)
self.assertEqual(list(buffer), expected)
buffer = array.array('i', [0]*10)
expected = [0] * 3 + list(arr) + [0] * (10 - 3 - len(arr))
self.assertEqual(conn.send_bytes(arr), None)
self.assertEqual(conn.recv_bytes_into(buffer, 3 * buffer.itemsize),
len(arr) * buffer.itemsize)
self.assertEqual(list(buffer), expected)
buffer = bytearray(latin(' ' * 40))
self.assertEqual(conn.send_bytes(longmsg), None)
try:
res = conn.recv_bytes_into(buffer)
except multiprocessing.BufferTooShort as e:
self.assertEqual(e.args, (longmsg,))
else:
self.fail('expected BufferTooShort, got %s' % res)
poll = TimingWrapper(conn.poll)
self.assertEqual(poll(), False)
self.assertTimingAlmostEqual(poll.elapsed, 0)
self.assertEqual(poll(-1), False)
self.assertTimingAlmostEqual(poll.elapsed, 0)
self.assertEqual(poll(TIMEOUT1), False)
self.assertTimingAlmostEqual(poll.elapsed, TIMEOUT1)
conn.send(None)
time.sleep(.1)
self.assertEqual(poll(TIMEOUT1), True)
self.assertTimingAlmostEqual(poll.elapsed, 0)
self.assertEqual(conn.recv(), None)
really_big_msg = latin('X') * (1024 * 1024 * 16) # 16Mb
conn.send_bytes(really_big_msg)
self.assertEqual(conn.recv_bytes(), really_big_msg)
conn.send_bytes(SENTINEL) # tell child to quit
child_conn.close()
if self.TYPE == 'processes':
self.assertEqual(conn.readable, True)
self.assertEqual(conn.writable, True)
self.assertRaises(EOFError, conn.recv)
self.assertRaises(EOFError, conn.recv_bytes)
p.join()
def test_duplex_false(self):
reader, writer = self.Pipe(duplex=False)
self.assertEqual(writer.send(1), None)
self.assertEqual(reader.recv(), 1)
if self.TYPE == 'processes':
self.assertEqual(reader.readable, True)
self.assertEqual(reader.writable, False)
self.assertEqual(writer.readable, False)
self.assertEqual(writer.writable, True)
self.assertRaises(OSError, reader.send, 2)
self.assertRaises(OSError, writer.recv)
self.assertRaises(OSError, writer.poll)
def test_spawn_close(self):
# We test that a pipe connection can be closed by parent
# process immediately after child is spawned. On Windows this
# would have sometimes failed on old versions because
# child_conn would be closed before the child got a chance to
# duplicate it.
conn, child_conn = self.Pipe()
p = self.Process(target=self._echo, args=(child_conn,))
p.daemon = True
p.start()
child_conn.close() # this might complete before child initializes
msg = latin('hello')
conn.send_bytes(msg)
self.assertEqual(conn.recv_bytes(), msg)
conn.send_bytes(SENTINEL)
conn.close()
p.join()
def test_sendbytes(self):
if self.TYPE != 'processes':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
msg = latin('abcdefghijklmnopqrstuvwxyz')
a, b = self.Pipe()
a.send_bytes(msg)
self.assertEqual(b.recv_bytes(), msg)
a.send_bytes(msg, 5)
self.assertEqual(b.recv_bytes(), msg[5:])
a.send_bytes(msg, 7, 8)
self.assertEqual(b.recv_bytes(), msg[7:7+8])
a.send_bytes(msg, 26)
self.assertEqual(b.recv_bytes(), latin(''))
a.send_bytes(msg, 26, 0)
self.assertEqual(b.recv_bytes(), latin(''))
self.assertRaises(ValueError, a.send_bytes, msg, 27)
self.assertRaises(ValueError, a.send_bytes, msg, 22, 5)
self.assertRaises(ValueError, a.send_bytes, msg, 26, 1)
self.assertRaises(ValueError, a.send_bytes, msg, -1)
self.assertRaises(ValueError, a.send_bytes, msg, 4, -1)
@classmethod
def _is_fd_assigned(cls, fd):
try:
os.fstat(fd)
except OSError as e:
if e.errno == errno.EBADF:
return False
raise
else:
return True
@classmethod
def _writefd(cls, conn, data, create_dummy_fds=False):
if create_dummy_fds:
for i in range(0, 256):
if not cls._is_fd_assigned(i):
os.dup2(conn.fileno(), i)
fd = reduction.recv_handle(conn)
if msvcrt:
fd = msvcrt.open_osfhandle(fd, os.O_WRONLY)
os.write(fd, data)
os.close(fd)
@unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
def test_fd_transfer(self):
if self.TYPE != 'processes':
self.skipTest("only makes sense with processes")
conn, child_conn = self.Pipe(duplex=True)
p = self.Process(target=self._writefd, args=(child_conn, b"foo"))
p.daemon = True
p.start()
self.addCleanup(test.support.unlink, test.support.TESTFN)
with open(test.support.TESTFN, "wb") as f:
fd = f.fileno()
if msvcrt:
fd = msvcrt.get_osfhandle(fd)
reduction.send_handle(conn, fd, p.pid)
p.join()
with open(test.support.TESTFN, "rb") as f:
self.assertEqual(f.read(), b"foo")
@unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
@unittest.skipIf(sys.platform == "win32",
"test semantics don't make sense on Windows")
@unittest.skipIf(MAXFD <= 256,
"largest assignable fd number is too small")
@unittest.skipUnless(hasattr(os, "dup2"),
"test needs os.dup2()")
def test_large_fd_transfer(self):
# With fd > 256 (issue #11657)
if self.TYPE != 'processes':
self.skipTest("only makes sense with processes")
conn, child_conn = self.Pipe(duplex=True)
p = self.Process(target=self._writefd, args=(child_conn, b"bar", True))
p.daemon = True
p.start()
self.addCleanup(test.support.unlink, test.support.TESTFN)
with open(test.support.TESTFN, "wb") as f:
fd = f.fileno()
for newfd in range(256, MAXFD):
if not self._is_fd_assigned(newfd):
break
else:
self.fail("could not find an unassigned large file descriptor")
os.dup2(fd, newfd)
try:
reduction.send_handle(conn, newfd, p.pid)
finally:
os.close(newfd)
p.join()
with open(test.support.TESTFN, "rb") as f:
self.assertEqual(f.read(), b"bar")
@classmethod
def _send_data_without_fd(self, conn):
os.write(conn.fileno(), b"\0")
@unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
@unittest.skipIf(sys.platform == "win32", "doesn't make sense on Windows")
def test_missing_fd_transfer(self):
# Check that exception is raised when received data is not
# accompanied by a file descriptor in ancillary data.
if self.TYPE != 'processes':
self.skipTest("only makes sense with processes")
conn, child_conn = self.Pipe(duplex=True)
p = self.Process(target=self._send_data_without_fd, args=(child_conn,))
p.daemon = True
p.start()
self.assertRaises(RuntimeError, reduction.recv_handle, conn)
p.join()
def test_context(self):
a, b = self.Pipe()
with a, b:
a.send(1729)
self.assertEqual(b.recv(), 1729)
if self.TYPE == 'processes':
self.assertFalse(a.closed)
self.assertFalse(b.closed)
if self.TYPE == 'processes':
self.assertTrue(a.closed)
self.assertTrue(b.closed)
self.assertRaises(OSError, a.recv)
self.assertRaises(OSError, b.recv)
class _TestListener(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def test_multiple_bind(self):
for family in self.connection.families:
l = self.connection.Listener(family=family)
self.addCleanup(l.close)
self.assertRaises(OSError, self.connection.Listener,
l.address, family)
def test_context(self):
with self.connection.Listener() as l:
with self.connection.Client(l.address) as c:
with l.accept() as d:
c.send(1729)
self.assertEqual(d.recv(), 1729)
if self.TYPE == 'processes':
self.assertRaises(OSError, l.accept)
@unittest.skipUnless(util.abstract_sockets_supported,
"test needs abstract socket support")
def test_abstract_socket(self):
with self.connection.Listener("\0something") as listener:
with self.connection.Client(listener.address) as client:
with listener.accept() as d:
client.send(1729)
self.assertEqual(d.recv(), 1729)
if self.TYPE == 'processes':
self.assertRaises(OSError, listener.accept)
class _TestListenerClient(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
@classmethod
def _test(cls, address):
conn = cls.connection.Client(address)
conn.send('hello')
conn.close()
def test_listener_client(self):
for family in self.connection.families:
l = self.connection.Listener(family=family)
p = self.Process(target=self._test, args=(l.address,))
p.daemon = True
p.start()
conn = l.accept()
self.assertEqual(conn.recv(), 'hello')
p.join()
l.close()
def test_issue14725(self):
l = self.connection.Listener()
p = self.Process(target=self._test, args=(l.address,))
p.daemon = True
p.start()
time.sleep(1)
# On Windows the client process should by now have connected,
# written data and closed the pipe handle by now. This causes
# ConnectNamdedPipe() to fail with ERROR_NO_DATA. See Issue
# 14725.
conn = l.accept()
self.assertEqual(conn.recv(), 'hello')
conn.close()
p.join()
l.close()
def test_issue16955(self):
for fam in self.connection.families:
l = self.connection.Listener(family=fam)
c = self.connection.Client(l.address)
a = l.accept()
a.send_bytes(b"hello")
self.assertTrue(c.poll(1))
a.close()
c.close()
l.close()
class _TestPoll(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
def test_empty_string(self):
a, b = self.Pipe()
self.assertEqual(a.poll(), False)
b.send_bytes(b'')
self.assertEqual(a.poll(), True)
self.assertEqual(a.poll(), True)
@classmethod
def _child_strings(cls, conn, strings):
for s in strings:
time.sleep(0.1)
conn.send_bytes(s)
conn.close()
def test_strings(self):
strings = (b'hello', b'', b'a', b'b', b'', b'bye', b'', b'lop')
a, b = self.Pipe()
p = self.Process(target=self._child_strings, args=(b, strings))
p.start()
for s in strings:
for i in range(200):
if a.poll(0.01):
break
x = a.recv_bytes()
self.assertEqual(s, x)
p.join()
@classmethod
def _child_boundaries(cls, r):
# Polling may "pull" a message in to the child process, but we
# don't want it to pull only part of a message, as that would
# corrupt the pipe for any other processes which might later
# read from it.
r.poll(5)
def test_boundaries(self):
r, w = self.Pipe(False)
p = self.Process(target=self._child_boundaries, args=(r,))
p.start()
time.sleep(2)
L = [b"first", b"second"]
for obj in L:
w.send_bytes(obj)
w.close()
p.join()
self.assertIn(r.recv_bytes(), L)
@classmethod
def _child_dont_merge(cls, b):
b.send_bytes(b'a')
b.send_bytes(b'b')
b.send_bytes(b'cd')
def test_dont_merge(self):
a, b = self.Pipe()
self.assertEqual(a.poll(0.0), False)
self.assertEqual(a.poll(0.1), False)
p = self.Process(target=self._child_dont_merge, args=(b,))
p.start()
self.assertEqual(a.recv_bytes(), b'a')
self.assertEqual(a.poll(1.0), True)
self.assertEqual(a.poll(1.0), True)
self.assertEqual(a.recv_bytes(), b'b')
self.assertEqual(a.poll(1.0), True)
self.assertEqual(a.poll(1.0), True)
self.assertEqual(a.poll(0.0), True)
self.assertEqual(a.recv_bytes(), b'cd')
p.join()
#
# Test of sending connection and socket objects between processes
#
@unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
class _TestPicklingConnections(BaseTestCase):
ALLOWED_TYPES = ('processes',)
@classmethod
def tearDownClass(cls):
from multiprocessing import resource_sharer
resource_sharer.stop(timeout=TIMEOUT)
@classmethod
def _listener(cls, conn, families):
for fam in families:
l = cls.connection.Listener(family=fam)
conn.send(l.address)
new_conn = l.accept()
conn.send(new_conn)
new_conn.close()
l.close()
l = socket.socket()
l.bind((test.support.HOST, 0))
l.listen()
conn.send(l.getsockname())
new_conn, addr = l.accept()
conn.send(new_conn)
new_conn.close()
l.close()
conn.recv()
@classmethod
def _remote(cls, conn):
for (address, msg) in iter(conn.recv, None):
client = cls.connection.Client(address)
client.send(msg.upper())
client.close()
address, msg = conn.recv()
client = socket.socket()
client.connect(address)
client.sendall(msg.upper())
client.close()
conn.close()
def test_pickling(self):
families = self.connection.families
lconn, lconn0 = self.Pipe()
lp = self.Process(target=self._listener, args=(lconn0, families))
lp.daemon = True
lp.start()
lconn0.close()
rconn, rconn0 = self.Pipe()
rp = self.Process(target=self._remote, args=(rconn0,))
rp.daemon = True
rp.start()
rconn0.close()
for fam in families:
msg = ('This connection uses family %s' % fam).encode('ascii')
address = lconn.recv()
rconn.send((address, msg))
new_conn = lconn.recv()
self.assertEqual(new_conn.recv(), msg.upper())
rconn.send(None)
msg = latin('This connection uses a normal socket')
address = lconn.recv()
rconn.send((address, msg))
new_conn = lconn.recv()
buf = []
while True:
s = new_conn.recv(100)
if not s:
break
buf.append(s)
buf = b''.join(buf)
self.assertEqual(buf, msg.upper())
new_conn.close()
lconn.send(None)
rconn.close()
lconn.close()
lp.join()
rp.join()
@classmethod
def child_access(cls, conn):
w = conn.recv()
w.send('all is well')
w.close()
r = conn.recv()
msg = r.recv()
conn.send(msg*2)
conn.close()
def test_access(self):
# On Windows, if we do not specify a destination pid when
# using DupHandle then we need to be careful to use the
# correct access flags for DuplicateHandle(), or else
# DupHandle.detach() will raise PermissionError. For example,
# for a read only pipe handle we should use
# access=FILE_GENERIC_READ. (Unfortunately
# DUPLICATE_SAME_ACCESS does not work.)
conn, child_conn = self.Pipe()
p = self.Process(target=self.child_access, args=(child_conn,))
p.daemon = True
p.start()
child_conn.close()
r, w = self.Pipe(duplex=False)
conn.send(w)
w.close()
self.assertEqual(r.recv(), 'all is well')
r.close()
r, w = self.Pipe(duplex=False)
conn.send(r)
r.close()
w.send('foobar')
w.close()
self.assertEqual(conn.recv(), 'foobar'*2)
p.join()
#
#
#
class _TestHeap(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def setUp(self):
super().setUp()
# Make pristine heap for these tests
self.old_heap = multiprocessing.heap.BufferWrapper._heap
multiprocessing.heap.BufferWrapper._heap = multiprocessing.heap.Heap()
def tearDown(self):
multiprocessing.heap.BufferWrapper._heap = self.old_heap
super().tearDown()
def test_heap(self):
iterations = 5000
maxblocks = 50
blocks = []
# create and destroy lots of blocks of different sizes
for i in range(iterations):
size = int(random.lognormvariate(0, 1) * 1000)
b = multiprocessing.heap.BufferWrapper(size)
blocks.append(b)
if len(blocks) > maxblocks:
i = random.randrange(maxblocks)
del blocks[i]
# get the heap object
heap = multiprocessing.heap.BufferWrapper._heap
# verify the state of the heap
all = []
occupied = 0
heap._lock.acquire()
self.addCleanup(heap._lock.release)
for L in list(heap._len_to_seq.values()):
for arena, start, stop in L:
all.append((heap._arenas.index(arena), start, stop,
stop-start, 'free'))
for arena, start, stop in heap._allocated_blocks:
all.append((heap._arenas.index(arena), start, stop,
stop-start, 'occupied'))
occupied += (stop-start)
all.sort()
for i in range(len(all)-1):
(arena, start, stop) = all[i][:3]
(narena, nstart, nstop) = all[i+1][:3]
self.assertTrue((arena != narena and nstart == 0) or
(stop == nstart))
@test.support.cpython_only
def test_free_from_gc(self):
# Check that freeing of blocks by the garbage collector doesn't deadlock
# (issue #12352).
# Make sure the GC is enabled, and set lower collection thresholds to
# make collections more frequent (and increase the probability of
# deadlock).
if not gc.isenabled():
gc.enable()
self.addCleanup(gc.disable)
thresholds = gc.get_threshold()
self.addCleanup(gc.set_threshold, *thresholds)
gc.set_threshold(10)
# perform numerous block allocations, with cyclic references to make
# sure objects are collected asynchronously by the gc
for i in range(5000):
a = multiprocessing.heap.BufferWrapper(1)
b = multiprocessing.heap.BufferWrapper(1)
# circular references
a.buddy = b
b.buddy = a
#
#
#
class _Foo(Structure):
_fields_ = [
('x', c_int),
('y', c_double),
('z', c_longlong,)
]
class _TestSharedCTypes(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def setUp(self):
if not HAS_SHAREDCTYPES:
self.skipTest("requires multiprocessing.sharedctypes")
@classmethod
def _double(cls, x, y, z, foo, arr, string):
x.value *= 2
y.value *= 2
z.value *= 2
foo.x *= 2
foo.y *= 2
string.value *= 2
for i in range(len(arr)):
arr[i] *= 2
def test_sharedctypes(self, lock=False):
x = Value('i', 7, lock=lock)
y = Value(c_double, 1.0/3.0, lock=lock)
z = Value(c_longlong, 2 ** 33, lock=lock)
foo = Value(_Foo, 3, 2, lock=lock)
arr = self.Array('d', list(range(10)), lock=lock)
string = self.Array('c', 20, lock=lock)
string.value = latin('hello')
p = self.Process(target=self._double, args=(x, y, z, foo, arr, string))
p.daemon = True
p.start()
p.join()
self.assertEqual(x.value, 14)
self.assertAlmostEqual(y.value, 2.0/3.0)
self.assertEqual(z.value, 2 ** 34)
self.assertEqual(foo.x, 6)
self.assertAlmostEqual(foo.y, 4.0)
for i in range(10):
self.assertAlmostEqual(arr[i], i*2)
self.assertEqual(string.value, latin('hellohello'))
def test_synchronize(self):
self.test_sharedctypes(lock=True)
def test_copy(self):
foo = _Foo(2, 5.0, 2 ** 33)
bar = copy(foo)
foo.x = 0
foo.y = 0
foo.z = 0
self.assertEqual(bar.x, 2)
self.assertAlmostEqual(bar.y, 5.0)
self.assertEqual(bar.z, 2 ** 33)
#
#
#
class _TestFinalize(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def setUp(self):
self.registry_backup = util._finalizer_registry.copy()
util._finalizer_registry.clear()
def tearDown(self):
for i in range(3):
gc.collect()
self.assertFalse(util._finalizer_registry)
util._finalizer_registry.update(self.registry_backup)
@classmethod
def _test_finalize(cls, conn):
class Foo(object):
pass
a = Foo()
util.Finalize(a, conn.send, args=('a',))
del a # triggers callback for a
import gc; gc.collect()
b = Foo()
close_b = util.Finalize(b, conn.send, args=('b',))
close_b() # triggers callback for b
close_b() # does nothing because callback has already been called
del b # does nothing because callback has already been called
import gc; gc.collect()
c = Foo()
util.Finalize(c, conn.send, args=('c',))
d10 = Foo()
util.Finalize(d10, conn.send, args=('d10',), exitpriority=1)
d01 = Foo()
util.Finalize(d01, conn.send, args=('d01',), exitpriority=0)
d02 = Foo()
util.Finalize(d02, conn.send, args=('d02',), exitpriority=0)
d03 = Foo()
util.Finalize(d03, conn.send, args=('d03',), exitpriority=0)
util.Finalize(None, conn.send, args=('e',), exitpriority=-10)
util.Finalize(None, conn.send, args=('STOP',), exitpriority=-100)
# call multiprocessing's cleanup function then exit process without
# garbage collecting locals
util._exit_function()
conn.close()
os._exit(0)
def test_finalize(self):
conn, child_conn = self.Pipe()
p = self.Process(target=self._test_finalize, args=(child_conn,))
p.daemon = True
p.start()
p.join()
result = [obj for obj in iter(conn.recv, 'STOP')]
self.assertEqual(result, ['a', 'b', 'd10', 'd03', 'd02', 'd01', 'e'])
@test.support.cpython_only
def test_thread_safety(self):
# bpo-24484: _run_finalizers() should be thread-safe
def cb():
pass
class Foo(object):
def __init__(self):
self.ref = self # create reference cycle
# insert finalizer at random key
util.Finalize(self, cb, exitpriority=random.randint(1, 100))
finish = False
exc = None
def run_finalizers():
nonlocal exc
while not finish:
time.sleep(random.random() * 1e-1)
try:
# A GC run will eventually happen during this,
# collecting stale Foo's and mutating the registry
util._run_finalizers()
except Exception as e:
exc = e
def make_finalizers():
nonlocal exc
d = {}
while not finish:
try:
# Old Foo's get gradually replaced and later
# collected by the GC (because of the cyclic ref)
d[random.getrandbits(5)] = {Foo() for i in range(10)}
except Exception as e:
exc = e
d.clear()
old_interval = sys.getswitchinterval()
old_threshold = gc.get_threshold()
try:
sys.setswitchinterval(1e-6)
gc.set_threshold(5, 5, 5)
threads = [threading.Thread(target=run_finalizers),
threading.Thread(target=make_finalizers)]
with test.support.start_threads(threads):
time.sleep(4.0) # Wait a bit to trigger race condition
finish = True
if exc is not None:
raise exc
finally:
sys.setswitchinterval(old_interval)
gc.set_threshold(*old_threshold)
gc.collect() # Collect remaining Foo's
#
# Test that from ... import * works for each module
#
class _TestImportStar(unittest.TestCase):
def get_module_names(self):
import glob
folder = os.path.dirname(multiprocessing.__file__)
pattern = os.path.join(folder, '*.py')
files = glob.glob(pattern)
modules = [os.path.splitext(os.path.split(f)[1])[0] for f in files]
modules = ['multiprocessing.' + m for m in modules]
modules.remove('multiprocessing.__init__')
modules.append('multiprocessing')
return modules
def test_import(self):
modules = self.get_module_names()
if sys.platform == 'win32':
modules.remove('multiprocessing.popen_fork')
modules.remove('multiprocessing.popen_forkserver')
modules.remove('multiprocessing.popen_spawn_posix')
else:
modules.remove('multiprocessing.popen_spawn_win32')
if not HAS_REDUCTION:
modules.remove('multiprocessing.popen_forkserver')
if c_int is None:
# This module requires _ctypes
modules.remove('multiprocessing.sharedctypes')
for name in modules:
__import__(name)
mod = sys.modules[name]
self.assertTrue(hasattr(mod, '__all__'), name)
for attr in mod.__all__:
self.assertTrue(
hasattr(mod, attr),
'%r does not have attribute %r' % (mod, attr)
)
#
# Quick test that logging works -- does not test logging output
#
class _TestLogging(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def test_enable_logging(self):
logger = multiprocessing.get_logger()
logger.setLevel(util.SUBWARNING)
self.assertTrue(logger is not None)
logger.debug('this will not be printed')
logger.info('nor will this')
logger.setLevel(LOG_LEVEL)
@classmethod
def _test_level(cls, conn):
logger = multiprocessing.get_logger()
conn.send(logger.getEffectiveLevel())
def test_level(self):
LEVEL1 = 32
LEVEL2 = 37
logger = multiprocessing.get_logger()
root_logger = logging.getLogger()
root_level = root_logger.level
reader, writer = multiprocessing.Pipe(duplex=False)
logger.setLevel(LEVEL1)
p = self.Process(target=self._test_level, args=(writer,))
p.start()
self.assertEqual(LEVEL1, reader.recv())
p.join()
p.close()
logger.setLevel(logging.NOTSET)
root_logger.setLevel(LEVEL2)
p = self.Process(target=self._test_level, args=(writer,))
p.start()
self.assertEqual(LEVEL2, reader.recv())
p.join()
p.close()
root_logger.setLevel(root_level)
logger.setLevel(level=LOG_LEVEL)
# class _TestLoggingProcessName(BaseTestCase):
#
# def handle(self, record):
# assert record.processName == multiprocessing.current_process().name
# self.__handled = True
#
# def test_logging(self):
# handler = logging.Handler()
# handler.handle = self.handle
# self.__handled = False
# # Bypass getLogger() and side-effects
# logger = logging.getLoggerClass()(
# 'multiprocessing.test.TestLoggingProcessName')
# logger.addHandler(handler)
# logger.propagate = False
#
# logger.warn('foo')
# assert self.__handled
#
# Check that Process.join() retries if os.waitpid() fails with EINTR
#
class _TestPollEintr(BaseTestCase):
ALLOWED_TYPES = ('processes',)
@classmethod
def _killer(cls, pid):
time.sleep(0.1)
os.kill(pid, signal.SIGUSR1)
@unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1')
def test_poll_eintr(self):
got_signal = [False]
def record(*args):
got_signal[0] = True
pid = os.getpid()
oldhandler = signal.signal(signal.SIGUSR1, record)
try:
killer = self.Process(target=self._killer, args=(pid,))
killer.start()
try:
p = self.Process(target=time.sleep, args=(2,))
p.start()
p.join()
finally:
killer.join()
self.assertTrue(got_signal[0])
self.assertEqual(p.exitcode, 0)
finally:
signal.signal(signal.SIGUSR1, oldhandler)
#
# Test to verify handle verification, see issue 3321
#
class TestInvalidHandle(unittest.TestCase):
@unittest.skipIf(WIN32, "skipped on Windows")
def test_invalid_handles(self):
conn = multiprocessing.connection.Connection(44977608)
# check that poll() doesn't crash
try:
conn.poll()
except (ValueError, OSError):
pass
finally:
# Hack private attribute _handle to avoid printing an error
# in conn.__del__
conn._handle = None
self.assertRaises((ValueError, OSError),
multiprocessing.connection.Connection, -1)
class OtherTest(unittest.TestCase):
# TODO: add more tests for deliver/answer challenge.
def test_deliver_challenge_auth_failure(self):
class _FakeConnection(object):
def recv_bytes(self, size):
return b'something bogus'
def send_bytes(self, data):
pass
self.assertRaises(multiprocessing.AuthenticationError,
multiprocessing.connection.deliver_challenge,
_FakeConnection(), b'abc')
def test_answer_challenge_auth_failure(self):
class _FakeConnection(object):
def __init__(self):
self.count = 0
def recv_bytes(self, size):
self.count += 1
if self.count == 1:
return multiprocessing.connection.CHALLENGE
elif self.count == 2:
return b'something bogus'
return b''
def send_bytes(self, data):
pass
self.assertRaises(multiprocessing.AuthenticationError,
multiprocessing.connection.answer_challenge,
_FakeConnection(), b'abc')
#
# Test Manager.start()/Pool.__init__() initializer feature - see issue 5585
#
def initializer(ns):
ns.test += 1
class TestInitializers(unittest.TestCase):
def setUp(self):
self.mgr = multiprocessing.Manager()
self.ns = self.mgr.Namespace()
self.ns.test = 0
def tearDown(self):
self.mgr.shutdown()
self.mgr.join()
def test_manager_initializer(self):
m = multiprocessing.managers.SyncManager()
self.assertRaises(TypeError, m.start, 1)
m.start(initializer, (self.ns,))
self.assertEqual(self.ns.test, 1)
m.shutdown()
m.join()
def test_pool_initializer(self):
self.assertRaises(TypeError, multiprocessing.Pool, initializer=1)
p = multiprocessing.Pool(1, initializer, (self.ns,))
p.close()
p.join()
self.assertEqual(self.ns.test, 1)
#
# Issue 5155, 5313, 5331: Test process in processes
# Verifies os.close(sys.stdin.fileno) vs. sys.stdin.close() behavior
#
def _this_sub_process(q):
try:
item = q.get(block=False)
except pyqueue.Empty:
pass
def _test_process():
queue = multiprocessing.Queue()
subProc = multiprocessing.Process(target=_this_sub_process, args=(queue,))
subProc.daemon = True
subProc.start()
subProc.join()
def _afunc(x):
return x*x
def pool_in_process():
pool = multiprocessing.Pool(processes=4)
x = pool.map(_afunc, [1, 2, 3, 4, 5, 6, 7])
pool.close()
pool.join()
class _file_like(object):
def __init__(self, delegate):
self._delegate = delegate
self._pid = None
@property
def cache(self):
pid = os.getpid()
# There are no race conditions since fork keeps only the running thread
if pid != self._pid:
self._pid = pid
self._cache = []
return self._cache
def write(self, data):
self.cache.append(data)
def flush(self):
self._delegate.write(''.join(self.cache))
self._cache = []
class TestStdinBadfiledescriptor(unittest.TestCase):
def test_queue_in_process(self):
proc = multiprocessing.Process(target=_test_process)
proc.start()
proc.join()
def test_pool_in_process(self):
p = multiprocessing.Process(target=pool_in_process)
p.start()
p.join()
def test_flushing(self):
sio = io.StringIO()
flike = _file_like(sio)
flike.write('foo')
proc = multiprocessing.Process(target=lambda: flike.flush())
flike.flush()
assert sio.getvalue() == 'foo'
class TestWait(unittest.TestCase):
@classmethod
def _child_test_wait(cls, w, slow):
for i in range(10):
if slow:
time.sleep(random.random()*0.1)
w.send((i, os.getpid()))
w.close()
def test_wait(self, slow=False):
from multiprocessing.connection import wait
readers = []
procs = []
messages = []
for i in range(4):
r, w = multiprocessing.Pipe(duplex=False)
p = multiprocessing.Process(target=self._child_test_wait, args=(w, slow))
p.daemon = True
p.start()
w.close()
readers.append(r)
procs.append(p)
self.addCleanup(p.join)
while readers:
for r in wait(readers):
try:
msg = r.recv()
except EOFError:
readers.remove(r)
r.close()
else:
messages.append(msg)
messages.sort()
expected = sorted((i, p.pid) for i in range(10) for p in procs)
self.assertEqual(messages, expected)
@classmethod
def _child_test_wait_socket(cls, address, slow):
s = socket.socket()
s.connect(address)
for i in range(10):
if slow:
time.sleep(random.random()*0.1)
s.sendall(('%s\n' % i).encode('ascii'))
s.close()
def test_wait_socket(self, slow=False):
from multiprocessing.connection import wait
l = socket.socket()
l.bind((test.support.HOST, 0))
l.listen()
addr = l.getsockname()
readers = []
procs = []
dic = {}
for i in range(4):
p = multiprocessing.Process(target=self._child_test_wait_socket,
args=(addr, slow))
p.daemon = True
p.start()
procs.append(p)
self.addCleanup(p.join)
for i in range(4):
r, _ = l.accept()
readers.append(r)
dic[r] = []
l.close()
while readers:
for r in wait(readers):
msg = r.recv(32)
if not msg:
readers.remove(r)
r.close()
else:
dic[r].append(msg)
expected = ''.join('%s\n' % i for i in range(10)).encode('ascii')
for v in dic.values():
self.assertEqual(b''.join(v), expected)
def test_wait_slow(self):
self.test_wait(True)
def test_wait_socket_slow(self):
self.test_wait_socket(True)
def test_wait_timeout(self):
from multiprocessing.connection import wait
expected = 5
a, b = multiprocessing.Pipe()
start = time.monotonic()
res = wait([a, b], expected)
delta = time.monotonic() - start
self.assertEqual(res, [])
self.assertLess(delta, expected * 2)
self.assertGreater(delta, expected * 0.5)
b.send(None)
start = time.monotonic()
res = wait([a, b], 20)
delta = time.monotonic() - start
self.assertEqual(res, [a])
self.assertLess(delta, 0.4)
@classmethod
def signal_and_sleep(cls, sem, period):
sem.release()
time.sleep(period)
def test_wait_integer(self):
from multiprocessing.connection import wait
expected = 3
sorted_ = lambda l: sorted(l, key=lambda x: id(x))
sem = multiprocessing.Semaphore(0)
a, b = multiprocessing.Pipe()
p = multiprocessing.Process(target=self.signal_and_sleep,
args=(sem, expected))
p.start()
self.assertIsInstance(p.sentinel, int)
self.assertTrue(sem.acquire(timeout=20))
start = time.monotonic()
res = wait([a, p.sentinel, b], expected + 20)
delta = time.monotonic() - start
self.assertEqual(res, [p.sentinel])
self.assertLess(delta, expected + 2)
self.assertGreater(delta, expected - 2)
a.send(None)
start = time.monotonic()
res = wait([a, p.sentinel, b], 20)
delta = time.monotonic() - start
self.assertEqual(sorted_(res), sorted_([p.sentinel, b]))
self.assertLess(delta, 0.4)
b.send(None)
start = time.monotonic()
res = wait([a, p.sentinel, b], 20)
delta = time.monotonic() - start
self.assertEqual(sorted_(res), sorted_([a, p.sentinel, b]))
self.assertLess(delta, 0.4)
p.terminate()
p.join()
def test_neg_timeout(self):
from multiprocessing.connection import wait
a, b = multiprocessing.Pipe()
t = time.monotonic()
res = wait([a], timeout=-1)
t = time.monotonic() - t
self.assertEqual(res, [])
self.assertLess(t, 1)
a.close()
b.close()
#
# Issue 14151: Test invalid family on invalid environment
#
class TestInvalidFamily(unittest.TestCase):
@unittest.skipIf(WIN32, "skipped on Windows")
def test_invalid_family(self):
with self.assertRaises(ValueError):
multiprocessing.connection.Listener(r'\\.\test')
@unittest.skipUnless(WIN32, "skipped on non-Windows platforms")
def test_invalid_family_win32(self):
with self.assertRaises(ValueError):
multiprocessing.connection.Listener('/var/test.pipe')
#
# Issue 12098: check sys.flags of child matches that for parent
#
class TestFlags(unittest.TestCase):
@classmethod
def run_in_grandchild(cls, conn):
conn.send(tuple(sys.flags))
@classmethod
def run_in_child(cls):
import json
r, w = multiprocessing.Pipe(duplex=False)
p = multiprocessing.Process(target=cls.run_in_grandchild, args=(w,))
p.start()
grandchild_flags = r.recv()
p.join()
r.close()
w.close()
flags = (tuple(sys.flags), grandchild_flags)
print(json.dumps(flags))
def test_flags(self):
import json, subprocess
# start child process using unusual flags
prog = ('from test._test_multiprocessing import TestFlags; ' +
'TestFlags.run_in_child()')
data = subprocess.check_output(
[sys.executable, '-E', '-S', '-O', '-c', prog])
child_flags, grandchild_flags = json.loads(data.decode('ascii'))
self.assertEqual(child_flags, grandchild_flags)
#
# Test interaction with socket timeouts - see Issue #6056
#
class TestTimeouts(unittest.TestCase):
@classmethod
def _test_timeout(cls, child, address):
time.sleep(1)
child.send(123)
child.close()
conn = multiprocessing.connection.Client(address)
conn.send(456)
conn.close()
def test_timeout(self):
old_timeout = socket.getdefaulttimeout()
try:
socket.setdefaulttimeout(0.1)
parent, child = multiprocessing.Pipe(duplex=True)
l = multiprocessing.connection.Listener(family='AF_INET')
p = multiprocessing.Process(target=self._test_timeout,
args=(child, l.address))
p.start()
child.close()
self.assertEqual(parent.recv(), 123)
parent.close()
conn = l.accept()
self.assertEqual(conn.recv(), 456)
conn.close()
l.close()
join_process(p)
finally:
socket.setdefaulttimeout(old_timeout)
#
# Test what happens with no "if __name__ == '__main__'"
#
class TestNoForkBomb(unittest.TestCase):
def test_noforkbomb(self):
sm = multiprocessing.get_start_method()
name = os.path.join(os.path.dirname(__file__), 'mp_fork_bomb.py')
if sm != 'fork':
rc, out, err = test.support.script_helper.assert_python_failure(name, sm)
self.assertEqual(out, b'')
self.assertIn(b'RuntimeError', err)
else:
rc, out, err = test.support.script_helper.assert_python_ok(name, sm)
self.assertEqual(out.rstrip(), b'123')
self.assertEqual(err, b'')
#
# Issue #17555: ForkAwareThreadLock
#
class TestForkAwareThreadLock(unittest.TestCase):
# We recursively start processes. Issue #17555 meant that the
# after fork registry would get duplicate entries for the same
# lock. The size of the registry at generation n was ~2**n.
@classmethod
def child(cls, n, conn):
if n > 1:
p = multiprocessing.Process(target=cls.child, args=(n-1, conn))
p.start()
conn.close()
join_process(p)
else:
conn.send(len(util._afterfork_registry))
conn.close()
def test_lock(self):
r, w = multiprocessing.Pipe(False)
l = util.ForkAwareThreadLock()
old_size = len(util._afterfork_registry)
p = multiprocessing.Process(target=self.child, args=(5, w))
p.start()
w.close()
new_size = r.recv()
join_process(p)
self.assertLessEqual(new_size, old_size)
#
# Check that non-forked child processes do not inherit unneeded fds/handles
#
class TestCloseFds(unittest.TestCase):
def get_high_socket_fd(self):
if WIN32:
# The child process will not have any socket handles, so
# calling socket.fromfd() should produce WSAENOTSOCK even
# if there is a handle of the same number.
return socket.socket().detach()
else:
# We want to produce a socket with an fd high enough that a
# freshly created child process will not have any fds as high.
fd = socket.socket().detach()
to_close = []
while fd < 50:
to_close.append(fd)
fd = os.dup(fd)
for x in to_close:
os.close(x)
return fd
def close(self, fd):
if WIN32:
socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=fd).close()
else:
os.close(fd)
@classmethod
def _test_closefds(cls, conn, fd):
try:
s = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
except Exception as e:
conn.send(e)
else:
s.close()
conn.send(None)
def test_closefd(self):
if not HAS_REDUCTION:
raise unittest.SkipTest('requires fd pickling')
reader, writer = multiprocessing.Pipe()
fd = self.get_high_socket_fd()
try:
p = multiprocessing.Process(target=self._test_closefds,
args=(writer, fd))
p.start()
writer.close()
e = reader.recv()
join_process(p)
finally:
self.close(fd)
writer.close()
reader.close()
if multiprocessing.get_start_method() == 'fork':
self.assertIs(e, None)
else:
WSAENOTSOCK = 10038
self.assertIsInstance(e, OSError)
self.assertTrue(e.errno == errno.EBADF or
e.winerror == WSAENOTSOCK, e)
#
# Issue #17097: EINTR should be ignored by recv(), send(), accept() etc
#
class TestIgnoreEINTR(unittest.TestCase):
# Sending CONN_MAX_SIZE bytes into a multiprocessing pipe must block
CONN_MAX_SIZE = max(support.PIPE_MAX_SIZE, support.SOCK_MAX_SIZE)
@classmethod
def _test_ignore(cls, conn):
def handler(signum, frame):
pass
signal.signal(signal.SIGUSR1, handler)
conn.send('ready')
x = conn.recv()
conn.send(x)
conn.send_bytes(b'x' * cls.CONN_MAX_SIZE)
@unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1')
def test_ignore(self):
conn, child_conn = multiprocessing.Pipe()
try:
p = multiprocessing.Process(target=self._test_ignore,
args=(child_conn,))
p.daemon = True
p.start()
child_conn.close()
self.assertEqual(conn.recv(), 'ready')
time.sleep(0.1)
os.kill(p.pid, signal.SIGUSR1)
time.sleep(0.1)
conn.send(1234)
self.assertEqual(conn.recv(), 1234)
time.sleep(0.1)
os.kill(p.pid, signal.SIGUSR1)
self.assertEqual(conn.recv_bytes(), b'x' * self.CONN_MAX_SIZE)
time.sleep(0.1)
p.join()
finally:
conn.close()
@classmethod
def _test_ignore_listener(cls, conn):
def handler(signum, frame):
pass
signal.signal(signal.SIGUSR1, handler)
with multiprocessing.connection.Listener() as l:
conn.send(l.address)
a = l.accept()
a.send('welcome')
@unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1')
def test_ignore_listener(self):
conn, child_conn = multiprocessing.Pipe()
try:
p = multiprocessing.Process(target=self._test_ignore_listener,
args=(child_conn,))
p.daemon = True
p.start()
child_conn.close()
address = conn.recv()
time.sleep(0.1)
os.kill(p.pid, signal.SIGUSR1)
time.sleep(0.1)
client = multiprocessing.connection.Client(address)
self.assertEqual(client.recv(), 'welcome')
p.join()
finally:
conn.close()
class TestStartMethod(unittest.TestCase):
@classmethod
def _check_context(cls, conn):
conn.send(multiprocessing.get_start_method())
def check_context(self, ctx):
r, w = ctx.Pipe(duplex=False)
p = ctx.Process(target=self._check_context, args=(w,))
p.start()
w.close()
child_method = r.recv()
r.close()
p.join()
self.assertEqual(child_method, ctx.get_start_method())
def test_context(self):
for method in ('fork', 'spawn', 'forkserver'):
try:
ctx = multiprocessing.get_context(method)
except ValueError:
continue
self.assertEqual(ctx.get_start_method(), method)
self.assertIs(ctx.get_context(), ctx)
self.assertRaises(ValueError, ctx.set_start_method, 'spawn')
self.assertRaises(ValueError, ctx.set_start_method, None)
self.check_context(ctx)
def test_set_get(self):
multiprocessing.set_forkserver_preload(PRELOAD)
count = 0
old_method = multiprocessing.get_start_method()
try:
for method in ('fork', 'spawn', 'forkserver'):
try:
multiprocessing.set_start_method(method, force=True)
except ValueError:
continue
self.assertEqual(multiprocessing.get_start_method(), method)
ctx = multiprocessing.get_context()
self.assertEqual(ctx.get_start_method(), method)
self.assertTrue(type(ctx).__name__.lower().startswith(method))
self.assertTrue(
ctx.Process.__name__.lower().startswith(method))
self.check_context(multiprocessing)
count += 1
finally:
multiprocessing.set_start_method(old_method, force=True)
self.assertGreaterEqual(count, 1)
def test_get_all(self):
methods = multiprocessing.get_all_start_methods()
if sys.platform == 'win32':
self.assertEqual(methods, ['spawn'])
else:
self.assertTrue(methods == ['fork', 'spawn'] or
methods == ['fork', 'spawn', 'forkserver'])
def test_preload_resources(self):
if multiprocessing.get_start_method() != 'forkserver':
self.skipTest("test only relevant for 'forkserver' method")
name = os.path.join(os.path.dirname(__file__), 'mp_preload.py')
rc, out, err = test.support.script_helper.assert_python_ok(name)
out = out.decode()
err = err.decode()
if out.rstrip() != 'ok' or err != '':
print(out)
print(err)
self.fail("failed spawning forkserver or grandchild")
@unittest.skipIf(sys.platform == "win32",
"test semantics don't make sense on Windows")
class TestSemaphoreTracker(unittest.TestCase):
def test_semaphore_tracker(self):
#
# Check that killing process does not leak named semaphores
#
import subprocess
cmd = '''if 1:
import multiprocessing as mp, time, os
mp.set_start_method("spawn")
lock1 = mp.Lock()
lock2 = mp.Lock()
os.write(%d, lock1._semlock.name.encode("ascii") + b"\\n")
os.write(%d, lock2._semlock.name.encode("ascii") + b"\\n")
time.sleep(10)
'''
r, w = os.pipe()
p = subprocess.Popen([sys.executable,
'-E', '-c', cmd % (w, w)],
pass_fds=[w],
stderr=subprocess.PIPE)
os.close(w)
with open(r, 'rb', closefd=True) as f:
name1 = f.readline().rstrip().decode('ascii')
name2 = f.readline().rstrip().decode('ascii')
_multiprocessing.sem_unlink(name1)
p.terminate()
p.wait()
time.sleep(2.0)
with self.assertRaises(OSError) as ctx:
_multiprocessing.sem_unlink(name2)
# docs say it should be ENOENT, but OSX seems to give EINVAL
self.assertIn(ctx.exception.errno, (errno.ENOENT, errno.EINVAL))
err = p.stderr.read().decode('utf-8')
p.stderr.close()
expected = 'semaphore_tracker: There appear to be 2 leaked semaphores'
self.assertRegex(err, expected)
self.assertRegex(err, r'semaphore_tracker: %r: \[Errno' % name1)
def check_semaphore_tracker_death(self, signum, should_die):
# bpo-31310: if the semaphore tracker process has died, it should
# be restarted implicitly.
from multiprocessing.semaphore_tracker import _semaphore_tracker
_semaphore_tracker.ensure_running()
pid = _semaphore_tracker._pid
os.kill(pid, signum)
time.sleep(1.0) # give it time to die
ctx = multiprocessing.get_context("spawn")
with contextlib.ExitStack() as stack:
if should_die:
stack.enter_context(self.assertWarnsRegex(
UserWarning,
"semaphore_tracker: process died"))
sem = ctx.Semaphore()
sem.acquire()
sem.release()
wr = weakref.ref(sem)
# ensure `sem` gets collected, which triggers communication with
# the semaphore tracker
del sem
gc.collect()
self.assertIsNone(wr())
def test_semaphore_tracker_sigint(self):
# Catchable signal (ignored by semaphore tracker)
self.check_semaphore_tracker_death(signal.SIGINT, False)
def test_semaphore_tracker_sigkill(self):
# Uncatchable signal.
self.check_semaphore_tracker_death(signal.SIGKILL, True)
class TestSimpleQueue(unittest.TestCase):
@classmethod
def _test_empty(cls, queue, child_can_start, parent_can_continue):
child_can_start.wait()
# issue 30301, could fail under spawn and forkserver
try:
queue.put(queue.empty())
queue.put(queue.empty())
finally:
parent_can_continue.set()
def test_empty(self):
queue = multiprocessing.SimpleQueue()
child_can_start = multiprocessing.Event()
parent_can_continue = multiprocessing.Event()
proc = multiprocessing.Process(
target=self._test_empty,
args=(queue, child_can_start, parent_can_continue)
)
proc.daemon = True
proc.start()
self.assertTrue(queue.empty())
child_can_start.set()
parent_can_continue.wait()
self.assertFalse(queue.empty())
self.assertEqual(queue.get(), True)
self.assertEqual(queue.get(), False)
self.assertTrue(queue.empty())
proc.join()
class TestSyncManagerTypes(unittest.TestCase):
"""Test all the types which can be shared between a parent and a
child process by using a manager which acts as an intermediary
between them.
In the following unit-tests the base type is created in the parent
process, the @classmethod represents the worker process and the
shared object is readable and editable between the two.
# The child.
@classmethod
def _test_list(cls, obj):
assert obj[0] == 5
assert obj.append(6)
# The parent.
def test_list(self):
o = self.manager.list()
o.append(5)
self.run_worker(self._test_list, o)
assert o[1] == 6
"""
manager_class = multiprocessing.managers.SyncManager
def setUp(self):
self.manager = self.manager_class()
self.manager.start()
self.proc = None
def tearDown(self):
if self.proc is not None and self.proc.is_alive():
self.proc.terminate()
self.proc.join()
self.manager.shutdown()
self.manager = None
self.proc = None
@classmethod
def setUpClass(cls):
support.reap_children()
tearDownClass = setUpClass
def wait_proc_exit(self):
# Only the manager process should be returned by active_children()
# but this can take a bit on slow machines, so wait a few seconds
# if there are other children too (see #17395).
join_process(self.proc)
start_time = time.monotonic()
t = 0.01
while len(multiprocessing.active_children()) > 1:
time.sleep(t)
t *= 2
dt = time.monotonic() - start_time
if dt >= 5.0:
test.support.environment_altered = True
print("Warning -- multiprocessing.Manager still has %s active "
"children after %s seconds"
% (multiprocessing.active_children(), dt),
file=sys.stderr)
break
def run_worker(self, worker, obj):
self.proc = multiprocessing.Process(target=worker, args=(obj, ))
self.proc.daemon = True
self.proc.start()
self.wait_proc_exit()
self.assertEqual(self.proc.exitcode, 0)
@classmethod
def _test_queue(cls, obj):
assert obj.qsize() == 2
assert obj.full()
assert not obj.empty()
assert obj.get() == 5
assert not obj.empty()
assert obj.get() == 6
assert obj.empty()
def test_queue(self, qname="Queue"):
o = getattr(self.manager, qname)(2)
o.put(5)
o.put(6)
self.run_worker(self._test_queue, o)
assert o.empty()
assert not o.full()
def test_joinable_queue(self):
self.test_queue("JoinableQueue")
@classmethod
def _test_event(cls, obj):
assert obj.is_set()
obj.wait()
obj.clear()
obj.wait(0.001)
def test_event(self):
o = self.manager.Event()
o.set()
self.run_worker(self._test_event, o)
assert not o.is_set()
o.wait(0.001)
@classmethod
def _test_lock(cls, obj):
obj.acquire()
def test_lock(self, lname="Lock"):
o = getattr(self.manager, lname)()
self.run_worker(self._test_lock, o)
o.release()
self.assertRaises(RuntimeError, o.release) # already released
@classmethod
def _test_rlock(cls, obj):
obj.acquire()
obj.release()
def test_rlock(self, lname="Lock"):
o = getattr(self.manager, lname)()
self.run_worker(self._test_rlock, o)
@classmethod
def _test_semaphore(cls, obj):
obj.acquire()
def test_semaphore(self, sname="Semaphore"):
o = getattr(self.manager, sname)()
self.run_worker(self._test_semaphore, o)
o.release()
def test_bounded_semaphore(self):
self.test_semaphore(sname="BoundedSemaphore")
@classmethod
def _test_condition(cls, obj):
obj.acquire()
obj.release()
def test_condition(self):
o = self.manager.Condition()
self.run_worker(self._test_condition, o)
@classmethod
def _test_barrier(cls, obj):
assert obj.parties == 5
obj.reset()
def test_barrier(self):
o = self.manager.Barrier(5)
self.run_worker(self._test_barrier, o)
@classmethod
def _test_pool(cls, obj):
# TODO: fix https://bugs.python.org/issue35919
with obj:
pass
def test_pool(self):
o = self.manager.Pool(processes=4)
self.run_worker(self._test_pool, o)
@classmethod
def _test_list(cls, obj):
assert obj[0] == 5
assert obj.count(5) == 1
assert obj.index(5) == 0
obj.sort()
obj.reverse()
for x in obj:
pass
assert len(obj) == 1
assert obj.pop(0) == 5
def test_list(self):
o = self.manager.list()
o.append(5)
self.run_worker(self._test_list, o)
assert not o
self.assertEqual(len(o), 0)
@classmethod
def _test_dict(cls, obj):
assert len(obj) == 1
assert obj['foo'] == 5
assert obj.get('foo') == 5
assert list(obj.items()) == [('foo', 5)]
assert list(obj.keys()) == ['foo']
assert list(obj.values()) == [5]
assert obj.copy() == {'foo': 5}
assert obj.popitem() == ('foo', 5)
def test_dict(self):
o = self.manager.dict()
o['foo'] = 5
self.run_worker(self._test_dict, o)
assert not o
self.assertEqual(len(o), 0)
@classmethod
def _test_value(cls, obj):
assert obj.value == 1
assert obj.get() == 1
obj.set(2)
def test_value(self):
o = self.manager.Value('i', 1)
self.run_worker(self._test_value, o)
self.assertEqual(o.value, 2)
self.assertEqual(o.get(), 2)
@classmethod
def _test_array(cls, obj):
assert obj[0] == 0
assert obj[1] == 1
assert len(obj) == 2
assert list(obj) == [0, 1]
def test_array(self):
o = self.manager.Array('i', [0, 1])
self.run_worker(self._test_array, o)
@classmethod
def _test_namespace(cls, obj):
assert obj.x == 0
assert obj.y == 1
def test_namespace(self):
o = self.manager.Namespace()
o.x = 0
o.y = 1
self.run_worker(self._test_namespace, o)
#
# Mixins
#
class BaseMixin(object):
@classmethod
def setUpClass(cls):
cls.dangling = (multiprocessing.process._dangling.copy(),
threading._dangling.copy())
@classmethod
def tearDownClass(cls):
# bpo-26762: Some multiprocessing objects like Pool create reference
# cycles. Trigger a garbage collection to break these cycles.
test.support.gc_collect()
processes = set(multiprocessing.process._dangling) - set(cls.dangling[0])
if processes:
test.support.environment_altered = True
print('Warning -- Dangling processes: %s' % processes,
file=sys.stderr)
processes = None
threads = set(threading._dangling) - set(cls.dangling[1])
if threads:
test.support.environment_altered = True
print('Warning -- Dangling threads: %s' % threads,
file=sys.stderr)
threads = None
class ProcessesMixin(BaseMixin):
TYPE = 'processes'
Process = multiprocessing.Process
connection = multiprocessing.connection
current_process = staticmethod(multiprocessing.current_process)
active_children = staticmethod(multiprocessing.active_children)
Pool = staticmethod(multiprocessing.Pool)
Pipe = staticmethod(multiprocessing.Pipe)
Queue = staticmethod(multiprocessing.Queue)
JoinableQueue = staticmethod(multiprocessing.JoinableQueue)
Lock = staticmethod(multiprocessing.Lock)
RLock = staticmethod(multiprocessing.RLock)
Semaphore = staticmethod(multiprocessing.Semaphore)
BoundedSemaphore = staticmethod(multiprocessing.BoundedSemaphore)
Condition = staticmethod(multiprocessing.Condition)
Event = staticmethod(multiprocessing.Event)
Barrier = staticmethod(multiprocessing.Barrier)
Value = staticmethod(multiprocessing.Value)
Array = staticmethod(multiprocessing.Array)
RawValue = staticmethod(multiprocessing.RawValue)
RawArray = staticmethod(multiprocessing.RawArray)
class ManagerMixin(BaseMixin):
TYPE = 'manager'
Process = multiprocessing.Process
Queue = property(operator.attrgetter('manager.Queue'))
JoinableQueue = property(operator.attrgetter('manager.JoinableQueue'))
Lock = property(operator.attrgetter('manager.Lock'))
RLock = property(operator.attrgetter('manager.RLock'))
Semaphore = property(operator.attrgetter('manager.Semaphore'))
BoundedSemaphore = property(operator.attrgetter('manager.BoundedSemaphore'))
Condition = property(operator.attrgetter('manager.Condition'))
Event = property(operator.attrgetter('manager.Event'))
Barrier = property(operator.attrgetter('manager.Barrier'))
Value = property(operator.attrgetter('manager.Value'))
Array = property(operator.attrgetter('manager.Array'))
list = property(operator.attrgetter('manager.list'))
dict = property(operator.attrgetter('manager.dict'))
Namespace = property(operator.attrgetter('manager.Namespace'))
@classmethod
def Pool(cls, *args, **kwds):
return cls.manager.Pool(*args, **kwds)
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.manager = multiprocessing.Manager()
@classmethod
def tearDownClass(cls):
# only the manager process should be returned by active_children()
# but this can take a bit on slow machines, so wait a few seconds
# if there are other children too (see #17395)
start_time = time.monotonic()
t = 0.01
while len(multiprocessing.active_children()) > 1:
time.sleep(t)
t *= 2
dt = time.monotonic() - start_time
if dt >= 5.0:
test.support.environment_altered = True
print("Warning -- multiprocessing.Manager still has %s active "
"children after %s seconds"
% (multiprocessing.active_children(), dt),
file=sys.stderr)
break
gc.collect() # do garbage collection
if cls.manager._number_of_objects() != 0:
# This is not really an error since some tests do not
# ensure that all processes which hold a reference to a
# managed object have been joined.
test.support.environment_altered = True
print('Warning -- Shared objects which still exist at manager '
'shutdown:')
print(cls.manager._debug_info())
cls.manager.shutdown()
cls.manager.join()
cls.manager = None
super().tearDownClass()
class ThreadsMixin(BaseMixin):
TYPE = 'threads'
Process = multiprocessing.dummy.Process
connection = multiprocessing.dummy.connection
current_process = staticmethod(multiprocessing.dummy.current_process)
active_children = staticmethod(multiprocessing.dummy.active_children)
Pool = staticmethod(multiprocessing.dummy.Pool)
Pipe = staticmethod(multiprocessing.dummy.Pipe)
Queue = staticmethod(multiprocessing.dummy.Queue)
JoinableQueue = staticmethod(multiprocessing.dummy.JoinableQueue)
Lock = staticmethod(multiprocessing.dummy.Lock)
RLock = staticmethod(multiprocessing.dummy.RLock)
Semaphore = staticmethod(multiprocessing.dummy.Semaphore)
BoundedSemaphore = staticmethod(multiprocessing.dummy.BoundedSemaphore)
Condition = staticmethod(multiprocessing.dummy.Condition)
Event = staticmethod(multiprocessing.dummy.Event)
Barrier = staticmethod(multiprocessing.dummy.Barrier)
Value = staticmethod(multiprocessing.dummy.Value)
Array = staticmethod(multiprocessing.dummy.Array)
#
# Functions used to create test cases from the base ones in this module
#
def install_tests_in_module_dict(remote_globs, start_method):
__module__ = remote_globs['__name__']
local_globs = globals()
ALL_TYPES = {'processes', 'threads', 'manager'}
for name, base in local_globs.items():
if not isinstance(base, type):
continue
if issubclass(base, BaseTestCase):
if base is BaseTestCase:
continue
assert set(base.ALLOWED_TYPES) <= ALL_TYPES, base.ALLOWED_TYPES
for type_ in base.ALLOWED_TYPES:
newname = 'With' + type_.capitalize() + name[1:]
Mixin = local_globs[type_.capitalize() + 'Mixin']
class Temp(base, Mixin, unittest.TestCase):
pass
Temp.__name__ = Temp.__qualname__ = newname
Temp.__module__ = __module__
remote_globs[newname] = Temp
elif issubclass(base, unittest.TestCase):
class Temp(base, object):
pass
Temp.__name__ = Temp.__qualname__ = name
Temp.__module__ = __module__
remote_globs[name] = Temp
dangling = [None, None]
old_start_method = [None]
def setUpModule():
multiprocessing.set_forkserver_preload(PRELOAD)
multiprocessing.process._cleanup()
dangling[0] = multiprocessing.process._dangling.copy()
dangling[1] = threading._dangling.copy()
old_start_method[0] = multiprocessing.get_start_method(allow_none=True)
try:
multiprocessing.set_start_method(start_method, force=True)
except ValueError:
raise unittest.SkipTest(start_method +
' start method not supported')
if sys.platform.startswith("linux"):
try:
lock = multiprocessing.RLock()
except OSError:
raise unittest.SkipTest("OSError raises on RLock creation, "
"see issue 3111!")
check_enough_semaphores()
util.get_temp_dir() # creates temp directory
multiprocessing.get_logger().setLevel(LOG_LEVEL)
def tearDownModule():
need_sleep = False
# bpo-26762: Some multiprocessing objects like Pool create reference
# cycles. Trigger a garbage collection to break these cycles.
test.support.gc_collect()
multiprocessing.set_start_method(old_start_method[0], force=True)
# pause a bit so we don't get warning about dangling threads/processes
processes = set(multiprocessing.process._dangling) - set(dangling[0])
if processes:
need_sleep = True
test.support.environment_altered = True
print('Warning -- Dangling processes: %s' % processes,
file=sys.stderr)
processes = None
threads = set(threading._dangling) - set(dangling[1])
if threads:
need_sleep = True
test.support.environment_altered = True
print('Warning -- Dangling threads: %s' % threads,
file=sys.stderr)
threads = None
# Sleep 500 ms to give time to child processes to complete.
if need_sleep:
time.sleep(0.5)
multiprocessing.util._cleanup_tests()
remote_globs['setUpModule'] = setUpModule
remote_globs['tearDownModule'] = tearDownModule
|
ca.py | import os
import socket
import threading
from base64 import b64encode
import functions
# *******************GENERATE CA RSA KEYS********************
p = functions.pstart("Generating RSA keys", 0.2)
public, private = functions.newkeys(1024)
ca_keys = functions.keys(public, private) # as RSA Object
directory = os.path.join(os.getcwd(), 'CA')
if not os.path.exists(directory):
os.makedirs(directory)
os.makedirs(os.path.join(directory, "clients"))
functions.file(directory, ca_keys.public.exportKey("PEM")).write("public_key.PEM") # Write client public key to file
functions.file(directory, ca_keys.private.exportKey("PEM")).write("private_key.PEM") # Write client private key to file
functions.pstop(p, 1.5)
print(functions.bcolors.OKGREEN + "[+] RSA Keys Generated Successfully" + functions.bcolors.ENDC)
# ****************************************************************
class ThreadedServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
self.p = None
def listen(self):
p = functions.pstart("Waiting For Clients", 0.2)
self.sock.listen(5)
try:
while True:
client, address = self.sock.accept()
functions.pstop(p, 0)
client.settimeout(60)
threading.Thread(target=self.listenToClient, args=(client, address)).start()
p = functions.pstart("Waiting For Clients", 0.2)
except KeyboardInterrupt:
p.terminate()
print(functions.bcolors.FAIL + "\nKeyboard Interrupt Pressed" + functions.bcolors.ENDC)
exit(0)
def listenToClient(self, client, address):
size = 1024
data = client.recv(size)
name = data
data = client.recv(size)
pub = data
functions.clean()
print(functions.bcolors.OKGREEN + "[+] User " + name.decode("utf-8") + " Connected" + functions.bcolors.ENDC)
if name:
dir = os.path.join(directory, "clients")
functions.file(dir, pub).write(name.decode("utf-8") + ".PEM")
sign = b64encode(functions.sign(pub, private))
client.send(sign)
functions.wait()
client.send(ca_keys.public.exportKey("PEM"))
functions.clean()
print(functions.bcolors.OKGREEN + " Certificate Sent Successfully" + functions.bcolors.ENDC)
else:
print(functions.bcolors.WARNING + "[-] Client disconnected" + functions.bcolors.ENDC)
client.close()
return False
def terminate(self):
p.terminate()
if __name__ == "__main__":
while True:
port_num = 1104
try:
port_num = int(port_num)
break
except ValueError:
pass
T = ThreadedServer('', port_num)
try:
T.listen()
except KeyboardInterrupt:
p.terminate()
T.terminate()
print(functions.bcolors.FAIL + "\nKeyboard Interrupt Pressed" + functions.bcolors.ENDC)
exit(0)
|
test_http_client.py | #! /usr/bin/env python
import errno
import io
import logging
import os.path
import select
import shutil
import socket
import threading
import time
import random
import unittest
from tempfile import mkdtemp
import pyslet.http.client as http
import pyslet.http.messages as messages
import pyslet.http.params as params
import pyslet.http.server as server
import pyslet.rfc2396 as uri
from pyslet.py2 import range3
from pyslet.streams import Pipe, io_timedout
from test_http_server import MockSocketBase, MockTime
TEST_DATA_DIR = os.path.join(
os.path.split(os.path.abspath(__file__))[0], 'data_rfc2616')
TEST_STRING = b"The quick brown fox jumped over the lazy dog"
TEST_BODY = b"123456\r\n\r\n"
def suite():
return unittest.TestSuite((
unittest.makeSuite(ClientTests, 'test'),
unittest.makeSuite(LegacyServerTests, 'test'),
unittest.makeSuite(ClientRequestTests, 'test'),
# unittest.makeSuite(SecureTests, 'test')
))
class MockSocket(MockSocketBase):
"""Mocks the socket for the client"""
def __init__(self, connection, allow_continue=True, close_on_417=False):
super(MockSocket, self).__init__()
self.allow_continue = allow_continue
self.close_on_417 = close_on_417
# start a thread to mock the server side of the connection
t = threading.Thread(target=connection.manager.mock_server,
args=(connection.host, connection.port, self))
t.start()
def recv_request(self):
while True:
responded = False
request = messages.Request()
request.start_receiving()
check_continue = False
try:
while True:
if check_continue and request.get_expect_continue():
# push an expect response
if self.allow_continue:
logging.debug("Sending 100 Continue")
self.send_continue()
else:
logging.debug("Sending 417 Expectation Failed")
self.send_expectation_failed()
if self.close_on_417:
# we're not sending any more data, hangup
self.mock_shutdown(socket.SHUT_RDWR)
return None
else:
# wait for the next request
responded = True
check_continue = False
mode = request.recv_mode()
if mode == messages.Message.RECV_LINE:
line = self.send_pipe.readmatch()
if line == b'':
if request.method is None:
# EOF, no more requests
return None
else:
# EOF, unexpected
raise messages.HTTPException(
"Unexpected EOF in mock socket")
request.recv(line)
elif mode == messages.Message.RECV_HEADERS:
lines = []
last_line = b''
while last_line != b'\r\n':
last_line = self.send_pipe.readmatch()
lines.append(last_line)
request.recv(lines)
check_continue = True
elif mode is None:
break
elif mode > 0:
data = self.send_pipe.read(mode)
if data == b'':
# EOF, unexpected
raise messages.HTTPException(
"Unexpected EOF in mock socket")
else:
request.recv(data)
elif mode == messages.Message.RECV_ALL:
data = self.send_pipe.read()
if data == b'':
# EOF, expected
break
else:
request.recv(data)
else:
raise ValueError("unexpected recv_mode!")
except IOError as e:
if io_timedout(e):
logging.debug(
"mock socket timed out while reading request")
responded = False
request = None
else:
raise
if responded:
continue
else:
return request
def send_continue(self):
self.recv_pipe.write(b"HTTP/1.1 100 Go on then!\r\n\r\n")
def send_expectation_failed(self):
self.recv_pipe.write(
b"HTTP/1.1 417 Expectation Failed\r\n"
b"Content-Length: 0\r\n")
if self.close_on_417:
self.recv_pipe.write(b"Connection: close\r\n")
self.recv_pipe.write(b"\r\n")
def send_response(self, response):
try:
response.start_sending()
self.recv_pipe.write(response.send_start())
self.recv_pipe.write(response.send_header())
while True:
data = response.send_body()
if data:
self.recv_pipe.write(data)
else:
break
except IOError as e:
logging.debug("mock socket error while sending response: %s",
str(e))
except Exception as e:
import traceback
traceback.print_exc()
raise
class MockSocketNoContinue(MockSocket):
def __init__(self, connection):
super(MockSocketNoContinue, self).__init__(connection,
allow_continue=False)
class MockSocketNoContinueClose(MockSocket):
def __init__(self, connection):
super(MockSocketNoContinueClose, self).__init__(
connection, allow_continue=False, close_on_417=True)
class MockConnectionWrapper(http.Connection):
SocketClass = MockSocket
def new_socket(self):
# turn the timeout down nice and low
self.timeout = 10
with self.lock:
if self.closed:
logging.error(
"new_socket called on dead connection to %s", self.host)
raise messages.HTTPException("Connection closed")
self.socket = None
self.socket_file = None
self.socketSelect = select.select
else:
logging.info("Opening connection to %s...", self.host)
self.socket = self.SocketClass(self)
self.socket_file = self.socket
self.socket.setblocking(False)
self.socketSelect = self.SocketClass.wrap_select
class MockConnectionWrapperNoContinue(MockConnectionWrapper):
SocketClass = MockSocketNoContinue
class MockConnectionWrapperNoContinueClose(MockConnectionWrapper):
SocketClass = MockSocketNoContinueClose
class MockClientWrapper(http.Client):
ConnectionClass = MockConnectionWrapper
def __init__(self, mock_server, **kwargs):
http.Client.__init__(self, **kwargs)
self.socketSelect = self.ConnectionClass.SocketClass.wrap_select
self.mock_server = mock_server
class ClientRequestTests(unittest.TestCase):
def setUp(self): # noqa
global time
self.save_time = http.time
http.time = MockTime
def tearDown(self): # noqa
global time
http.time = self.save_time
MockTime.now = time.time()
def test_retries(self):
request = http.ClientRequest("http://www.domain1.com/", max_retries=10,
min_retry_time=4)
self.assertTrue(request.max_retries == 10)
self.assertTrue(request.nretries == 0)
self.assertTrue(request.retry_time == 0)
MockTime.now = 10.0
ranges = [
(10.0, 10.0), # 10+0 +-0
(13.0, 15.0), # 10+4 +-1
(13.0, 15.0), # 10+4 +-1
(16.0, 20.0), # 10+8 +-2
(19.0, 25.0), # 10+12 +-3
(25.0, 35.0), # 10+20 +-5
(34.0, 50.0), # 10+32 +-8
(49.0, 75.0), # 10+52 +-13
(73.0, 115.0), # 10+84 +-21
(112.0, 180.0)] # 10+136 +-34
for i in range3(10):
# simulate a failed send
request.connect(None, 0)
request.disconnect(1)
self.assertTrue(request.can_retry(), "retry %ith time" % i)
self.assertTrue(request.retry_time >= ranges[i][0],
"%f too small in pair %i" %
(request.retry_time, i))
self.assertTrue(request.retry_time <= ranges[i][1],
"%f too large in pair %i" %
(request.retry_time, i))
class ClientTests(unittest.TestCase):
def setUp(self): # noqa
self.client = MockClientWrapper(self.run_manager, max_connections=3)
self.client.httpUserAgent = None
self.unreliable = True
self.error_count = 2
def tearDown(self): # noqa
self.client.close()
def test_simple(self):
"""simple tests
RFC 2616:
If the abs_path is not present in the URL, it MUST be given
as "/" when used as a Request-URI for a resource"""
request = http.ClientRequest("http://www.example.com/")
request.start_sending()
request_line = request.send_start()
self.assertTrue(request_line.startswith(b"GET / HTTP/1."),
request_line)
def run_domain1(self, sock):
while True:
req = sock.recv_request()
if req is None:
break
if req.method == "GET":
response = messages.Response(req, entity_body=TEST_STRING)
response.set_status(200, "You got it!")
elif req.method == "HEAD":
response = messages.Response(req)
response.set_content_length(len(TEST_STRING))
response.set_status(200, "You got it!")
elif req.method == "PUT":
# check the request body
response = messages.Response(req, entity_body=b'')
if req.entity_body.getvalue() != TEST_BODY:
response.set_status(400, "PUT failed for domain1")
logging.debug("run_domain1: PUT %s" %
repr(req.entity_body.getvalue()))
else:
response.set_status(200)
else:
response = messages.Response(req)
response.set_status(400, "Test failed for domain1")
sock.send_response(response)
def run_domain2(self, sock):
while True:
req = sock.recv_request()
if req is None:
break
if req.method == "GET":
response = messages.Response(req, entity_body=b"Not here")
response.set_status(301, "Moved")
response.set_location("http://www.domain1.com/")
elif req.method == "HEAD":
response = messages.Response(req, entity_body=None)
response.set_status(301, "Moved")
response.set_location("http://www.domain1.com/")
else:
response = messages.Response(req)
response.set_status(400, "Test failed for domain2")
sock.send_response(response)
def run_domain5(self, sock):
while True:
req = sock.recv_request()
if req is None:
break
if self.unreliable:
self.unreliable = False
# shutdown the socket
logging.debug("Server hang-up after reading request")
sock.mock_shutdown(socket.SHUT_RDWR)
break
if req.method == "GET":
response = messages.Response(req, entity_body=TEST_STRING)
response.set_status(200, "Thanks for your patience")
elif req.method == "HEAD":
response = messages.Response(req)
response.set_content_length(len(TEST_STRING))
response.set_status(200, "Thanks for your patience")
elif req.method == "POST":
response = messages.Response(req, entity_body=TEST_STRING)
response.set_content_length(len(TEST_STRING))
response.set_status(200, "Thanks for your patience")
else:
response = messages.Response(req)
response.set_status(400, "Test failed for domain5")
sock.send_response(response)
def run_domain6(self, sock):
while True:
# shutdown the socket
logging.debug("Server hang-up before reading request")
sock.mock_shutdown(socket.SHUT_RDWR)
break
def run_domain7(self, sock):
while True:
if self.error_count > 1:
# generate an error on the socket for the client
sock.io_error = socket.error(errno.EINTR,
os.strerror(errno.EINTR))
self.error_count -= 1
break
elif self.error_count:
req = sock.recv_request()
if req is None:
break
sock.io_error = socket.error(errno.EINTR,
os.strerror(errno.EINTR))
self.error_count -= 1
sock.close()
break
else:
req = sock.recv_request()
if req is None:
break
response = messages.Response(req, entity_body=TEST_STRING)
response.set_status(200, "Thanks for your patience")
sock.send_response(response)
def run_domain8(self, sock):
while True:
# simulates a server with a short fuse, shuts down
# the socket after a single request
req = sock.recv_request()
if req is None:
break
if req.method == "GET":
response = messages.Response(req, entity_body=TEST_STRING)
response.set_status(200, "Success")
elif req.method == "HEAD":
response = messages.Response(req)
response.set_content_length(len(TEST_STRING))
response.set_status(200, "Success")
elif req.method == "POST":
response = messages.Response(req)
response.set_status(200, "Success")
else:
response = messages.Response(req)
response.set_status(400, "Test failed for domain8")
sock.send_response(response)
logging.debug("Server hang-up after 0s idle time")
sock.mock_shutdown(socket.SHUT_RDWR)
break
def run_domain9(self, sock):
while True:
# simulates a server that supports upgrade to happy
req = sock.recv_request()
if req is None:
break
connection = req.get_connection()
if "upgrade" in connection:
response = messages.Response(req)
response.set_status(101)
response.set_upgrade([params.ProductToken("happy")])
sock.send_response(response)
logging.debug("Switching to happy protocol")
input = sock.send_pipe.readmatch()
sock.recv_pipe.write(input)
sock.recv_pipe.write_eof()
else:
response = messages.Response(req)
response.set_status(400, "Test failed for domain9")
sock.send_response(response)
sock.mock_shutdown(socket.SHUT_RDWR)
break
def run_manager(self, host, port, sock):
# read some data from sock, and post a response
logging.debug('run_manager: %s, %i' % (host, port))
if host == "www.domain1.com" and port == 80:
self.run_domain1(sock)
elif host == "www.domain2.com" and port == 80:
self.run_domain2(sock)
elif host == "www.domain3.com" and port == 80:
# just a copy of domain1
self.run_domain1(sock)
elif host == "www.domain4.com" and port == 80:
# just a copy of domain1
self.run_domain1(sock)
elif host == "www.domain5.com" and port == 80:
self.run_domain5(sock)
elif host == "www.domain6.com" and port == 80:
self.run_domain6(sock)
elif host == "www.domain7.com" and port == 80:
self.run_domain7(sock)
elif host == "www.domain8.com" and port == 80:
self.run_domain8(sock)
elif host == "www.domain9.com" and port == 80:
self.run_domain9(sock)
else:
# connection error
raise ValueError("run_manager: bad host in connect")
def test_manager(self):
request1 = http.ClientRequest("http://www.domain1.com/")
self.assertTrue(request1.method == "GET")
request2 = http.ClientRequest("http://www.domain2.com/", "HEAD")
self.assertTrue(request2.method == "HEAD")
self.client.queue_request(request1)
self.client.queue_request(request2)
# thread_loop will process the queue until it blocks for more
# than the timeout (default, 60s)
self.client.thread_loop(timeout=5)
response1 = request1.response
self.assertTrue(
str(response1.protocol) == "HTTP/1.1",
"Protocol in response1: %s" % response1.protocol)
self.assertTrue(
response1.status == 200,
"Status in response1: %i" %
response1.status)
self.assertTrue(response1.reason == "You got it!",
"Reason in response1: %s" % response1.reason)
self.assertTrue(
request1.res_body == TEST_STRING,
"Data in response1: %s" %
request1.res_body)
response2 = request2.response
self.assertTrue(
str(response2.protocol) == "HTTP/1.1",
"Protocol in response2: %s" % response2.protocol)
self.assertTrue(
response2.status == 200,
"Status in response2: %i" %
response2.status)
self.assertTrue(response2.reason == "You got it!",
"Reason in response2: %s" % response2.reason)
self.assertTrue(request2.res_body == b"",
"Data in response2: %s" % request2.res_body)
def test_redirect(self):
request = http.ClientRequest("http://www.domain2.com/")
self.client.queue_request(request)
self.client.thread_loop(timeout=5)
response = request.response
self.assertTrue(
str(response.protocol) == "HTTP/1.1",
"Protocol in response1: %s" % response.protocol)
self.assertTrue(
response.status == 200,
"Status in response: %i" %
response.status)
self.assertTrue(response.reason == "You got it!",
"Reason in response: %s" % response.reason)
self.assertTrue(
request.res_body == TEST_STRING,
"Data in response: %s" %
repr(request.res_body))
def test_continue(self):
"""RFC2616:
If a client will wait for a 100 (Continue) response before
sending the request body, it MUST send an Expect
request-header field with the "100-continue" expectation."""
request1 = http.ClientRequest(
"http://www.domain1.com/file", method="PUT",
entity_body=TEST_BODY)
self.assertTrue(request1.method == "PUT")
request2 = http.ClientRequest(
"http://www.domain1.com/file2", method="PUT",
entity_body=TEST_BODY)
request2.set_expect_continue()
self.client.queue_request(request1)
self.assertTrue(request1.get_header('Expect') is None)
self.client.queue_request(request2)
self.assertTrue(request2.get_header('Expect') == b"100-continue")
# thread_loop will process the queue until it blocks for more
# than the timeout (default, forever)
self.client.thread_loop(timeout=5)
response1 = request1.response
self.assertTrue(
response1.status == 200,
"Status in response1: %i" %
response1.status)
self.assertTrue(
response1.reason == "OK",
"Reason in response1: %s" %
response1.reason)
self.assertTrue(request1.res_body == b'',
"Data in response1: %s" % request1.res_body)
response2 = request2.response
self.assertTrue(
response2.status == 200,
"Status in response2: %i" %
response2.status)
self.assertTrue(
response2.reason == "OK",
"Reason in response2: %s" %
response2.reason)
self.assertTrue(request2.res_body == b"",
"Data in response2: %s" % request2.res_body)
# How do we test that response2 held back from sending the data before
# the redirect?
def test_expectation_failed(self):
"""RFC7231
A client that receives a 417 (Expectation Failed) status code in
response to a request containing a 100-continue expectation
SHOULD repeat that request without a 100-continue expectation
Try this using the same connection (aborted send)"""
# fix up the mock client to force a 417 response
self.client.ConnectionClass = MockConnectionWrapperNoContinue
request1 = http.ClientRequest(
"http://www.domain1.com/file", method="PUT",
entity_body=TEST_BODY)
request1.set_expect_continue()
self.client.queue_request(request1)
self.client.thread_loop(timeout=5)
response1 = request1.response
self.assertTrue(
response1.status == 200,
"Status in response1: %i" %
response1.status)
self.assertTrue(
response1.reason == "OK",
"Reason in response1: %s" %
response1.reason)
self.assertTrue(request1.res_body == b'',
"Data in response1: %s" % request1.res_body)
def test_expectation_failed_reconnect(self):
"""RFC7231
A client that receives a 417 (Expectation Failed) status code in
response to a request containing a 100-continue expectation
SHOULD repeat that request without a 100-continue expectation
Try this using a new connection after server indicates closing"""
# fix up the mock client to force a 417 response
self.client.ConnectionClass = MockConnectionWrapperNoContinueClose
request1 = http.ClientRequest(
"http://www.domain1.com/file", method="PUT",
entity_body=TEST_BODY)
request1.set_expect_continue()
self.client.queue_request(request1)
self.client.thread_loop(timeout=5)
response1 = request1.response
self.assertTrue(
response1.status == 200,
"Status in response1: %i" %
response1.status)
self.assertTrue(
response1.reason == "OK",
"Reason in response1: %s" %
response1.reason)
self.assertTrue(request1.res_body == b'',
"Data in response1: %s" % request1.res_body)
def test_streamed_put(self):
request = http.ClientRequest(
"http://www.domain1.com/file2",
"PUT",
entity_body=io.BytesIO(b"123456\r\n\r\n"))
request.set_expect_continue()
self.client.process_request(request)
response = request.response
self.assertTrue(
response.status == 200, "Status in response: %i" % response.status)
self.assertTrue(
response.reason == "OK",
"Reason in response: %s" %
response.reason)
self.assertTrue(
request.res_body == b"", "Data in response: %s" % request.res_body)
request = http.ClientRequest(
"http://www.domain1.com/file",
"PUT",
entity_body=io.BytesIO(b"123456\r\n\r\n"))
request.set_content_length(10)
self.client.process_request(request)
response = request.response
self.assertTrue(
response.status == 200, "Status in response: %i" % response.status)
self.assertTrue(
response.reason == "OK",
"Reason in response: %s" %
response.reason)
self.assertTrue(
request.res_body == b"", "Data in response: %s" % request.res_body)
def test_streamed_get(self):
buff = io.BytesIO()
request = http.ClientRequest(
"http://www.domain1.com/", "GET", entity_body=None, res_body=buff)
self.client.process_request(request)
response = request.response
self.assertTrue(
response.status == 200, "Status in response: %i" % response.status)
self.assertTrue(
buff.getvalue() == TEST_STRING,
"Data in response: %s" %
request.res_body)
self.assertTrue(
request.res_body == b"",
"Data in streamed response: %s" %
repr(request.res_body))
def domain3_thread_oneshot(self):
time.sleep(1)
logging.debug("domain3_thread_oneshot starting...")
request = http.ClientRequest("http://www.domain3.com/index.txt")
try:
self.client.process_request(request)
except messages.HTTPException as err:
logging.error(err)
def domain4_thread_oneshot(self):
time.sleep(1)
logging.debug("domain4_thread_oneshot starting...")
request = http.ClientRequest("http://www.domain4.com/index.txt")
try:
self.client.process_request(request)
except messages.HTTPException as err:
logging.error(err)
def test_multiget(self):
threads = []
for i in range3(10):
threads.append(
threading.Thread(target=self.domain3_thread_oneshot))
for i in range3(10):
threads.append(
threading.Thread(target=self.domain4_thread_oneshot))
for t in threads:
t.start()
while threads:
t = threads.pop()
t.join()
# success criteria? that we survived
self.client.idle_cleanup(3)
self.client.idle_cleanup(0)
def test_async_close(self):
"""RFC2616:
clients, servers, and proxies MUST be able to recover from
asynchronous close events
Client software SHOULD reopen the transport connection and
retransmit the aborted sequence of requests without user
interaction so long as the request sequence is idempotent"""
request = http.ClientRequest("http://www.domain5.com/unreliable")
# this request will timeout the first time before any data
# has been sent to the client, it should retry and succeed
self.client.process_request(request)
response = request.response
self.assertFalse(response.status is None, "No response")
self.assertTrue(
response.status == 200, "Status in response: %i" % response.status)
self.assertTrue(
response.reason == "Thanks for your patience",
"Reason in response: %s" %
response.reason)
self.assertTrue(
response.entity_body.getvalue() == TEST_STRING,
"Body in response: %i" % response.status)
request = http.ClientRequest("http://www.domain6.com/unreliable",
min_retry_time=0.1)
# this request will always fail with a broken server
self.client.process_request(request)
response = request.response
self.assertTrue(response.status is None, "No response")
def test_async_close2(self):
"""RFC2616:
Non-idempotent methods or sequences MUST NOT be
automatically retried."""
request = http.ClientRequest("http://www.domain5.com/unreliable",
method="POST", entity_body=b"Hello")
# this request will timeout the first time before any data
# has been sent to the client, it should retry and fail!
self.client.process_request(request)
response = request.response
self.assertTrue(response.status is None, "No response")
def test_async_error(self):
request = http.ClientRequest(
"http://www.domain7.com/", min_retry_time=0.1)
self.client.process_request(request)
response = request.response
self.assertTrue(response.status == 200)
self.client.idle_cleanup(0)
def test_post_after_shutdown(self):
request = http.ClientRequest("http://www.domain8.com/",
method="POST", entity_body=b"Hello")
self.client.process_request(request)
response = request.response
self.assertTrue(response.status == 200)
# the remote end has shut down the socket, but without telling
# us so we'll get an error here. We should be able to detect
# that the error happens before we send the request and so
# re-establish the connection. A fail is likely though because
# the method is POST which we won't resend if the data was
# partially sent.
request = http.ClientRequest("http://www.domain8.com/",
method="POST", entity_body=b"Hello")
self.client.process_request(request)
response = request.response
self.assertTrue(response.status == 200)
def test_kill(self):
threads = []
for i in range3(10):
threads.append(
threading.Thread(target=self.domain3_thread_oneshot))
for i in range3(10):
threads.append(
threading.Thread(target=self.domain4_thread_oneshot))
for t in threads:
t.start()
# we can't guarantee we'll find active connections unfortunately
time.sleep(1)
logging.info("%i active connections", self.client.active_count())
self.client.active_cleanup(3)
logging.info(
"%i active connections after active_cleanup(3)",
self.client.active_count())
self.client.active_cleanup(0)
logging.info(
"%i active connections after active_cleanup(0)",
self.client.active_count())
while threads:
t = threads.pop()
t.join()
def upgrade_request(self, request):
self.client.process_request(request)
def test_upgrade(self):
request = http.ClientRequest("http://www.domain9.com/socket")
request.set_upgrade([params.ProductToken("happy")])
self.client.process_request(request)
self.assertTrue(request.status == 101)
try:
self.assertTrue(isinstance(request.send_pipe, Pipe))
self.assertTrue(isinstance(request.recv_pipe, Pipe))
request.send_pipe.write(b'hello\r\n')
request.send_pipe.write_eof()
output = request.recv_pipe.read()
self.assertTrue(output == b'hello\r\n',
"Failed echo test on upgrade: %s" % str(output))
finally:
request.recv_pipe.close()
class LegacyServerTests(unittest.TestCase):
def setUp(self): # noqa
self.port = random.randint(1111, 9999)
self.server = server.Server(port=self.port, app=self.legacy_app,
protocol=params.HTTP_1p0)
# We need to give time to prevent handle_request doing nothing
self.server.timeout = 10
self.client = http.Client()
def tearDown(self): # noqa
self.client.close()
self.server.server_close()
def run_legacy(self, nrequests):
while nrequests:
logging.debug("run_legacy: handling request...")
self.server.handle_request()
nrequests = nrequests - 1
logging.debug("run_legacy: terminating")
def legacy_app(self, environ, start_response):
method = environ['REQUEST_METHOD'].upper()
path = environ['PATH_INFO']
content_length = environ.get('CONTENT_LENGTH', None)
if content_length:
content_length = int(content_length)
else:
content_length = 0
logging.debug("legacy_app invoked: %s %s", method, path)
if path == "/nochunked":
if method == "GET":
# just return some data
start_response("200 OK", [])
return [b"Got it!"]
elif method == "PUT":
environ['wsgi.input'].read(content_length)
start_response("204 Updated", [])
return []
else:
start_response("500 Unexpected", [])
return []
else:
start_response("404 Not Fond", [])
return []
def test_nochunked(self):
"""RFC2616:
For compatibility with HTTP/1.0 applications, HTTP/1.1
requests containing a message-body MUST include a valid
Content-Length header field unless the server is known to be
HTTP/1.1 compliant"""
t = threading.Thread(target=self.run_legacy, args=(2,))
t.start()
request = http.ClientRequest(
"http://localhost:%i/nochunked" % self.port)
self.assertTrue(request.protocol == params.HTTP_1p1)
# start off optimistic about keep_alive
self.assertTrue(request.keep_alive)
self.client.process_request(request)
self.assertTrue(request.response.status == 200)
self.assertTrue(request.response.protocol == params.HTTP_1p0)
# legacy server closes the connection
self.assertFalse(request.response.keep_alive)
# now try and make a call which would normally default to chunked
data = b"How long is a piece of string?"
bodytext = Pipe(rblocking=False, timeout=10)
bodytext.write(data)
request = http.ClientRequest(
"http://localhost:%i/nochunked" % self.port,
"PUT", entity_body=bodytext)
# we should now know that the server is 1.0, so we expect an
# error when trying to send an unbounded entity without
# content-length
self.client.process_request(request)
self.assertTrue(request.response.status is None)
request.set_content_length(len(data))
self.client.process_request(request)
self.assertTrue(request.response.status == 204)
self.assertFalse(request.response.keep_alive)
def test_nochunked2(self):
"""RFC2616:
when a client sends this header field to an origin server
(possibly via a proxy) from which it has never seen a 100
(Continue) status, the client SHOULD NOT wait for an
indefinite period before sending the request body."""
t = threading.Thread(target=self.run_legacy, args=(1,))
t.start()
data = b"How long is a piece of string?"
request = http.ClientRequest(
"http://localhost:%i/nochunked" % self.port,
"PUT", entity_body=data)
# we don't know that the server is 1.0, let's clip the timeout
# on the wait for 100-Continue, 6s on the client is about right,
# will translate to 1s on the wait for continue timeout
self.client.timeout = 6.0
request.set_expect_continue()
self.client.process_request(request)
self.assertTrue(request.response.status == 204)
class SecureTests(unittest.TestCase):
def setUp(self): # noqa
self.cwd = os.getcwd()
self.d = mkdtemp('.d', 'pyslet-test_https-')
os.chdir(self.d)
def tearDown(self): # noqa
os.chdir(self.cwd)
shutil.rmtree(self.d, True)
def test_google_insecure(self):
client = http.Client()
request = http.ClientRequest("https://code.google.com/p/qtimigration/")
try:
client.process_request(request)
except messages.HTTPException as err:
logging.error(err)
client.close()
def test_google_secure(self):
client = http.Client(
ca_certs=os.path.join(TEST_DATA_DIR, "ca_certs.txt"))
request = http.ClientRequest("https://code.google.com/p/qtimigration/")
try:
client.process_request(request)
except messages.HTTPException as err:
logging.error(err)
client.close()
client = http.Client(
ca_certs=os.path.join(TEST_DATA_DIR, "no_certs.txt"))
request = http.ClientRequest("https://code.google.com/p/qtimigration/")
try:
client.process_request(request)
if request.status != 0:
self.fail("Expected status=0 after security failure")
if not request.error:
self.fail("Expected error after security failure")
logging.info(str(request.error))
except messages.HTTPException as err:
logging.error(str(err))
client.close()
def test_chain(self):
try:
from OpenSSL import SSL # noqa
except ImportError:
logging.warning(
"Skipping chain test (install pyOpenSSL to activate test)")
return
client = http.Client()
try:
client.get_server_certificate_chain(
uri.URI.from_octets("http://www.pyslet.org/"))
self.fail("Can't get certificate chain from http URL")
except ValueError:
pass
chain = client.get_server_certificate_chain(
uri.URI.from_octets("https://code.google.com/p/qtimigration/"))
fpath = os.path.join(self.d, 'ca_certs.txt')
with open(fpath, 'wb') as f:
f.write(chain)
client = http.Client(ca_certs=fpath)
request = http.ClientRequest("https://code.google.com/p/qtimigration/")
try:
client.process_request(request)
except messages.HTTPException as err:
logging.error(err)
client.close()
if __name__ == '__main__':
logging.basicConfig(
level=logging.DEBUG, format="[%(thread)d] %(levelname)s %(message)s")
unittest.main()
|
echo-server.py | import socket
import os
import json
from threading import Lock
import threading
import time
HOST = "127.0.0.1"
PORT = 65431
FILE = "store.json"
def ensure_store_exists():
if not os.path.exists(FILE):
with open(FILE, 'w'): pass
class KeyValueCache(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
self.lock = Lock()
def listen(self):
self.sock.listen(5)
while True:
client, address = self.sock.accept()
client.settimeout(60)
threading.Thread(target = self.listenToClient,args = (client,address)).start()
def _get(self, key):
print("GET ", key)
try:
with open(FILE, "r") as f:
data = json.load(f)
if key in data:
return data[key]
else:
return "NO-KEY"
except Exception as e:
print("Unable to be open JSON file")
def _set(self, key, value):
print("SET ", key)
self.lock.acquire()
try:
data = None
with open(FILE, "r") as f:
try:
data = json.load(f)
except Exception as e:
data = dict()
data[key] = value
with open(FILE, "w") as f:
json.dump(data, f)
return "STORED"
except Exception as e:
print(e)
return "NOT-STORED"
finally:
self.lock.release()
def listenToClient(self, client, address):
while True:
try:
byte_data = client.recv(2048)
byte_data = byte_data.decode("utf-8")
byte_data = byte_data.split("\r\n")
header = byte_data[0]
tokens = header.split(" ")
cmd = tokens[0]
if cmd == "set":
key = tokens[1]
size = tokens[2]
value = byte_data[1]
client.sendall(self._set(key, value).encode("utf-8"))
elif cmd == "get":
key = tokens[1]
value = self._get(key)
resp = "VALUE {} {}\r\n{}".format(key, len(value), value)
client.sendall(resp.encode("utf-8"))
else:
raise error('Client disconnected')
except:
client.close()
return False
ensure_store_exists()
KeyValueCache('127.0.0.1', PORT).listen()
# ===========
def find_char(f, start, char):
f.seek(start)
while f.read(1) != char:
continue
return f.tell()
def _get_old(key, size):
with open("store", "r") as store:
pos = 0
current_key = None
while file.tell() < f.size():
pos_s = find_char(f, pos, ' ')
f.seek(pos)
current_key = f.read(pos_s - pos + 1)
if current_key == key:
f.read(1)
pos = f.tell()
pos_s = find_char(f, pos, ' ')
f.seek(pos)
current_size = f.read(pos_s - pos + 1)
f.read(1)
return f.read(current_size)
else:
f.read(1)
pos = f.tell()
pos_s = find_char(f, pos, ' ')
f.seek(pos)
current_size = f.read(pos_s - pos + 1)
pos = f.tell() + current_size + 1 |
laikago_stand_batch.py | import os,inspect,argparse, datetime, copy, itertools, time
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0, parentdir)
os.sys.path.insert(0, os.path.dirname(currentdir))
from b3px_gym.b3px_env.singleton import laikago, laikago_gym_env
from b3px_gym.b3px_env.parallel import laikago_gym_env_pl
from b3px_gym.b3px_env.examples.laikago_b3px_simple_env import DefaultCfg
import rlkit.torch.pytorch_util as ptu
from rlkit.data_management.env_replay_buffer import EnvReplayBuffer
from rlkit.launchers.launcher_util import setup_logger
from rlkit.samplers.data_collector import MdpPathCollector, BatchMdpPathCollector
from rlkit.torch.sac.policies import TanhGaussianPolicy, MakeDeterministic
from rlkit.torch.sac.sac import SACTrainer
from rlkit.torch.networks import FlattenMlp
from rlkit.torch.torch_rl_algorithm import TorchBatchRLAlgorithm
from distWrapper import grpcServer, grpcClient
import numpy as np
import torch
import imageio
from multiprocessing import Process
def make_env(cfg):
env = laikago_gym_env_pl.LaikagoB3PxEnvPl_1(cfg)
return env
def global_seed_reset(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
def sub_process_env(bind_addr):
grpcServer.Serve(bind_addr, make_env)
def experiment(variant, cfg):
proc_expl = Process(target=sub_process_env, args = (cfg['addr_expl'],))
proc_eval = Process(target=sub_process_env, args = (cfg['addr_eval'],))
proc_expl.start()
proc_eval.start()
time.sleep(2)
expl_env = grpcClient.GrpcClient(cfg['addr_expl'])
eval_env = grpcClient.GrpcClient(cfg['addr_eval'])
expl_env.connect(cfg)
eval_env.connect(cfg)
obs_dim = expl_env.observation_space.low.size
action_dim = expl_env.action_space.low.size
M = variant['layer_size']
qf1 = FlattenMlp(
input_size=obs_dim + action_dim,
output_size=1,
hidden_sizes=[M, M, M],
)
qf2 = FlattenMlp(
input_size=obs_dim + action_dim,
output_size=1,
hidden_sizes=[M, M, M],
)
target_qf1 = FlattenMlp(
input_size=obs_dim + action_dim,
output_size=1,
hidden_sizes=[M, M, M],
)
target_qf2 = FlattenMlp(
input_size=obs_dim + action_dim,
output_size=1,
hidden_sizes=[M, M, M],
)
policy = TanhGaussianPolicy(
obs_dim=obs_dim,
action_dim=action_dim,
hidden_sizes=[M, M, M],
)
eval_policy = MakeDeterministic(policy)
eval_path_collector = BatchMdpPathCollector(
eval_env,
eval_policy,
)
expl_path_collector = BatchMdpPathCollector(
expl_env,
policy,
)
replay_buffer = EnvReplayBuffer(
variant['replay_buffer_size'],
expl_env,
)
trainer = SACTrainer(
env=expl_env,
policy=policy,
qf1=qf1,
qf2=qf2,
target_qf1=target_qf1,
target_qf2=target_qf2,
**variant['trainer_kwargs']
)
algorithm = TorchBatchRLAlgorithm(
trainer=trainer,
exploration_env=expl_env,
evaluation_env=eval_env,
exploration_data_collector=expl_path_collector,
evaluation_data_collector=eval_path_collector,
replay_buffer=replay_buffer,
**variant['algorithm_kwargs']
)
algorithm.to(ptu.device)
algorithm.train()
def main(args):
# SimEnv Config
cfg = copy.deepcopy(DefaultCfg)
cfg['backend'] = 'physx' if args.backend else 'bullet'
cfg['gui'] = args.gui
cfg['solver'] = 'tgs'
cfg['urdf_root'] = '../urdf'
cfg['cam_dist'] = 1000
cfg['core'] = 5
cfg['batch'] = 1
cfg['gpu'] = False
cfg['enlarge'] = 5
cfg['addr_expl'] = '127.0.0.1:5000'
cfg['addr_eval'] = '127.0.0.1:6000'
variant = dict(
seed=666666, #int(time.time()),
algorithm="SAC",
version="normal",
layer_size=256,
replay_buffer_size=int(1E6),
algorithm_kwargs=dict(
num_epochs=3000,
num_eval_steps_per_epoch=1000,
num_trains_per_train_loop=1000,
num_expl_steps_per_train_loop=1000,
min_num_steps_before_training=10000,
max_path_length=125,
batch_size=256
),
trainer_kwargs=dict(
discount=0.99,
soft_target_tau=5e-3,
target_update_period=1,
policy_lr=1E-3,
qf_lr=1E-3,
reward_scale=1,
use_automatic_entropy_tuning=True,
),
)
setup_logger('laikago_pl_large_exp', variant=variant)
ptu.set_gpu_mode(True) # optionally set the GPU (default=False)
experiment(variant, cfg)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='PyTorch REINFORCE example')
parser.add_argument('--policy', default="Gaussian",
help='algorithm to use: Gaussian | Deterministic')
parser.add_argument('--eval', type=bool, default=True,
help='Evaluates a policy a policy every 10 episode (default:True)')
parser.add_argument('--gamma', type=float, default=0.99, metavar='G',
help='discount factor for reward (default: 0.99)')
parser.add_argument('--tau', type=float, default=0.005, metavar='G',
help='target smoothing coefficient(τ) (default: 0.005)')
parser.add_argument('--lr', type=float, default=0.0003, metavar='G',
help='learning rate (default: 0.0003)')
parser.add_argument('--alpha', type=float, default=0.2, metavar='G',
help='Temperature parameter α determines the relative importance of the entropy term against the reward (default: 0.2)')
parser.add_argument('--automatic_entropy_tuning', type=bool, default=False, metavar='G',
help='Temperature parameter α automaically adjusted.')
parser.add_argument('--seed', type=int, default=456, metavar='N',
help='random seed (default: 456)')
parser.add_argument('--batch_size', type=int, default=256, metavar='N',
help='batch size (default: 256)')
parser.add_argument('--num_steps', type=int, default=1000001, metavar='N',
help='maximum number of steps (default: 1000000)')
parser.add_argument('--hidden_size', type=int, default=256, metavar='N',
help='hidden size (default: 256)')
parser.add_argument('--updates_per_step', type=int, default=1, metavar='N',
help='model updates per simulator step (default: 1)')
parser.add_argument('--start_steps', type=int, default=10000, metavar='N',
help='Steps sampling random actions (default: 10000)')
parser.add_argument('--target_update_interval', type=int, default=1, metavar='N',
help='Value target update per no. of updates per step (default: 1)')
parser.add_argument('--replay_size', type=int, default=1000000, metavar='N',
help='size of replay buffer (default: 10000000)')
parser.add_argument('--cuda', action="store_true",
help='run on CUDA (default: False)')
parser.add_argument('--backend', type=bool, default=False,
help='BackEnd type(default: False, pybullet, True, PhysX)')
parser.add_argument('-g', '--gui', type=bool, default=False,
help='use gui or not ( default is False, not load)')
args = parser.parse_args()
main(args) |
cluster.py | import zmq
import time
import threading
import json
import socket
class Node:
name = ''
ipaddr = ''
cmd_port = 0
event_port = 0
details = None
def __init__ (self, cmd_port, event_port, name = ''):
self.ipaddr = socket.gethostbyname_ex (socket.gethostname ())[2][0]
self.cmd_port = cmd_port
self.event_port = event_port
if name == '':
self.name = self.ipaddr
else:
self.name = name
self.details = {'name': self.name, 'ipaddr': self.ipaddr, 'command': "{}:{}".format (self.ipaddr, cmd_port), 'event': '{}:{}'.format (self.ipaddr, event_port)}
class Cluster:
nodes = None
local_node = None
ctx = None
cmdListener = None
evtListener = None
pubSocket = None
def __init__ (self, node, context):
self.local_node = node
self.nodes = [node.details]
self.ctx = context
self.cmdListener = ClusterCommandListener (context, self)
self.evtListener = ClusterEventListener (context, self)
self.pubSocket = self.ctx.socket (zmq.PUB)
self.heartbeat = HeartbeatAgent (self.pubSocket, self)
def start (self):
self.pubSocket.bind ('tcp://{}:{}'.format (self.local_node.ipaddr, self.local_node.event_port))
self.cmdListener.start ()
self.evtListener.start ()
self.heartbeat.start ()
def stop (self):
self.heartbeat.stop ()
self.cmdListener.stop ()
self.evtListener.stop ()
self.pubSocket.close ()
def connected (self):
return self.cmdListener.connected ()
def running (self):
return self.cmdListener.running () and self.evtListener.running ()
def add_node (self, node):
if node not in self.nodes:
self.nodes.append (node)
self.evtListener.add_subscription (node)
self.pubSocket.send_json ({'type': 'UPDATE', 'node': self.local_node.details, 'nodes': self.nodes, 'timestamp': time.time ()})
def remove_node (self, node):
if node in self.nodes:
self.nodes.remove (node)
self.evtListener.remove_subscription (node)
self.pubSocket.send_json ({'type': 'UPDATE', 'node': self.local_node.details, 'nodes': self.nodes, 'timestamp': time.time ()})
def join_cluster (self, cluster_cmd_uri):
socket = self.ctx.socket (zmq.REQ)
socket.connect ('tcp://{}'.format (cluster_cmd_uri))
socket.send_json ({'type': 'JOIN', 'node': self.local_node.details, 'timestamp': time.time ()})
resp = socket.recv_json ()
for node in resp['nodes']:
self.add_node (node)
socket.close ()
def status_report (self):
ret = {'local_node': self.local_node.details,
'cluster_nodes': self.nodes,
'command_listener': {
'command_uri': self.local_node.details['command'],
'running': self.cmdListener.running (),
'connected': self.cmdListener.connected ()
},
'event_listener': {
'event_uri': self.local_node.details['event'],
'running': self.evtListener.running (),
'sockets': self.evtListener.sockets.keys ()
}
}
return ret
class HeartbeatAgent:
runFlag = False
cluster = None
pubSocket = None
def __init__ (self, socket, cluster):
self.pubSocket = socket
self.cluster = cluster
def start (self):
self.runFlag = True
self.thread = threading.Thread (target = self.run, args = ())
self.thread.start ()
def stop (self):
self.runFlag = False
def run (self):
while self.runFlag:
self.pubSocket.send_json ({'type': 'HEARTBEAT', 'node': self.cluster.local_node.details, 'timestamp': time.time ()})
time.sleep (1)
class ClusterCommandListener:
runFlag = False
thread = None
ctx = None
sock = None
cluster = None
def __init__ (self, context, cluster):
self.cluster = cluster
self.ctx = context
self.sock = self.ctx.socket (zmq.REP)
def start (self):
self.sock.bind ('tcp://{}:{}'.format (self.cluster.local_node.ipaddr, self.cluster.local_node.cmd_port))
self.runFlag = True
self.thread = threading.Thread (target = self.run, args = ())
self.thread.start ()
def run (self):
while self.runFlag:
try:
req = self.sock.recv_json (zmq.NOBLOCK)
if 'type' in req and req['type'] == 'JOIN':
self.cluster.add_node (req['node'])
self.sock.send_json ({'type': 'ACK', 'nodes': self.cluster.nodes, 'timestamp': time.time ()})
except zmq.ZMQError:
time.sleep (1)
except Exception as ex:
print ex
self.sock.close ()
def stop (self):
self.runFlag = False
def connected (self):
return not self.sock.closed
def running (self):
return self.runFlag
class ClusterEventListener:
runFlag = False
thread = None
ctx = None
poller = None
cluster = None
sockets = None
hb_monitor = None
def __init__ (self, context, cluster):
self.cluster = cluster
self.ctx = context
self.poller = zmq.Poller ()
self.sockets = {}
self.hb_monitor = {}
def start (self):
self.runFlag = True
self.thread = threading.Thread (target = self.run, args = ())
self.thread.start ()
def run (self):
while self.runFlag:
socks = dict(self.poller.poll (1000))
for key in socks.keys ():
if socks[key] == zmq.POLLIN:
message = key.recv_json ()
if 'type' in message and message['type'] == 'UPDATE':
for node in message['nodes']:
self.cluster.add_node (node)
elif 'type' in message and message['type'] == 'HEARTBEAT':
node = message['node']
node_name = node['name']
if node_name not in self.hb_monitor:
self.hb_monitor[node_name] = 0
self.hb_monitor[node_name] = time.time ()
# check if we've not received a heartbeat from any nodes
curr_time = time.time ()
for node in self.cluster.nodes:
node_name = node['name']
if node_name == self.cluster.local_node.name:
continue
if node_name not in self.hb_monitor:
self.hb_monitor[node_name] = curr_time
if (curr_time - self.hb_monitor[node_name]) > 3:
self.cluster.remove_node (node)
for socket in self.sockets.values ():
self.poller.unregister (socket)
socket.close ()
def add_subscription (self, node):
sub_uri = 'tcp://{}'.format (node['event'])
if sub_uri in self.sockets:
return
socket = self.ctx.socket (zmq.SUB)
socket.connect (sub_uri)
socket.setsockopt (zmq.SUBSCRIBE, '')
self.poller.register (socket, zmq.POLLIN)
self.sockets[sub_uri] = socket
def remove_subscription (self, node):
sub_uri = 'tcp://{}'.format (node['event'])
if sub_uri not in self.sockets:
return
socket = self.sockets.pop (sub_uri)
self.poller.unregister (socket)
socket.close ()
def stop (self):
self.runFlag = False
def running (self):
return self.runFlag
|
test_autocommit_update_blocks.py | ##############
# Setup Django
import django
django.setup()
#############
# Test proper
import threading
import time
import pytest
from django.db import transaction
from django.db.models import F, Subquery
from app.models import Sock
@pytest.mark.django_db
def test_autocommit_update_blocks():
# We check that an autocommit UPDATE can block, by holding open a
# concurrent UPDATE
def create():
Sock.objects.all().delete()
Sock.objects.create(id_a=1, id_b=1, colour='black')
create_thread = threading.Thread(target=create)
create_thread.start()
create_thread.join()
barrier = threading.Barrier(2)
def update_with_sleep():
with transaction.atomic():
Sock.objects.all().update(colour='black')
barrier.wait()
time.sleep(11)
time_to_update_autocommit = None
def update_autocommit():
nonlocal time_to_update_autocommit
barrier.wait()
start = time.time()
Sock.objects.all().update(colour='black')
end = time.time()
time_to_update_autocommit = end - start
update_with_sleep_thread = threading.Thread(target=update_with_sleep)
update_with_sleep_thread.start()
update_autocommit_thread = threading.Thread(target=update_autocommit)
update_autocommit_thread.start()
update_with_sleep_thread.join()
update_autocommit_thread.join()
assert time_to_update_autocommit >= 10.0
|
main_file.py | import face_recognition as fr
from threading import Thread
import numpy as np
import time
import os
import cv2
exclude_names = ['Unknown', 'HOD', 'Principal']
class VideoStream:
def __init__(self, stream):
self.video = cv2.VideoCapture(stream)
# Setting the FPS for the video stream
self.video.set(cv2.CAP_PROP_FPS, 60)
if self.video.isOpened() is False:
print("Can't accessing the webcam stream.")
exit(0)
self.grabbed , self.frame = self.video.read()
self.stopped = True
self.thread = Thread(target=self.update)
self.thread.daemon = True
def start(self):
self.stopped = False
self.thread.start()
def update(self):
while True :
if self.stopped is True :
break
self.grabbed , self.frame = self.video.read()
self.video.release()
def read(self):
return self.frame
def stop(self):
self.stopped = True
def encode_faces():
encoded_data = {}
for dirpath, dnames, fnames in os.walk("./Images"):
for f in fnames:
if f.endswith(".jpg") or f.endswith(".png"):
face = fr.load_image_file("Images/" + f)
encoding = fr.face_encodings(face)[0]
encoded_data[f.split(".")[0]] = encoding
# return encoded data of images
return encoded_data
def Attendance(name):
# It will get the current date
today = time.strftime('%d_%m_%Y')
# To create a file if it doesn't exists
f = open(f'Records/record_{today}.csv', 'a')
f.close()
# It will read the CSV file and check if the name
# is already present there or not.
# If the name doesn't exist there, it'll be added
# to a list called 'names'
with open(f'Records/record_{today}.csv', 'r') as f:
data = f.readlines()
names = []
for line in data:
entry = line.split(',')
names.append(entry[0])
# It will check it the name is in the list 'names'
# or not. If not then, the name will be added to
# the CSV file along with the entering time
with open(f'Records/record_{today}.csv', 'a') as fs:
if name not in names:
current_time = time.strftime('%H:%M:%S')
if name not in exclude_names:
fs.write(f"\n{name}, {current_time}")
if __name__ == "__main__":
faces = encode_faces()
encoded_faces = list(faces.values())
faces_name = list(faces.keys())
video_frame = True
# Initialize and start multi-thread video input
# stream from the WebCam.
# 0 refers to the default WebCam
video_stream = VideoStream(stream=0)
video_stream.start()
while True:
if video_stream.stopped is True:
break
else :
frame = video_stream.read()
if video_frame:
face_locations = fr.face_locations(frame)
unknown_face_encodings = fr.face_encodings(frame, \
face_locations)
face_names = []
for face_encoding in unknown_face_encodings:
# Comapring the faces
matches = fr.compare_faces(encoded_faces, \
face_encoding)
name = "Unknown"
face_distances = fr.face_distance(encoded_faces,\
face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = faces_name[best_match_index]
face_names.append(name)
video_frame = not video_frame
for (top, right, bottom, left), name in zip(face_locations,\
face_names):
# Draw a rectangular box around the face
cv2.rectangle(frame, (left-20, top-20), (right+20, \
bottom+20), (0, 255, 0), 2)
# Draw a Label for showing the name of the person
cv2.rectangle(frame, (left-20, bottom -15), \
(right+20, bottom+20), (0, 255, 0), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
# Showing the name of the detected person through
# the WebCam
cv2.putText(frame, name, (left -20, bottom + 15), \
font, 0.85, (255, 255, 255), 2)
# Call the function for attendance
Attendance(name)
# delay for processing a frame
delay = 0.04
time.sleep(delay)
cv2.imshow('frame' , frame)
key = cv2.waitKey(1)
# Press 'q' for stop the executing of the program
if key == ord('q'):
break
video_stream.stop()
# closing all windows
cv2.destroyAllWindows()
|
test_utils.py | """This module provides utilities related to unit testing.
This module contains the `build_and_run_watched_suite`, `assert_array_equals`, `behavior_test`, `generic_test`,
`dalpy_equals` and the `dalpy_to_string` functions, as well as `UnexpectedReturnWarning`.
"""
import copy
import inspect
import math
import traceback
import unittest
import warnings
from multiprocessing import Process
from dalpy.arrays import Array, Array2D
from dalpy.factory_utils import copy_stack
from dalpy.graphs import Graph, Vertex
from dalpy.linked_lists import SinglyLinkedListNode
from dalpy.queues import Queue
from dalpy.sets import Set
from dalpy.stacks import Stack
from dalpy.trees import BinaryTreeNode, NaryTreeNode
def build_and_run_watched_suite(cases, timeout=None, show_tb=False, grading_file=None, warning_filter="once"):
"""Runs a set of test cases, ensuring that they do not run longer than `timeout` seconds. Optionally,
writes comma-separated test results to a file.
Args:
cases: A list of TestCases to be run.
timeout: Number of seconds to allow each test case to run for.
show_tb: Boolean toggle for stack trace.
grading_file: Output file path to store comma-separated test results.
warning_filter: A `warnings.simplefilter` action. Default value ensures that warnings are only displayed once.
Choose `"ignore"` to suppress warnings.
If `grading_file` is not specified, the test logs will be dumped to console.
"""
def _warning(
message,
category,
filename,
lineno,
file=None,
line=None):
print(f'{__bcolors.WARNING}{category.__name__}: {message}{__bcolors.ENDC}')
warnings.showwarning = _warning
warnings.simplefilter(warning_filter, UnexpectedReturnWarning)
warnings.simplefilter("once", DeprecationWarning)
watcher = _Watcher(show_tb)
suite = unittest.TestSuite()
for case in cases:
tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
suite.addTests(tests)
for test in suite:
__run_timed_test(test, watcher, timeout)
if grading_file is not None:
watcher.print_columns(grading_file)
else:
watcher.print_log()
def assert_array_equals(expected, actual, msg=None):
"""Asserts that two `dalpy.arrays.Array`s are equal, displaying a custom message if specified.
Args:
expected: The expected `dalpy.arrays.Array`.
actual: The actual `dalpy.arrays.Array`.
msg: The message to display on `AssertionError`, if not specified, then a default message is displayed.
Raises:
AssertionError: If `expected` != `actual`.
"""
assert isinstance(actual, Array)
assert expected.length() == actual.length(), f"Expected Array length = {expected.length()}, Actual Array length = {actual.length()}" if msg is None else msg
for i in range(expected.length()):
assert expected[i] == actual[
i], f"Expected {expected[i]} at index {i}, Actual = {actual[i]}" if msg is None else msg
def behavior_test(behavior, objects):
"""Test the behavior of an object.
Args:
behavior: a `list` of `tuple`s of the form `(RESULT, METHOD, PARAMETERS)`.
objects: a `list` of objects who's parameters are being called.
Raises:
AssertionError: If `METHOD(PARAMETERS) != RESULT`.
For each tuple in behavior this test asserts that `METHOD(PARAMETERS) = RESULT`.
In each `tuple` `METHOD` should an uncalled `callable`, for example:
>>> stack = Stack()
>>> uncalled_callable = stack.pop
Notes:
- If `METHOD` requires multiple parameters, then `PARAMETERS` can be passed as a `tuple`.
- If `METHOD` has no required return, then `RESULT` can be omitted in favor of `(METHOD, PARAMETERS)`.
- If `METHOD` has no parameters, then `PARAMETERS` can be omitted in favor of `(RESULT, METHOD)`.
Example:
>>> stack = Stack()
>>> behavior = [ (stack.push, 1), (1, stack.pop) ]
The objects parameter is the object who's behavior is being tested, which will be used for the test log.
If multiple objects are being tested, pass a tuple of objects.
"""
msg = f'Behavior:\ninit {", ".join(type(obj).__name__ for obj in objects) if isinstance(objects, list) else type(objects).__name__}\n'
passed = True
expected, method, params, result = None, None, None, None
if not isinstance(behavior, list): behavior = [behavior]
try:
for event in behavior:
if len(event) == 2 and callable(event[0]) and not isinstance(event[0], type): event = (None,) + event
expected = event[0]
method = event[1]
if len(event) > 2:
params = (event[2],)
result = method(*params)
msg += f'{__method_to_string((method,) + params)} {dalpy_to_string(result)}'
else:
result = method()
msg += f'{__method_to_string(method)} {dalpy_to_string(result)}'
params = None
if dalpy_equals(result, expected):
msg += ' ✓\n'
continue
msg += f' ✗\nexpected {dalpy_to_string(expected)}'
passed = False
break
except Exception as e:
# If expected is an exception then check that exception thrown matches expected exception
msg += f'{__method_to_string((method,) + params if params is not None else method)} {dalpy_to_string(result)} ✗\n'
if type(expected) == type and isinstance(e, expected): return
# error_message = e.args[0] if len(e.args) > 0 else e.with_traceback
assert False, f'{msg}Unexpected error: {type(e).__name__}'
assert passed, msg
def run_generic_test(params, expected, method, custom_comparator=None, in_place=False, enforce_no_mod=False,
init_params=None,
init_expected=None, params_to_string=None, expected_to_string=None, output_to_string=None):
"""Test the output of a function.
Warnings:
Deprecated in 1.1.0, to be removed. Use the generic_test function instead.
Args:
params: Parameters to be passed into the function being tested. This argument can either be a single parameter,
or a list of parameters.
expected: Expected return value of tested function with parameters specified by params.
method: Function being tested. Must be a `callable`.
custom_comparator: Function for determining if method output equals expected. Must be a `callable`.
in_place: `True` if `expected` should be compared against `params`.
enforce_no_mod: `bool` or a `list` of `bool` indicating which args should not be modified. Default `False`
allows modification of all args.
init_params: Function for initializing parameters. Must be a `callable`.
init_expected: Function for initializing expected output. Must be a `callable`.
params_to_string: Function for displaying the parameters. Must be a `callable`.
expected_to_string: Function for displaying the expected output. Must be a `callable`.
output_to_string: Function for displaying the actual output. Must be a `callable`.
Raises:
AssertionError: If the test fails.
UnexpectedReturnWarning: If `in_place` is set to `True` but `method` still returns a value.
DeprecationWarning: If used in version >= 1.1.0.
If `expected` is an `Exception`, the test will assert that the function tested on the given parameters throws the
expected `Exception`. If no custom `to_string`s are specified, the `dalpy_to_string` method will be used for
displaying parameters, input and output.
"""
warnings.warn("run_generic_test is deprecated after version 1.1.0, use generic_test instead.", DeprecationWarning,
stacklevel=2)
params = init_params(params) if init_params is not None else params
expected = init_expected(expected) if init_expected is not None else expected
generic_test(params, expected, method, custom_comparator=custom_comparator, in_place=in_place,
enforce_no_mod=enforce_no_mod,
params_to_string=params_to_string, expected_to_string=expected_to_string,
output_to_string=output_to_string)
def generic_test(params, expected, method, custom_comparator=None, in_place=False, enforce_no_mod=False,
params_to_string=None, expected_to_string=None, output_to_string=None):
"""Test the output of a function.
Args:
params: Parameters to be passed into the function being tested. This argument can either be a single parameter,
or a list of parameters.
expected: Expected return value of tested function with parameters specified by params. If `expected` is an
`Exception`, the test will assert that the function tested on the given parameters throws the expected
`Exception`.
method: Function being tested. Must be a `callable`.
custom_comparator: Function for determining if method output equals expected. Must be a `callable`. Default
`None` which means that `dalpy_equals` will be used.
in_place: `True` if `expected` should be compared against `params`. By default this is `False`.
enforce_no_mod: `bool` or a `list` of `bool` indicating which args should not be modified. Default `False`
allows modification of all args.
params_to_string: Function for displaying the parameters. Must be a `callable`. Default `None` which means that
`dalpy_to_string` will be used instead.
expected_to_string: Function for displaying the expected output. Must be a `callable`. Default `None` which
means that `dalpy_to_string` will be used instead.
output_to_string: Function for displaying the actual output. Must be a `callable`. Default `None` which means
that `dalpy_to_string` will be used instead.
Raises:
AssertionError: If the test fails.
UnexpectedReturnWarning: If `in_place` is set to `True` but `method` still returns a value.
"""
msg = f"Input: {dalpy_to_string(params) if params_to_string is None else params_to_string(params)}\nExpected: {dalpy_to_string(expected) if expected_to_string is None else expected_to_string(expected)}\n"
params_copy = copy.deepcopy(params) if isinstance(params, list) else [copy.deepcopy(params)]
passed = True
try:
result = method(*params) if isinstance(params, list) else method(params)
if in_place:
if result is not None:
warnings.warn("A function that is meant to modify its argument(s) returned a non-None value.",
UnexpectedReturnWarning, stacklevel=2)
result = params
result_string = output_to_string(result) if output_to_string is not None else dalpy_to_string(result)
if custom_comparator is None:
if not dalpy_equals(expected, result):
msg = f"{msg}Output: {result_string}"
passed = False
elif not custom_comparator(expected, result):
msg = f"{msg}Output: {result_string}"
passed = False
except Exception as e:
# If expected is an exception then check that exception thrown matches expected exception
if type(expected) == type and isinstance(e, expected): return
error_message = e.args[0] if len(e.args) > 0 else e.with_traceback
assert False, f"{msg}Output: {error_message}"
assert passed, msg
enforce_no_mod = [enforce_no_mod] * len(params_copy) if isinstance(enforce_no_mod, bool) else enforce_no_mod
modified_params_string = dalpy_to_string(params) if params_to_string is None else params_to_string(params)
if not isinstance(params, list): params = [params]
for i, no_mod in enumerate(enforce_no_mod):
if no_mod:
assert dalpy_equals(params_copy[i], params[
i]), f"{msg}Output: The {str(i + 1) + __append_int(i + 1)} input argument should not have been modified.\nArguments: {modified_params_string}"
def dalpy_equals(first, second):
"""Tests equality between two objects. If the objects are from the DALPy, they are compared using their own
custom comparator.
`dalpy_equals` supports equality for the following objects: `dalpy.arrays.Array`, `dalpy.arrays.Array2D`,
`dalpy.queues.Queue`, `dalpy.stacks.Stack`, `dalpy.sets.Set`,
`dalpy.linked_lists.SinglyLinkedListNode`. For `dalpy.linked_lists.SinglyLinkedListNode`, checks that all
nodes next of the passed `dalpy.linked_lists.SinglyLinkedListNode`s are the same. For instances of `float`s,
`math.isclose` is used for comparison.
Args:
first: The first element to be tested.
second: The second element to be tested
Returns:
`True` if `first = second` otherwise `False`.
"""
if isinstance(first, Array) and isinstance(second, Array):
return __array_equals(first, second)
if isinstance(first, Array2D) and isinstance(second, Array2D):
return __array2d_equals(first, second)
if isinstance(first, Queue) and isinstance(second, Queue):
return __queue_equals(first, second)
if isinstance(first, Stack) and isinstance(second, Stack):
return __stack_equals(first, second)
if isinstance(first, Set) and isinstance(second, Set):
return __set_equals(first, second)
if isinstance(first, SinglyLinkedListNode) and isinstance(second, SinglyLinkedListNode):
return __singly_linked_list_equals(first, second)
if isinstance(first, float) and isinstance(second, float):
return math.isclose(first, second)
return first == second
def dalpy_to_string(obj):
"""Generates a string representation of a DALPy object if passed object is from DALPy, otherwise calls
native str method.
dalpy_to_string supports the following objects: `dalpy.arrays.Array`, `dalpy.arrays.Array2D`,
`dalpy.queues.Queue`, `dalpy.stacks.Stack`, `dalpy.sets.Set`,
`dalpy.linked_lists.SinglyLinkedListNode`, `dalpy.trees.BinaryTreeNode`, `dalpy.trees.NaryTreeNode`,
`dalpy.graphs.Vertex`, and `dalpy.graphs.Graph`.
Calling dalpy_to_string on `dalpy.trees.BinaryTreeNode` or `dalpy.trees.NaryTreeNode` displays the entire
tree rooted at that node prepended with `"BinaryTree"` and `"NaryTree"` respectively.
This is done to clarify the nodes themselves are not holding the data listed after it.
Returns:
string representation of `obj`.
Args:
obj: The object to convert to string
"""
if isinstance(obj, list):
return "[" + ", ".join(dalpy_to_string(elem) for elem in obj) + "]"
if isinstance(obj, Array):
return "Array" + __array_to_string(obj)
if isinstance(obj, Array2D):
return "Array2D" + __array2d_to_string(obj)
if isinstance(obj, Queue):
return "Queue" + __queue_to_string(obj)
if isinstance(obj, Stack):
return "Stack" + __stack_to_string(obj)
if isinstance(obj, Set):
return "Set" + __set_to_string(obj)
if isinstance(obj, SinglyLinkedListNode):
return __singly_linked_list_to_string(obj)
if isinstance(obj, BinaryTreeNode):
return "BinaryTree" + __binary_tree_to_string(obj)
if isinstance(obj, NaryTreeNode):
return "NaryTree" + __nary_tree_to_string(obj)
if isinstance(obj, Vertex):
return __vertex_to_string(obj)
if isinstance(obj, Graph):
return __graph_to_string(obj)
try:
return str(obj)
except:
return obj
class UnexpectedReturnWarning(Warning):
"""A `Warning` subclass for instances where functions are expected to modify their arguments but return values instead."""
pass
class _TestTimeoutError(Exception):
def __init__(self, timeout):
super().__init__(f'Test timed out after {timeout}s.')
class _Watcher(unittest.TestResult):
def __init__(self, show_tb):
super().__init__()
self.test_ids = list()
self.results = list()
self.details = list()
self.show_tb = show_tb
@staticmethod
def parse_id(test_id):
return test_id[test_id.index('.') + 1:]
@staticmethod
def get_description(test):
if test.shortDescription() is None: return '\n'
lines = test._testMethodDoc.split('\n')
return "\n".join(line.strip() for line in lines) + "Output:\t"
def addSuccess(self, test) -> None:
self.test_ids.append(_Watcher.parse_id(test.id()))
self.results.append(1)
def addFailure(self, test, err) -> None:
self.test_ids.append(_Watcher.parse_id(test.id()))
self.results.append(0)
tb_str = ''
if self.show_tb:
tb_str = '\n' + ''.join(traceback.format_tb(err[2]))
self.details.append((_Watcher.get_description(test), str(err[1]) + tb_str, _Watcher.parse_id(test.id())))
def addError(self, test, err):
self.test_ids.append(_Watcher.parse_id(test.id()))
self.results.append(0)
tb_str = ''
if self.show_tb:
tb_str = '\n' + ''.join(traceback.format_tb(err[2]))
self.details.append(
(_Watcher.get_description(test), err[0], str(err[1]) + tb_str, _Watcher.parse_id(test.id())))
# Note The order in which the various tests will be run is determined by sorting the test method names with respect
# to the built-in ordering for strings.
def print_columns(self, fp):
with open(fp, mode='w+', encoding='utf-8') as f:
f.write(",".join(self.test_ids))
f.write('\n')
f.write(",".join(str(e) for e in self.results))
def print_log(self):
log = list()
for detail in self.details:
if len(detail) == 3:
log.append(f'{detail[2].split("Test.")[0]} test failed.\n{detail[0]}{detail[1]}')
else:
log.append(f'{detail[0]} raised {detail[1]}.\nMessage: {detail[2]}')
print("\n" + ("\n" + "-" * 40 + "\n").join(
log) + f"\n{'=' * 40}\n{sum(self.results)}/{len(self.results)} tests passed.\n")
def __run_timed_test(test, watcher, timeout):
if timeout is not None:
p = Process(target=test.run)
p.start()
p.join(timeout=timeout)
if p.is_alive():
p.terminate()
watcher.addError(test, (_TestTimeoutError, _TestTimeoutError(timeout)))
return
test.run(watcher)
def __array_to_string(array):
out = "["
for i in range(array.length()):
out += f'{dalpy_to_string(array[i])}, '
return out[:-2] + "]" if array.length() > 0 else out + "]"
def __array2d_to_string(array):
out = "["
for i in range(array.rows()):
out += "["
for j in range(array.columns()):
out += f'{dalpy_to_string(array[(i, j)])}, '
out = out[:-2] + "]\n "
return out[:-2] + "]"
def __queue_to_string(queue):
out = []
for _ in range(queue.size()):
next = queue.dequeue()
out.append(dalpy_to_string(next))
queue.enqueue(next)
return "[" + ", ".join(out) + "]"
def __stack_to_string(stack):
out = []
temp_stack = Stack()
for _ in range(stack.size()):
next = stack.pop()
out.insert(0, dalpy_to_string(next))
temp_stack.push(next)
while not temp_stack.is_empty():
stack.push(temp_stack.pop())
return "[" + ", ".join(out) + "]"
def __set_to_string(s):
out = []
for elem in s:
out.append(dalpy_to_string(elem))
return "{" + ", ".join(out) + "}"
def __singly_linked_list_to_string(head):
out = list()
seen = set()
while head is not None:
if head in seen:
out.append("cycle")
break
seen.add(head)
out.append(dalpy_to_string(head.data))
head = head.next
return "➔ ".join(out)
def __strip_trailing_nones(ls):
while len(ls) > 0 and ls[-1] is None:
ls.pop()
def __binary_tree_to_string(root):
# https://leetcode.com/problems/balanced-binary-tree/
if root is None:
return ""
out_buf = list()
q = list()
q.append(root)
all_none_level = False
while not all_none_level:
k = len(q)
all_none_level = True
for _ in range(k):
curr = q.pop(0)
if curr is not None:
q.append(curr.left)
q.append(curr.right)
out_buf.append(dalpy_to_string(curr.data))
all_none_level = False
else:
out_buf.append(None)
__strip_trailing_nones(out_buf)
return f'[{", ".join(out_buf)}]'
def __vertex_to_string(vertex):
return vertex.get_name()
def __graph_to_string(graph):
contents = list()
for vertex in graph.vertices():
edges = list()
for dest in graph.adj(vertex):
edge_str = f'{dest.get_name()}'
weight = graph.weight(vertex, dest)
if weight is not None:
edge_str += f' <{weight}>'
edges.append(edge_str)
edges = ', '.join(edges)
contents.append(f'{vertex.get_name()}: {edges}')
contents = '\n'.join(contents)
return contents
def __nary_tree_to_string(root):
# https://leetcode.com/problems/n-ary-tree-preorder-traversal/
if root is None:
return ""
out = list()
q = [root, root.right_sibling]
while len(q) > 0:
k = len(q)
for _ in range(k):
curr = q.pop(0)
if curr is None:
out.append(None)
else:
out.append(dalpy_to_string(curr.data))
lm_child = curr.leftmost_child
q.append(lm_child)
while lm_child is not None:
lm_child = lm_child.right_sibling
q.append(lm_child)
__strip_trailing_nones(out)
return f'[{", ".join(out)}]'
def __array_equals(expected, actual):
if expected.length() != actual.length(): return False
for i in range(expected.length()):
if expected[i] != actual[i]: return False
return True
def __array2d_equals(expected, actual):
if expected.rows() != actual.rows() or expected.columns() != actual.columns(): return False
for i in range(expected.rows()):
for j in range(expected.columns()):
if expected[i, j] != actual[i, j]: return False
return True
def __queue_equals(expected, actual):
for _ in range(expected.size()):
expected_elem = expected.dequeue()
actual_elem = actual.dequeue()
if expected_elem != actual_elem: return False
expected.enqueue(expected_elem)
actual.enqueue(actual_elem)
return expected.size() == actual.size()
def __stack_equals(expected, actual):
if expected.size() != actual.size(): return False
expected_cpy = copy_stack(expected)
actual_cpy = copy_stack(actual)
i = 0
while not expected_cpy.is_empty():
e = expected_cpy.pop()
a = actual_cpy.pop()
if e != a: return False
i += 1
return True
def __set_equals(expected, actual):
expected_set = set()
actual_set = set()
for elem in expected:
expected_set.add(elem)
for elem in actual:
actual_set.add(elem)
return expected_set == actual_set
def __singly_linked_list_equals(expected, actual):
seen = set()
while (expected is not None and actual is not None):
if actual in seen: return False
seen.add(actual)
if expected != actual: return False
expected = expected.next
actual = actual.next
return expected is None and actual is None
def __method_to_string(method):
new_line = "\n"
if isinstance(method, tuple):
return f'({str(inspect.getsourcelines(method[0])[0][0]).strip(new_line).strip().split()[1].replace("(self,", "")}, {", ".join(str(param) for param in method[1:])})'
return str(inspect.getsourcelines(method)[0][0]).strip("\n").strip().split()[1].replace('(self):', '()')
def __append_int(num):
if num > 9:
secondToLastDigit = str(num)[-2]
if secondToLastDigit == '1':
return 'th'
lastDigit = num % 10
if (lastDigit == 1):
return 'st'
elif (lastDigit == 2):
return 'nd'
elif (lastDigit == 3):
return 'rd'
else:
return 'th'
class __bcolors:
HEADER = '\033[95m'
WARNING = '\033[93m'
ENDC = '\033[0m'
|
threading_local_defaults.py | #!/usr/bin/env python3
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""Defaults for thread-local values
"""
#end_pymotw_header
import random
import threading
import logging
def show_value(data):
try:
val = data.value
except AttributeError:
logging.debug('No value yet')
else:
logging.debug('value=%s', val)
def worker(data):
show_value(data)
data.value = random.randint(1, 100)
show_value(data)
class MyLocal(threading.local):
def __init__(self, value):
super().__init__()
logging.debug('Initializing %r', self)
self.value = value
logging.basicConfig(
level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
local_data = MyLocal(1000)
show_value(local_data)
for i in range(2):
t = threading.Thread(target=worker, args=(local_data,))
t.start()
|
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
from bauh.api.abstract.view import MessageType
from bauh.commons.html import strip_html
from bauh.commons.system import SystemProcess, ProcessHandler
from bauh.gems.flatpak import flatpak, suggestions
from bauh.gems.flatpak.model import FlatpakApplication
from bauh.gems.flatpak.worker import FlatpakAsyncDataLoader, FlatpakUpdateLoader
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()
context.disk_loader_factory.map(FlatpakApplication, self.api_cache)
self.enabled = True
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)
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).start()
else:
app.fill_cached_data(api_data)
return app
def search(self, words: str, disk_loader: DiskCacheLoader, limit: int = -1) -> SearchResult:
res = SearchResult([], [], 0)
apps_found = flatpak.search(flatpak.get_version(), words)
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:
if thread_updates:
thread_updates.join()
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 = app_json['ref'] in updates[0] if updates else None
models.append(model)
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)
watcher.change_progress(10)
watcher.change_substatus(self.i18n['flatpak.downgrade.commits'])
commits = flatpak.get_app_commits(pkg.ref, pkg.origin)
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, 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)))
def uninstall(self, pkg: FlatpakApplication, root_password: str, watcher: ProcessWatcher) -> bool:
return ProcessHandler(watcher).handle(SystemProcess(subproc=flatpak.uninstall(pkg.ref)))
def get_info(self, app: FlatpakApplication) -> dict:
app_info = flatpak.get_app_info_fields(app.id, app.branch)
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_info.get('installed'):
app_info['installed'] = app_info['installed'].replace('?', ' ')
return app_info
def get_history(self, pkg: FlatpakApplication) -> PackageHistory:
pkg.commit = flatpak.get_commit(pkg.id, pkg.branch)
commits = flatpak.get_app_commits_data(pkg.ref, pkg.origin)
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:
res = ProcessHandler(watcher).handle(SystemProcess(subproc=flatpak.install(pkg.id, pkg.origin), wrong_error_phrase='Warning'))
if res:
try:
fields = flatpak.get_fields(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'
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),
pkg_type='flatpak',
version=app.version))
return updates
def list_warnings(self) -> List[str]:
if flatpak.is_installed():
if not flatpak.has_remotes_set():
return [self.i18n['flatpak.notification.no_remotes']]
def list_suggestions(self, limit: int) -> List[PackageSuggestion]:
cli_version = flatpak.get_version()
res = []
sugs = [(i, p) for i, p in suggestions.ALL.items()]
sugs.sort(key=lambda t: t[1].value, reverse=True)
for sug in sugs:
if limit <= 0 or len(res) < limit:
app_json = flatpak.search(cli_version, sug[0], app_id=True)
if app_json:
res.append(PackageSuggestion(self._map_to_model(app_json[0], False, None), sug[1]))
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: SoftwarePackage):
flatpak.run(pkg.id)
|
network.py | # Copyright 2019 Uber Technologies, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import random
import socket
import struct
import threading
import cloudpickle
import psutil
from six.moves import queue, socketserver
from horovod.run.common.util import secret
class PingRequest(object):
pass
class NoValidAddressesFound(Exception):
pass
class PingResponse(object):
def __init__(self, service_name, source_address):
self.service_name = service_name
"""Service name that responded to this ping."""
self.source_address = source_address
"""Source IP address that was visible to the service."""
class AckResponse(object):
"""Used for situations when the response does not carry any data."""
pass
class Wire(object):
"""
Used for serialization/deserialization of objects over the wire.
We use HMAC to protect services from unauthorized use. The key used for
the HMAC digest is distributed by Open MPI and Spark.
The objects are serialized using cloudpickle. Serialized objects become
the body of the message.
Structure of the message is as follows:
- HMAC digest of the body (32 bytes)
- length of the body (4 bytes)
- body
"""
def __init__(self, key):
self._key = key
def write(self, obj, wfile):
message = cloudpickle.dumps(obj)
digest = secret.compute_digest(self._key, message)
wfile.write(digest)
# Pack message length into 4-byte integer.
wfile.write(struct.pack('i', len(message)))
wfile.write(message)
wfile.flush()
def read(self, rfile):
digest = rfile.read(secret.DIGEST_LENGTH)
# Unpack message length into 4-byte integer.
message_len = struct.unpack('i', rfile.read(4))[0]
message = rfile.read(message_len)
if not secret.check_digest(self._key, message, digest):
raise Exception('Security error: digest did not match the message.')
return cloudpickle.loads(message)
class BasicService(object):
def __init__(self, service_name, key):
self._service_name = service_name
self._wire = Wire(key)
self._server = self._make_server()
self._port = self._server.socket.getsockname()[1]
self._thread = threading.Thread(target=self._server.serve_forever)
self._thread.daemon = True
self._thread.start()
def _make_server(self):
min_port = 1024
max_port = 65536
num_ports = max_port - min_port
start_port = random.randrange(0, num_ports)
for port_offset in range(num_ports):
try:
port = min_port + (start_port + port_offset) % num_ports
return socketserver.ThreadingTCPServer(('0.0.0.0', port), self._make_handler())
except:
pass
raise Exception('Unable to find a port to bind to.')
def _make_handler(self):
server = self
class _Handler(socketserver.StreamRequestHandler):
def handle(self):
try:
req = server._wire.read(self.rfile)
resp = server._handle(req, self.client_address)
if not resp:
raise Exception('Handler did not return a response.')
server._wire.write(resp, self.wfile)
except EOFError:
# Happens when client is abruptly terminated, don't want to pollute the logs.
pass
return _Handler
def _handle(self, req, client_address):
if isinstance(req, PingRequest):
return PingResponse(self._service_name, client_address[0])
raise NotImplementedError(req)
def addresses(self):
result = {}
for intf, intf_addresses in psutil.net_if_addrs().items():
for addr in intf_addresses:
if addr.family == socket.AF_INET:
if intf not in result:
result[intf] = []
result[intf].append((addr.address, self._port))
return result
def shutdown(self):
self._server.shutdown()
self._server.server_close()
self._thread.join()
def get_port(self):
return self._port
class BasicClient(object):
def __init__(self, service_name, addresses, key, verbose, match_intf=False,
probe_timeout=20, retries=3):
# Note: because of retry logic, ALL RPC calls are REQUIRED to be idempotent.
self._verbose = verbose
self._service_name = service_name
self._wire = Wire(key)
self._match_intf = match_intf
self._probe_timeout = probe_timeout
self._retries = retries
self._addresses = self._probe(addresses)
if not self._addresses:
raise NoValidAddressesFound(
'Horovodrun was unable to connect to {service_name} on any '
'of the following addresses: {addresses}.\n\n'
'One possible cause of this problem is that '
'horovodrun currently requires every host to have at '
'least one routable network interface with the same '
'name across all of the hosts. '
'You can run \"ifconfig -a\" '
'on every host and check for the common '
'routable interface. '
'To fix the problem, you can rename interfaces on '
'Linux.'.format(service_name=service_name, addresses=addresses))
def _probe(self, addresses):
result_queue = queue.Queue()
threads = []
for intf, intf_addresses in addresses.items():
for addr in intf_addresses:
thread = threading.Thread(target=self._probe_one,
args=(intf, addr, result_queue))
thread.daemon = True
thread.start()
threads.append(thread)
for t in threads:
t.join()
result = {}
while not result_queue.empty():
intf, addr = result_queue.get()
if intf not in result:
result[intf] = []
result[intf].append(addr)
return result
def _probe_one(self, intf, addr, result_queue):
for iter in range(self._retries):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self._probe_timeout)
try:
sock.connect(addr)
rfile = sock.makefile('rb')
wfile = sock.makefile('wb')
try:
self._wire.write(PingRequest(), wfile)
resp = self._wire.read(rfile)
if resp.service_name != self._service_name:
return
if self._match_intf:
# Interface name of destination and source must match
# since `match_intf` is requested.
client_intf_addrs = [x.address
for x in psutil.net_if_addrs().get(intf, [])
if x.family == socket.AF_INET]
if resp.source_address not in client_intf_addrs:
if self._verbose >= 2:
# Need to find the local interface name whose
# adderss was visible to the target
# host's server.
resp_intf = ''
for key in psutil.net_if_addrs().keys():
key_intf_addrs = [x.address
for x in psutil.net_if_addrs().get(key, [])]
if resp.source_address in key_intf_addrs:
resp_intf = key
break
print('WARNING: Expected to connect the host '
'{addr} using interface '
'{intf}, but reached it on interface '
'{resp_intf}.'.format(
addr=str(addr[0])+':'+str(addr[1]),
intf=intf,
resp_intf=resp_intf))
return
result_queue.put((intf, addr))
return
finally:
rfile.close()
wfile.close()
except:
pass
finally:
sock.close()
def _send_one(self, addr, req):
for iter in range(self._retries):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect(addr)
rfile = sock.makefile('rb')
wfile = sock.makefile('wb')
try:
self._wire.write(req, wfile)
resp = self._wire.read(rfile)
return resp
finally:
rfile.close()
wfile.close()
except:
if iter == self._retries - 1:
# Raise exception on the last retry.
raise
finally:
sock.close()
def _send(self, req):
# Since all the addresses were vetted, use the first one.
addr = list(self._addresses.values())[0][0]
return self._send_one(addr, req)
def addresses(self):
return self._addresses
|
utils.py | #================================================================
# Adapted from: https://github.com/pythonlessons/TensorFlow-2.x-YOLOv3
# Description : additional yolov3 and yolov4 functions
#
#================================================================
from multiprocessing import Process, Queue, Pipe
import cv2
import time
import random
import colorsys
import numpy as np
from PIL import Image
import io
import base64
import tensorflow as tf
import sys
sys.path.insert(1, "C:/Users/jeane/Documents/new-hands-on-2021/notebooks/yolov3")
import configs
from configs import *
import yolov4
from yolov4 import *
#from yolov3.configs import * ##sur colab ou sur l'environnement de base
#from yolov3.yolov4 import * ##sur colab ou sur l'environnement de base
from tensorflow.python.saved_model import tag_constants
def load_yolo_weights(model, weights_file):
tf.keras.backend.clear_session() # used to reset layer names
# load Darknet original weights to TensorFlow model
if YOLO_TYPE == "yolov3":
range1 = 75 if not TRAIN_YOLO_TINY else 13
range2 = [58, 66, 74] if not TRAIN_YOLO_TINY else [9, 12]
if YOLO_TYPE == "yolov4":
range1 = 110 if not TRAIN_YOLO_TINY else 21
range2 = [93, 101, 109] if not TRAIN_YOLO_TINY else [17, 20]
with open(weights_file, 'rb') as wf:
major, minor, revision, seen, _ = np.fromfile(wf, dtype=np.int32, count=5)
j = 0
for i in range(range1):
if i > 0:
conv_layer_name = 'conv2d_%d' %i
else:
conv_layer_name = 'conv2d'
if j > 0:
bn_layer_name = 'batch_normalization_%d' %j
else:
bn_layer_name = 'batch_normalization'
conv_layer = model.get_layer(conv_layer_name)
filters = conv_layer.filters
k_size = conv_layer.kernel_size[0]
in_dim = conv_layer.input_shape[-1]
if i not in range2:
# darknet weights: [beta, gamma, mean, variance]
bn_weights = np.fromfile(wf, dtype=np.float32, count=4 * filters)
# tf weights: [gamma, beta, mean, variance]
bn_weights = bn_weights.reshape((4, filters))[[1, 0, 2, 3]]
bn_layer = model.get_layer(bn_layer_name)
j += 1
else:
conv_bias = np.fromfile(wf, dtype=np.float32, count=filters)
# darknet shape (out_dim, in_dim, height, width)
conv_shape = (filters, in_dim, k_size, k_size)
conv_weights = np.fromfile(wf, dtype=np.float32, count=np.product(conv_shape))
# tf shape (height, width, in_dim, out_dim)
conv_weights = conv_weights.reshape(conv_shape).transpose([2, 3, 1, 0])
if i not in range2:
conv_layer.set_weights([conv_weights])
bn_layer.set_weights(bn_weights)
else:
conv_layer.set_weights([conv_weights, conv_bias])
assert len(wf.read()) == 0, 'failed to read all data'
def Load_Yolo_model():
gpus = tf.config.experimental.list_physical_devices('GPU')
if len(gpus) > 0:
print(f'GPUs {gpus}')
try: tf.config.experimental.set_memory_growth(gpus[0], True)
except RuntimeError: pass
if YOLO_FRAMEWORK == "tf": # TensorFlow detection
if YOLO_TYPE == "yolov4":
Darknet_weights = YOLO_V4_TINY_WEIGHTS if TRAIN_YOLO_TINY else YOLO_V4_WEIGHTS
if YOLO_TYPE == "yolov3":
Darknet_weights = YOLO_V3_TINY_WEIGHTS if TRAIN_YOLO_TINY else YOLO_V3_WEIGHTS
if YOLO_CUSTOM_WEIGHTS == False:
print("Loading Darknet_weights from:", Darknet_weights)
yolo = Create_Yolo(input_size=YOLO_INPUT_SIZE, CLASSES=YOLO_COCO_CLASSES)
load_yolo_weights(yolo, Darknet_weights) # use Darknet weights
else:
checkpoint = f"./checkpoints/{TRAIN_MODEL_NAME}"
if TRAIN_YOLO_TINY:
checkpoint += "_Tiny"
print("Loading custom weights from:", checkpoint)
yolo = Create_Yolo(input_size=YOLO_INPUT_SIZE, CLASSES=TRAIN_CLASSES)
yolo.load_weights(checkpoint) # use custom weights
elif YOLO_FRAMEWORK == "trt": # TensorRT detection
saved_model_loaded = tf.saved_model.load(YOLO_CUSTOM_WEIGHTS, tags=[tag_constants.SERVING])
signature_keys = list(saved_model_loaded.signatures.keys())
yolo = saved_model_loaded.signatures['serving_default']
return yolo
def image_preprocess(image, target_size, gt_boxes=None):
ih, iw = target_size
h, w, _ = image.shape
scale = min(iw/w, ih/h)
nw, nh = int(scale * w), int(scale * h)
image_resized = cv2.resize(image, (nw, nh))
image_paded = np.full(shape=[ih, iw, 3], fill_value=128.0)
dw, dh = (iw - nw) // 2, (ih-nh) // 2
image_paded[dh:nh+dh, dw:nw+dw, :] = image_resized
image_paded = image_paded / 255.
if gt_boxes is None:
return image_paded
else:
gt_boxes[:, [0, 2]] = gt_boxes[:, [0, 2]] * scale + dw
gt_boxes[:, [1, 3]] = gt_boxes[:, [1, 3]] * scale + dh
return image_paded, gt_boxes
def draw_bbox(image, bboxes, CLASSES=YOLO_COCO_CLASSES, show_label=True, show_confidence = True, Text_colors=(255,255,0), rectangle_colors='', tracking=False):
NUM_CLASS = read_class_names(CLASSES)
num_classes = len(NUM_CLASS)
image_h, image_w, _ = image.shape
hsv_tuples = [(1.0 * x / num_classes, 1., 1.) for x in range(num_classes)]
#print("hsv_tuples", hsv_tuples)
colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))
random.seed(0)
random.shuffle(colors)
random.seed(None)
for i, bbox in enumerate(bboxes):
coor = np.array(bbox[:4], dtype=np.int32)
score = bbox[4]
class_ind = int(bbox[5])
bbox_color = rectangle_colors if rectangle_colors != '' else colors[class_ind]
bbox_thick = int(0.6 * (image_h + image_w) / 1000)
if bbox_thick < 1: bbox_thick = 1
fontScale = 0.75 * bbox_thick
(x1, y1), (x2, y2) = (coor[0], coor[1]), (coor[2], coor[3])
# put object rectangle
cv2.rectangle(image, (x1, y1), (x2, y2), bbox_color, bbox_thick*2)
if show_label:
# get text label
score_str = " {:.2f}".format(score) if show_confidence else ""
if tracking: score_str = " "+str(score)
try:
label = "{}".format(NUM_CLASS[class_ind]) + score_str
except KeyError:
print("You received KeyError, this might be that you are trying to use yolo original weights")
print("while using custom classes, if using custom model in configs.py set YOLO_CUSTOM_WEIGHTS = True")
# get text size
(text_width, text_height), baseline = cv2.getTextSize(label, cv2.FONT_HERSHEY_COMPLEX_SMALL,
fontScale, thickness=bbox_thick)
# put filled text rectangle
cv2.rectangle(image, (x1, y1), (x1 + text_width, y1 - text_height - baseline), bbox_color, thickness=cv2.FILLED)
# put text above rectangle
cv2.putText(image, label, (x1, y1-4), cv2.FONT_HERSHEY_COMPLEX_SMALL,
fontScale, Text_colors, bbox_thick, lineType=cv2.LINE_AA)
return image
def bboxes_iou(boxes1, boxes2):
boxes1 = np.array(boxes1)
boxes2 = np.array(boxes2)
boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1])
boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., 3] - boxes2[..., 1])
left_up = np.maximum(boxes1[..., :2], boxes2[..., :2])
right_down = np.minimum(boxes1[..., 2:], boxes2[..., 2:])
inter_section = np.maximum(right_down - left_up, 0.0)
inter_area = inter_section[..., 0] * inter_section[..., 1]
union_area = boxes1_area + boxes2_area - inter_area
ious = np.maximum(1.0 * inter_area / union_area, np.finfo(np.float32).eps)
return ious
def nms(bboxes, iou_threshold, sigma=0.3, method='nms'):
"""
:param bboxes: (xmin, ymin, xmax, ymax, score, class)
Note: soft-nms, https://arxiv.org/pdf/1704.04503.pdf
https://github.com/bharatsingh430/soft-nms
"""
classes_in_img = list(set(bboxes[:, 5]))
best_bboxes = []
for cls in classes_in_img:
cls_mask = (bboxes[:, 5] == cls)
cls_bboxes = bboxes[cls_mask]
# Process 1: Determine whether the number of bounding boxes is greater than 0
while len(cls_bboxes) > 0:
# Process 2: Select the bounding box with the highest score according to socre order A
max_ind = np.argmax(cls_bboxes[:, 4])
best_bbox = cls_bboxes[max_ind]
best_bboxes.append(best_bbox)
cls_bboxes = np.concatenate([cls_bboxes[: max_ind], cls_bboxes[max_ind + 1:]])
# Process 3: Calculate this bounding box A and
# Remain all iou of the bounding box and remove those bounding boxes whose iou value is higher than the threshold
iou = bboxes_iou(best_bbox[np.newaxis, :4], cls_bboxes[:, :4])
weight = np.ones((len(iou),), dtype=np.float32)
assert method in ['nms', 'soft-nms']
if method == 'nms':
iou_mask = iou > iou_threshold
weight[iou_mask] = 0.0
if method == 'soft-nms':
weight = np.exp(-(1.0 * iou ** 2 / sigma))
cls_bboxes[:, 4] = cls_bboxes[:, 4] * weight
score_mask = cls_bboxes[:, 4] > 0.
cls_bboxes = cls_bboxes[score_mask]
return best_bboxes
def postprocess_boxes(pred_bbox, original_image, input_size, score_threshold):
valid_scale=[0, np.inf]
pred_bbox = np.array(pred_bbox)
pred_xywh = pred_bbox[:, 0:4]
pred_conf = pred_bbox[:, 4]
pred_prob = pred_bbox[:, 5:]
# 1. (x, y, w, h) --> (xmin, ymin, xmax, ymax)
pred_coor = np.concatenate([pred_xywh[:, :2] - pred_xywh[:, 2:] * 0.5,
pred_xywh[:, :2] + pred_xywh[:, 2:] * 0.5], axis=-1)
# 2. (xmin, ymin, xmax, ymax) -> (xmin_org, ymin_org, xmax_org, ymax_org)
org_h, org_w = original_image.shape[:2]
resize_ratio = min(input_size / org_w, input_size / org_h)
dw = (input_size - resize_ratio * org_w) / 2
dh = (input_size - resize_ratio * org_h) / 2
pred_coor[:, 0::2] = 1.0 * (pred_coor[:, 0::2] - dw) / resize_ratio
pred_coor[:, 1::2] = 1.0 * (pred_coor[:, 1::2] - dh) / resize_ratio
# 3. clip some boxes those are out of range
pred_coor = np.concatenate([np.maximum(pred_coor[:, :2], [0, 0]),
np.minimum(pred_coor[:, 2:], [org_w - 1, org_h - 1])], axis=-1)
invalid_mask = np.logical_or((pred_coor[:, 0] > pred_coor[:, 2]), (pred_coor[:, 1] > pred_coor[:, 3]))
pred_coor[invalid_mask] = 0
# 4. discard some invalid boxes
bboxes_scale = np.sqrt(np.multiply.reduce(pred_coor[:, 2:4] - pred_coor[:, 0:2], axis=-1))
scale_mask = np.logical_and((valid_scale[0] < bboxes_scale), (bboxes_scale < valid_scale[1]))
# 5. discard boxes with low scores
classes = np.argmax(pred_prob, axis=-1)
scores = pred_conf * pred_prob[np.arange(len(pred_coor)), classes]
score_mask = scores > score_threshold
mask = np.logical_and(scale_mask, score_mask)
coors, scores, classes = pred_coor[mask], scores[mask], classes[mask]
return np.concatenate([coors, scores[:, np.newaxis], classes[:, np.newaxis]], axis=-1)
def detect_image(Yolo, image_path= '',type_image_path = "str_path", output_path = '', input_size=416, show=False, CLASSES=YOLO_COCO_CLASSES, score_threshold=0.3, iou_threshold=0.45, rectangle_colors=''):
if type_image_path == "str_path":
original_image = cv2.imread(image_path)
original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
else:
original_image = Image.open(io.BytesIO(base64.b64decode(image_path)))
original_image = cv2.cvtColor(np.array(original_image), cv2.COLOR_BGR2RGB)
image_data = image_preprocess(np.copy(original_image), [input_size, input_size])
image_data = image_data[np.newaxis, ...].astype(np.float32)
if YOLO_FRAMEWORK == "tf":
pred_bbox = Yolo.predict(image_data)
elif YOLO_FRAMEWORK == "trt":
batched_input = tf.constant(image_data)
result = Yolo(batched_input)
pred_bbox = []
for key, value in result.items():
value = value.numpy()
pred_bbox.append(value)
pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]
pred_bbox = tf.concat(pred_bbox, axis=0)
bboxes = postprocess_boxes(pred_bbox, original_image, input_size, score_threshold)
bboxes = nms(bboxes, iou_threshold, method='nms')
image = draw_bbox(original_image, bboxes, CLASSES=CLASSES, rectangle_colors=rectangle_colors)
# CreateXMLfile("XML_Detections", str(int(time.time())), original_image, bboxes, read_class_names(CLASSES))
if output_path != '': cv2.imwrite(output_path, image)
if show:
# Show the image
cv2.imshow("predicted image", image)
# Load and hold the image
cv2.waitKey(0)
# To close the window after the required kill value was provided
cv2.destroyAllWindows()
return image
def Predict_bbox_mp(Frames_data, Predicted_data, Processing_times):
gpus = tf.config.experimental.list_physical_devices('GPU')
if len(gpus) > 0:
try: tf.config.experimental.set_memory_growth(gpus[0], True)
except RuntimeError: print("RuntimeError in tf.config.experimental.list_physical_devices('GPU')")
Yolo = Load_Yolo_model()
times = []
while True:
if Frames_data.qsize()>0:
image_data = Frames_data.get()
t1 = time.time()
Processing_times.put(time.time())
if YOLO_FRAMEWORK == "tf":
pred_bbox = Yolo.predict(image_data)
elif YOLO_FRAMEWORK == "trt":
batched_input = tf.constant(image_data)
result = Yolo(batched_input)
pred_bbox = []
for key, value in result.items():
value = value.numpy()
pred_bbox.append(value)
pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]
pred_bbox = tf.concat(pred_bbox, axis=0)
Predicted_data.put(pred_bbox)
def postprocess_mp(Predicted_data, original_frames, Processed_frames, Processing_times, input_size, CLASSES, score_threshold, iou_threshold, rectangle_colors, realtime):
times = []
while True:
if Predicted_data.qsize()>0:
pred_bbox = Predicted_data.get()
if realtime:
while original_frames.qsize() > 1:
original_image = original_frames.get()
else:
original_image = original_frames.get()
bboxes = postprocess_boxes(pred_bbox, original_image, input_size, score_threshold)
bboxes = nms(bboxes, iou_threshold, method='nms')
image = draw_bbox(original_image, bboxes, CLASSES=CLASSES, rectangle_colors=rectangle_colors)
times.append(time.time()-Processing_times.get())
times = times[-20:]
ms = sum(times)/len(times)*1000
fps = 1000 / ms
image = cv2.putText(image, "Time: {:.1f}FPS".format(fps), (0, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)
#print("Time: {:.2f}ms, Final FPS: {:.1f}".format(ms, fps))
Processed_frames.put(image)
def Show_Image_mp(Processed_frames, show, Final_frames):
while True:
if Processed_frames.qsize()>0:
image = Processed_frames.get()
Final_frames.put(image)
if show:
cv2.imshow('output', image)
if cv2.waitKey(25) & 0xFF == ord("q"):
cv2.destroyAllWindows()
break
# detect from webcam
def detect_video_realtime_mp(video_path, output_path, input_size=416, show=False, CLASSES=YOLO_COCO_CLASSES, score_threshold=0.3, iou_threshold=0.45, rectangle_colors='', realtime=False):
if realtime:
vid = cv2.VideoCapture(0)
else:
vid = cv2.VideoCapture(video_path)
# by default VideoCapture returns float instead of int
width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(vid.get(cv2.CAP_PROP_FPS))
codec = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(output_path, codec, fps, (width, height)) # output_path must be .mp4
no_of_frames = int(vid.get(cv2.CAP_PROP_FRAME_COUNT))
original_frames = Queue()
Frames_data = Queue()
Predicted_data = Queue()
Processed_frames = Queue()
Processing_times = Queue()
Final_frames = Queue()
p1 = Process(target=Predict_bbox_mp, args=(Frames_data, Predicted_data, Processing_times))
p2 = Process(target=postprocess_mp, args=(Predicted_data, original_frames, Processed_frames, Processing_times, input_size, CLASSES, score_threshold, iou_threshold, rectangle_colors, realtime))
p3 = Process(target=Show_Image_mp, args=(Processed_frames, show, Final_frames))
p1.start()
p2.start()
p3.start()
while True:
ret, img = vid.read()
if not ret:
break
original_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
original_frames.put(original_image)
image_data = image_preprocess(np.copy(original_image), [input_size, input_size])
image_data = image_data[np.newaxis, ...].astype(np.float32)
Frames_data.put(image_data)
while True:
if original_frames.qsize() == 0 and Frames_data.qsize() == 0 and Predicted_data.qsize() == 0 and Processed_frames.qsize() == 0 and Processing_times.qsize() == 0 and Final_frames.qsize() == 0:
p1.terminate()
p2.terminate()
p3.terminate()
break
elif Final_frames.qsize()>0:
image = Final_frames.get()
if output_path != '': out.write(image)
cv2.destroyAllWindows()
def detect_video(Yolo, video_path, output_path, input_size=416, show=False, CLASSES=YOLO_COCO_CLASSES, score_threshold=0.3, iou_threshold=0.45, rectangle_colors=''):
times, times_2 = [], []
vid = cv2.VideoCapture(video_path)
# by default VideoCapture returns float instead of int
width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(vid.get(cv2.CAP_PROP_FPS))
codec = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(output_path, codec, fps, (width, height)) # output_path must be .mp4
while True:
_, img = vid.read()
try:
original_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
except:
break
image_data = image_preprocess(np.copy(original_image), [input_size, input_size])
image_data = image_data[np.newaxis, ...].astype(np.float32)
t1 = time.time()
if YOLO_FRAMEWORK == "tf":
pred_bbox = Yolo.predict(image_data)
elif YOLO_FRAMEWORK == "trt":
batched_input = tf.constant(image_data)
result = Yolo(batched_input)
pred_bbox = []
for key, value in result.items():
value = value.numpy()
pred_bbox.append(value)
t2 = time.time()
pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]
pred_bbox = tf.concat(pred_bbox, axis=0)
bboxes = postprocess_boxes(pred_bbox, original_image, input_size, score_threshold)
bboxes = nms(bboxes, iou_threshold, method='nms')
image = draw_bbox(original_image, bboxes, CLASSES=CLASSES, rectangle_colors=rectangle_colors)
t3 = time.time()
times.append(t2-t1)
times_2.append(t3-t1)
times = times[-20:]
times_2 = times_2[-20:]
ms = sum(times)/len(times)*1000
fps = 1000 / ms
fps2 = 1000 / (sum(times_2)/len(times_2)*1000)
image = cv2.putText(image, "Time: {:.1f}FPS".format(fps), (0, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)
# CreateXMLfile("XML_Detections", str(int(time.time())), original_image, bboxes, read_class_names(CLASSES))
print("Time: {:.2f}ms, Detection FPS: {:.1f}, total FPS: {:.1f}".format(ms, fps, fps2))
if output_path != '': out.write(image)
if show:
cv2.imshow('output', image)
if cv2.waitKey(25) & 0xFF == ord("q"):
cv2.destroyAllWindows()
break
cv2.destroyAllWindows()
# detect from webcam
def detect_realtime(Yolo, output_path, input_size=416, show=False, CLASSES=YOLO_COCO_CLASSES, score_threshold=0.3, iou_threshold=0.45, rectangle_colors=''):
times = []
vid = cv2.VideoCapture(0)
# by default VideoCapture returns float instead of int
width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(vid.get(cv2.CAP_PROP_FPS))
codec = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(output_path, codec, fps, (width, height)) # output_path must be .mp4
while True:
_, frame = vid.read()
try:
original_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
original_frame = cv2.cvtColor(original_frame, cv2.COLOR_BGR2RGB)
except:
break
image_data = image_preprocess(np.copy(original_frame), [input_size, input_size])
image_data = image_data[np.newaxis, ...].astype(np.float32)
t1 = time.time()
if YOLO_FRAMEWORK == "tf":
pred_bbox = Yolo.predict(image_data)
elif YOLO_FRAMEWORK == "trt":
batched_input = tf.constant(image_data)
result = Yolo(batched_input)
pred_bbox = []
for key, value in result.items():
value = value.numpy()
pred_bbox.append(value)
t2 = time.time()
pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]
pred_bbox = tf.concat(pred_bbox, axis=0)
bboxes = postprocess_boxes(pred_bbox, original_frame, input_size, score_threshold)
bboxes = nms(bboxes, iou_threshold, method='nms')
times.append(t2-t1)
times = times[-20:]
ms = sum(times)/len(times)*1000
fps = 1000 / ms
print("Time: {:.2f}ms, {:.1f} FPS".format(ms, fps))
frame = draw_bbox(original_frame, bboxes, CLASSES=CLASSES, rectangle_colors=rectangle_colors)
# CreateXMLfile("XML_Detections", str(int(time.time())), original_frame, bboxes, read_class_names(CLASSES))
image = cv2.putText(frame, "Time: {:.1f}FPS".format(fps), (0, 30),
cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)
if output_path != '': out.write(frame)
if show:
cv2.imshow('output', frame)
if cv2.waitKey(25) & 0xFF == ord("q"):
cv2.destroyAllWindows()
break
cv2.destroyAllWindows()
|
main.py | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: main.py
Description : 运行主函数
Author : JHao
date: 2017/4/1
-------------------------------------------------
Change Activity:
2017/4/1:
-------------------------------------------------
"""
__author__ = 'JHao'
import sys
from multiprocessing import Process
sys.path.append('../')
from Api.ProxyApi import run as ProxyApiRun
from Schedule.ProxyValidSchedule import run as ValidRun
from Schedule.ProxyRefreshSchedule import run as RefreshRun
def run():
p_list = list()
p1 = Process(target=ProxyApiRun, name='ProxyApiRun')
p_list.append(p1)
p2 = Process(target=ValidRun, name='ValidRun')
p_list.append(p2)
p3 = Process(target=RefreshRun, name='RefreshRun')
p_list.append(p3)
for p in p_list:
p.daemon = True
p.start()
for p in p_list:
p.join()
if __name__ == '__main__':
run()
|
decorators.py | #!/usr/bin/env python
# encoding:utf-8
from threading import Thread
from functools import wraps
from flask import abort
from flask.ext.login import current_user
__author__ = 'zhangmm'
def async(fun):
def wrapper(*args, **kwargs):
thr = Thread(target=fun, args=args, kwargs=kwargs)
thr.start()
return wrapper
|
test_testutils.py | # Copyright 2012 National Research Foundation (South African Radio Astronomy Observatory)
# BSD license - see LICENSE for details
from __future__ import absolute_import, division, print_function
from future import standard_library
standard_library.install_aliases() # noqa: E402
import threading
import time
import unittest
import tornado.gen
import tornado.testing
from katcp import Sensor, testutils
def get_sensor(sensor_type, name=None):
if name is None:
name = 'test_%s_sensor' % sensor_type
params = None
if sensor_type in (Sensor.INTEGER, Sensor.FLOAT):
params = [0, 1000]
elif sensor_type == Sensor.DISCRETE:
params = ['value1', 'value2', 'value3']
sensor = Sensor(
sensor_type, name, "Dummy %s Sensor" % sensor_type, "Units",
params)
return sensor
class test_SensorTransitionWaiter(unittest.TestCase):
def test_wait_float_timeout(self):
timeout = 0.1
expected_conditions = (
lambda x: x < 0.7,
lambda x: x >= 0.7,
lambda x: x >= 1,
lambda x: x < 1,
lambda x: x < 0.3)
value_series = (0.5, 0.6, 1, 0.7, 0.299)
def sensor_stream(): # Target for thread that pushes values to DUT
# We are purposefully not adjusting the timestamps (1st 2
# parameters to sensor.set_value()) to check that events
# that come in faster than timer precision are also caught
thread_alive.set()
for val in value_series:
time.sleep(delay_value)
sensor.set_value(val)
# Set up the DUT
sensor = get_sensor(Sensor.FLOAT)
DUT = testutils.SensorTransitionWaiter(sensor, expected_conditions)
# Set up the thread that will push the values to DUT
sensor_thread = threading.Thread(target=sensor_stream)
sensor_thread.daemon = True
thread_alive = threading.Event()
delay_value = 0.005 # Should be fast enough to complete within timeout
thread_alive.clear()
sensor_thread.start()
# wait until the thread starts working
thread_alive.wait(timeout=0.5)
self.assertTrue(DUT.wait(timeout=timeout))
self.assertFalse(DUT.timed_out)
sensor_thread.join()
# Now try it too slow
delay_value = 0.021
DUT = testutils.SensorTransitionWaiter(sensor, expected_conditions)
sensor_thread = threading.Thread(target=sensor_stream)
sensor_thread.daemon = True
thread_alive.clear()
# wait until the thread starts working
sensor_thread.start()
thread_alive.wait(timeout=0.5)
self.assertFalse(DUT.wait(timeout=timeout))
self.assertTrue(DUT.timed_out)
sensor_thread.join()
def test_init_teardown(self):
now = time.time()
sensor = get_sensor(Sensor.INTEGER)
sensor.set_value(0)
# Test that an assertion is raised if the initial value of the
# sensor does not match the first value in the expected
# sequence.
with self.assertRaises(ValueError):
testutils.SensorTransitionWaiter(sensor, (1, 2, 3))
DUT = testutils.SensorTransitionWaiter(sensor, (0, 2, 3))
# Test that we are attached to the sensor
self.assertTrue(DUT._observer in sensor._observers)
self.assertEqual(DUT._observer.update, DUT._sensor_callback)
DUT.teardown()
# Check that the callback is unregistered
self.assertFalse(DUT._observer in sensor._observers)
self.assertTrue(DUT._torn_down)
with self.assertRaises(RuntimeError):
DUT.wait() # should not allow waiting if we're torn down
class test_wait_sensor(unittest.TestCase):
def _wait_sensor(self, vals, val, status):
sensor = get_sensor(Sensor.INTEGER)
sensor.set_value(0, Sensor.NOMINAL)
def set_vals():
time.sleep(0.05)
for v in vals:
if status is None:
sensor.set_value(v)
else:
sensor.set_value(*v)
sensor_thread = threading.Thread(target=set_vals)
# test timeout
self.assertFalse(testutils.wait_sensor(sensor, val, status=status, timeout=0.05))
# Now start setting vals
sensor_thread.start()
self.assertTrue(testutils.wait_sensor(sensor, val, status=status, timeout=1))
def test_values(self):
vals = (1, 2, 0, 3)
self._wait_sensor(vals, 3, status=None)
def test_values_and_status(self):
vals = ((1, Sensor.NOMINAL),
(7, Sensor.WARN),
(2, Sensor.ERROR),
(0, Sensor.ERROR))
self._wait_sensor(vals, 0, status=Sensor.ERROR)
class _test_WaitingMockBase(unittest.TestCase):
DUTClass = None
def test_reset_mock(self):
# skip test run on base clase directly
if not self.DUTClass:
return
# Verify that the call_count and call_args_list variables
# are initially zero, and get cleared by calling reset_mock
DUT = self.DUTClass()
self.assertEqual(DUT.call_count, 0)
self.assertEqual(len(DUT.call_args_list), 0)
DUT()
self.assertEqual(DUT.call_count, 1)
self.assertEqual(len(DUT.call_args_list), 1)
DUT.reset_mock()
self.assertEqual(DUT.call_count, 0)
self.assertEqual(len(DUT.call_args_list), 0)
class test_WaitingMock(_test_WaitingMockBase):
DUTClass = testutils.WaitingMock
def test_assert_wait_call_count_success(self):
# Test the normal case, in which the mock was called
DUT = self.DUTClass()
DUT(123)
DUT.assert_wait_call_count(1, timeout=0.1)
def test_assert_wait_call_count_fail_on_call_count(self):
# Test the negative case, when the mock was not called.
# This should cause an assertion error after the timeout.
DUT = self.DUTClass()
with self.assertRaises(AssertionError):
DUT.assert_wait_call_count(1, timeout=0.01)
def test_assert_wait_call_count_fail_on_call_args(self):
# Synthetic test case where the call_count is correct, but the
# call_args_list has not been updated yet. This might occur if
# the mock call is done in a different thread to the unit test.
# In this case we expect a runtime error after the timeout.
DUT = self.DUTClass()
DUT(123)
DUT.call_args_list = []
with self.assertRaises(RuntimeError):
DUT.assert_wait_call_count(1, timeout=0.1)
class test_AsyncWaitingMock(tornado.testing.AsyncTestCase, _test_WaitingMockBase):
DUTClass = testutils.AsyncWaitingMock
@tornado.testing.gen_test
def test_assert_wait_call_count_success(self):
# Test the normal case, in which the mock was called
DUT = self.DUTClass()
DUT(123)
yield DUT.assert_wait_call_count(1, timeout=0.1)
@tornado.testing.gen_test
def test_assert_wait_call_count_fail_on_call_count(self):
# Test the negative case, when the mock was not called.
# This should cause an assertion error after the timeout.
DUT = self.DUTClass()
with self.assertRaises(AssertionError):
yield DUT.assert_wait_call_count(1, timeout=0.01)
@tornado.testing.gen_test
def test_ioloop_hogging(self):
# Test implementation detail, if the waiting loop forgets to clear
# DUT._call_event after each call, it will go in a "busy waiting" loop
# that blocks the ioloop and prevents the second call (done using
# add_callback) from happening until after assert_wait_call_count()
# times out.
DUT = self.DUTClass()
DUT(1)
self.io_loop.add_callback(DUT, 2)
yield DUT.assert_wait_call_count(2, timeout=0.1)
|
sampler.py | # Copyright (c) 2016-2018 Uber Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division
import logging
import random
import time
import six
from threading import Lock, Thread
from .ioloop_util import PeriodicCallback
from .constants import (
MAX_ID_BITS,
DEFAULT_SAMPLING_INTERVAL,
SAMPLER_TYPE_CONST,
SAMPLER_TYPE_PROBABILISTIC,
SAMPLER_TYPE_RATE_LIMITING,
SAMPLER_TYPE_LOWER_BOUND,
)
from .metrics import Metrics, LegacyMetricsFactory
from .utils import ErrorReporter
from .rate_limiter import RateLimiter
default_logger = logging.getLogger('jaeger_tracing')
SAMPLER_TYPE_TAG_KEY = 'sampler.type'
SAMPLER_PARAM_TAG_KEY = 'sampler.param'
DEFAULT_SAMPLING_PROBABILITY = 0.001
DEFAULT_LOWER_BOUND = 1.0 / (10.0 * 60.0) # sample once every 10 minutes
DEFAULT_MAX_OPERATIONS = 2000
STRATEGIES_STR = 'perOperationStrategies'
OPERATION_STR = 'operation'
DEFAULT_LOWER_BOUND_STR = 'defaultLowerBoundTracesPerSecond'
PROBABILISTIC_SAMPLING_STR = 'probabilisticSampling'
SAMPLING_RATE_STR = 'samplingRate'
DEFAULT_SAMPLING_PROBABILITY_STR = 'defaultSamplingProbability'
OPERATION_SAMPLING_STR = 'operationSampling'
MAX_TRACES_PER_SECOND_STR = 'maxTracesPerSecond'
RATE_LIMITING_SAMPLING_STR = 'rateLimitingSampling'
STRATEGY_TYPE_STR = 'strategyType'
PROBABILISTIC_SAMPLING_STRATEGY = 'PROBABILISTIC'
RATE_LIMITING_SAMPLING_STRATEGY = 'RATE_LIMITING'
class Sampler(object):
"""
Sampler is responsible for deciding if a particular span should be
"sampled", i.e. recorded in permanent storage.
"""
def __init__(self, tags=None):
self._tags = tags
def is_sampled(self, trace_id, operation=''):
raise NotImplementedError()
def close(self):
raise NotImplementedError()
def __eq__(self, other):
return (
isinstance(other, self.__class__) and self.__dict__ == other.__dict__
)
def __ne__(self, other):
return not self.__eq__(other)
class ConstSampler(Sampler):
"""ConstSampler always returns the same decision."""
def __init__(self, decision):
super(ConstSampler, self).__init__(
tags={
SAMPLER_TYPE_TAG_KEY: SAMPLER_TYPE_CONST,
SAMPLER_PARAM_TAG_KEY: decision,
}
)
self.decision = decision
def is_sampled(self, trace_id, operation=''):
return self.decision, self._tags
def close(self):
pass
def __str__(self):
return 'ConstSampler(%s)' % self.decision
class ProbabilisticSampler(Sampler):
"""
A sampler that randomly samples a certain percentage of traces specified
by the samplingRate, in the range between 0.0 and 1.0.
It relies on the fact that new trace IDs are 64bit random numbers
themselves, thus making the sampling decision without generating a new
random number, but simply calculating if traceID < (samplingRate * 2^64).
Note that we actually ignore (zero out) the most significant bit.
"""
def __init__(self, rate):
super(ProbabilisticSampler, self).__init__(
tags={
SAMPLER_TYPE_TAG_KEY: SAMPLER_TYPE_PROBABILISTIC,
SAMPLER_PARAM_TAG_KEY: rate,
}
)
assert 0.0 <= rate <= 1.0, 'Sampling rate must be between 0.0 and 1.0'
self.rate = rate
self.max_number = 1 << MAX_ID_BITS
self.boundary = rate * self.max_number
def is_sampled(self, trace_id, operation=''):
return trace_id < self.boundary, self._tags
def close(self):
pass
def __str__(self):
return 'ProbabilisticSampler(%s)' % self.rate
class RateLimitingSampler(Sampler):
"""
Samples at most max_traces_per_second. The distribution of sampled
traces follows burstiness of the service, i.e. a service with uniformly
distributed requests will have those requests sampled uniformly as well,
but if requests are bursty, especially sub-second, then a number of
sequential requests can be sampled each second.
"""
def __init__(self, max_traces_per_second=10):
super(RateLimitingSampler, self).__init__()
self.rate_limiter = None
self._init(max_traces_per_second)
def _init(self, max_traces_per_second):
assert max_traces_per_second >= 0, \
'max_traces_per_second must not be negative'
self._tags = {
SAMPLER_TYPE_TAG_KEY: SAMPLER_TYPE_RATE_LIMITING,
SAMPLER_PARAM_TAG_KEY: max_traces_per_second,
}
self.traces_per_second = max_traces_per_second
max_balance = max(self.traces_per_second, 1.0)
if not self.rate_limiter:
self.rate_limiter = RateLimiter(
credits_per_second=self.traces_per_second,
max_balance=max_balance
)
else:
self.rate_limiter.update(max_traces_per_second, max_balance)
def is_sampled(self, trace_id, operation=''):
return self.rate_limiter.check_credit(1.0), self._tags
def close(self):
pass
def __eq__(self, other):
"""The last_tick and balance fields can be different"""
if not isinstance(other, self.__class__):
return False
d1 = dict(self.rate_limiter.__dict__)
d2 = dict(other.rate_limiter.__dict__)
d1['balance'] = d2['balance']
d1['last_tick'] = d2['last_tick']
return d1 == d2
def update(self, max_traces_per_second):
if self.traces_per_second == max_traces_per_second:
return False
self._init(max_traces_per_second)
return True
def __str__(self):
return 'RateLimitingSampler(%s)' % self.traces_per_second
class GuaranteedThroughputProbabilisticSampler(Sampler):
"""
A sampler that leverages both ProbabilisticSampler and RateLimitingSampler.
The RateLimitingSampler is used as a guaranteed lower bound sampler such
that every operation is sampled at least once in a time interval defined by
the lower_bound. ie a lower_bound of 1.0 / (60 * 10) will sample an
operation at least once every 10 minutes.
The ProbabilisticSampler is given higher priority when tags are emitted,
ie. if is_sampled() for both samplers return true, the tags for
ProbabilisticSampler will be used.
"""
def __init__(self, operation, lower_bound, rate):
super(GuaranteedThroughputProbabilisticSampler, self).__init__(
tags={
SAMPLER_TYPE_TAG_KEY: SAMPLER_TYPE_LOWER_BOUND,
SAMPLER_PARAM_TAG_KEY: rate,
}
)
self.probabilistic_sampler = ProbabilisticSampler(rate)
self.lower_bound_sampler = RateLimitingSampler(lower_bound)
self.operation = operation
self.rate = rate
self.lower_bound = lower_bound
def is_sampled(self, trace_id, operation=''):
sampled, tags = \
self.probabilistic_sampler.is_sampled(trace_id, operation)
if sampled:
self.lower_bound_sampler.is_sampled(trace_id, operation)
return True, tags
sampled, _ = self.lower_bound_sampler.is_sampled(trace_id, operation)
return sampled, self._tags
def close(self):
self.probabilistic_sampler.close()
self.lower_bound_sampler.close()
def update(self, lower_bound, rate):
# (NB) This function should only be called while holding a Write lock.
if self.rate != rate:
self.probabilistic_sampler = ProbabilisticSampler(rate)
self.rate = rate
self._tags = {
SAMPLER_TYPE_TAG_KEY: SAMPLER_TYPE_LOWER_BOUND,
SAMPLER_PARAM_TAG_KEY: rate,
}
if self.lower_bound != lower_bound:
self.lower_bound_sampler.update(lower_bound)
self.lower_bound = lower_bound
def __str__(self):
return 'GuaranteedThroughputProbabilisticSampler(%s, %f, %f)' \
% (self.operation, self.rate, self.lower_bound)
class AdaptiveSampler(Sampler):
"""
A sampler that leverages both ProbabilisticSampler and RateLimitingSampler
via the GuaranteedThroughputProbabilisticSampler. This sampler keeps track
of all operations and delegates calls the the respective
GuaranteedThroughputProbabilisticSampler.
"""
def __init__(self, strategies, max_operations):
super(AdaptiveSampler, self).__init__()
samplers = {}
for strategy in strategies.get(STRATEGIES_STR, []):
operation = strategy.get(OPERATION_STR)
sampler = GuaranteedThroughputProbabilisticSampler(
operation,
strategies.get(DEFAULT_LOWER_BOUND_STR, DEFAULT_LOWER_BOUND),
get_sampling_probability(strategy)
)
samplers[operation] = sampler
self.samplers = samplers
self.default_sampler = \
ProbabilisticSampler(strategies.get(DEFAULT_SAMPLING_PROBABILITY_STR,
DEFAULT_SAMPLING_PROBABILITY))
self.default_sampling_probability = \
strategies.get(DEFAULT_SAMPLING_PROBABILITY_STR, DEFAULT_SAMPLING_PROBABILITY)
self.lower_bound = strategies.get(DEFAULT_LOWER_BOUND_STR, DEFAULT_LOWER_BOUND)
self.max_operations = max_operations
def is_sampled(self, trace_id, operation=''):
sampler = self.samplers.get(operation)
if not sampler:
if len(self.samplers) >= self.max_operations:
return self.default_sampler.is_sampled(trace_id, operation)
sampler = GuaranteedThroughputProbabilisticSampler(
operation,
self.lower_bound,
self.default_sampling_probability
)
self.samplers[operation] = sampler
return sampler.is_sampled(trace_id, operation)
return sampler.is_sampled(trace_id, operation)
def update(self, strategies):
# (NB) This function should only be called while holding a Write lock.
for strategy in strategies.get(STRATEGIES_STR, []):
operation = strategy.get(OPERATION_STR)
lower_bound = strategies.get(DEFAULT_LOWER_BOUND_STR, DEFAULT_LOWER_BOUND)
sampling_rate = get_sampling_probability(strategy)
sampler = self.samplers.get(operation)
if not sampler:
sampler = GuaranteedThroughputProbabilisticSampler(
operation,
lower_bound,
sampling_rate
)
self.samplers[operation] = sampler
else:
sampler.update(lower_bound, sampling_rate)
self.lower_bound = strategies.get(DEFAULT_LOWER_BOUND_STR, DEFAULT_LOWER_BOUND)
if self.default_sampling_probability != strategies.get(DEFAULT_SAMPLING_PROBABILITY_STR,
DEFAULT_SAMPLING_PROBABILITY):
self.default_sampling_probability = \
strategies.get(DEFAULT_SAMPLING_PROBABILITY_STR, DEFAULT_SAMPLING_PROBABILITY)
self.default_sampler = \
ProbabilisticSampler(self.default_sampling_probability)
def close(self):
for _, sampler in six.iteritems(self.samplers):
sampler.close()
def __str__(self):
return 'AdaptiveSampler(%f, %f, %d)' \
% (self.default_sampling_probability, self.lower_bound,
self.max_operations)
class RemoteControlledSampler(Sampler):
"""Periodically loads the sampling strategy from a remote server."""
def __init__(self, channel, service_name, **kwargs):
"""
:param channel: channel for communicating with jaeger-agent
:param service_name: name of this application
:param kwargs: optional parameters
- init_sampler: initial value of the sampler,
else ProbabilisticSampler(0.001)
- sampling_refresh_interval: interval in seconds for polling
for new strategy
- logger: Logger instance
- metrics: metrics facade, used to emit metrics on errors.
This parameter has been deprecated, please use
metrics_factory instead.
- metrics_factory: used to generate metrics for errors
- error_reporter: ErrorReporter instance
- max_operations: maximum number of unique operations the
AdaptiveSampler will keep track of
:param init:
:return:
"""
super(RemoteControlledSampler, self).__init__()
self._channel = channel
self.service_name = service_name
self.logger = kwargs.get('logger', default_logger)
self.sampler = kwargs.get('init_sampler')
self.sampling_refresh_interval = \
kwargs.get('sampling_refresh_interval') or DEFAULT_SAMPLING_INTERVAL
self.metrics_factory = kwargs.get('metrics_factory') \
or LegacyMetricsFactory(kwargs.get('metrics') or Metrics())
self.metrics = SamplerMetrics(self.metrics_factory)
self.error_reporter = kwargs.get('error_reporter') or \
ErrorReporter(Metrics())
self.max_operations = kwargs.get('max_operations') or \
DEFAULT_MAX_OPERATIONS
if not self.sampler:
self.sampler = ProbabilisticSampler(DEFAULT_SAMPLING_PROBABILITY)
else:
self.sampler.is_sampled(0) # assert we got valid sampler API
self.sample_lock = Lock()
self._polling_lock = Lock()
self.running = True
self.periodic = None
self._init_polling_thread = None
self._polling_initialized = False
def is_sampled(self, trace_id, operation=''):
if not self._polling_initialized:
with self._polling_lock:
if self.running and self._init_polling_thread is None:
self._init_polling_thread = Thread(target=self._init_polling)
self._init_polling_thread.daemon = True
self._init_polling_thread.start()
self._polling_initialized = True
with self.sample_lock:
sampled = self.sampler.is_sampled(trace_id, operation)
return sampled
def _init_polling(self):
"""
Bootstrap polling for sampling strategy.
To avoid spiky traffic from the samplers, we use a random delay
before the first poll.
"""
if not self.running:
return
r = random.Random()
delay = r.random() * self.sampling_refresh_interval
self.logger.info(
'Delaying sampling strategy polling by %d sec', delay)
time.sleep(delay)
self._delayed_polling()
def _delayed_polling(self):
if not self.running:
return
if self.periodic is None:
self.periodic = self._create_periodic_callback()
self.periodic.start() # start the periodic cycle
self.logger.info(
'Tracing sampler started with sampling refresh '
'interval %d sec', self.sampling_refresh_interval)
def _create_periodic_callback(self):
return PeriodicCallback(
callback=self._poll_sampling_manager,
# convert interval to milliseconds
callback_time=self.sampling_refresh_interval * 1000)
def _sampling_request_callback(self, response, exc):
if exc:
self.metrics.sampler_query_failure(1)
self.error_reporter.error('Fail to get sampling strategy from jaeger-agent: %s', exc)
return
try:
sampling_strategies_response = response.json()
self.metrics.sampler_retrieved(1)
except Exception as e:
self.metrics.sampler_query_failure(1)
self.error_reporter.error(
'Fail to parse sampling strategy '
'from jaeger-agent: %s [%s]', e, response.content)
return
self._update_sampler(sampling_strategies_response)
self.logger.debug('Tracing sampler set to %s', self.sampler)
def _update_sampler(self, response):
with self.sample_lock:
try:
if response.get(OPERATION_SAMPLING_STR):
self._update_adaptive_sampler(response.get(OPERATION_SAMPLING_STR))
else:
self._update_rate_limiting_or_probabilistic_sampler(response)
except Exception as e:
self.metrics.sampler_update_failure(1)
self.error_reporter.error(
'Fail to update sampler'
'from jaeger-agent: %s [%s]', e, response)
def _update_adaptive_sampler(self, per_operation_strategies):
if isinstance(self.sampler, AdaptiveSampler):
self.sampler.update(per_operation_strategies)
else:
self.sampler = AdaptiveSampler(per_operation_strategies, self.max_operations)
self.metrics.sampler_updated(1)
def _update_rate_limiting_or_probabilistic_sampler(self, response):
s_type = response.get(STRATEGY_TYPE_STR)
new_sampler = self.sampler
if s_type == PROBABILISTIC_SAMPLING_STRATEGY:
sampling_rate = get_sampling_probability(response)
new_sampler = ProbabilisticSampler(rate=sampling_rate)
elif s_type == RATE_LIMITING_SAMPLING_STRATEGY:
mtps = get_rate_limit(response)
if mtps < 0 or mtps >= 500:
raise ValueError(
'Rate limiting parameter not in [0, 500) range: %s' % mtps)
if isinstance(self.sampler, RateLimitingSampler):
if self.sampler.update(max_traces_per_second=mtps):
self.metrics.sampler_updated(1)
else:
new_sampler = RateLimitingSampler(max_traces_per_second=mtps)
else:
raise ValueError('Unsupported sampling strategy type: %s' % s_type)
if self.sampler != new_sampler:
self.sampler = new_sampler
self.metrics.sampler_updated(1)
def _poll_sampling_manager(self):
self.logger.debug('Requesting tracing sampler refresh')
sampling_strategy_response = None
e = None
try:
sampling_strategy_response = self._channel.request_sampling_strategy(self.service_name)
except Exception as exc:
e = exc
self._sampling_request_callback(sampling_strategy_response, e)
def close(self):
self.running = False
if not self._polling_initialized:
return
with self._polling_lock:
if self.periodic is not None:
self.periodic.stop()
self.periodic = None
if self._init_polling_thread is not None:
self._init_polling_thread.join()
self._init_polling_thread = None
self._polling_initialized = False
def get_sampling_probability(strategy=None):
if not strategy:
return DEFAULT_SAMPLING_PROBABILITY
probability_strategy = strategy.get(PROBABILISTIC_SAMPLING_STR)
if not probability_strategy:
return DEFAULT_SAMPLING_PROBABILITY
return probability_strategy.get(SAMPLING_RATE_STR, DEFAULT_SAMPLING_PROBABILITY)
def get_rate_limit(strategy=None):
if not strategy:
return DEFAULT_LOWER_BOUND
rate_limit_strategy = strategy.get(RATE_LIMITING_SAMPLING_STR)
if not rate_limit_strategy:
return DEFAULT_LOWER_BOUND
return rate_limit_strategy.get(MAX_TRACES_PER_SECOND_STR, DEFAULT_LOWER_BOUND)
class SamplerMetrics(object):
"""Sampler specific metrics."""
def __init__(self, metrics_factory):
self.sampler_retrieved = \
metrics_factory.create_counter(name='jaeger:sampler_queries', tags={'result': 'ok'})
self.sampler_query_failure = \
metrics_factory.create_counter(name='jaeger:sampler_queries', tags={'result': 'err'})
self.sampler_updated = \
metrics_factory.create_counter(name='jaeger:sampler_updates', tags={'result': 'ok'})
self.sampler_update_failure = \
metrics_factory.create_counter(name='jaeger:sampler_updates', tags={'result': 'err'})
|
contentSpanExtractor.py | import sys
import os
from corenlp_xml_reader import AnnotatedText as A
#from intermediaries.nlpReaders.annotated_text import AnnotatedText as A
from intermediaries.nlpReaders.parc_reader import AnnotatedText as B
from parc_reader import ParcCorenlpReader as P
from nltk.tree import *
import csv
import multiprocessing
from multiprocessing import Manager
#fixes all the omnipresent unicode issues
print sys.getdefaultencoding()
reload(sys)
sys.setdefaultencoding('utf-8')
#change this if you would only like to do a certain number of files, useful for testing
maxNumFiles = 1000
#base dir for all data files
data_dir = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '../..', 'data/'))
#store the WordNet generated lists of hyponyms
with open(data_dir + '/peopleHyponyms.csv', 'rb') as f:
reader = csv.reader(f)
peopleHyponyms = list(reader)
with open(data_dir + '/orgHyponyms.csv', 'rb') as f:
reader = csv.reader(f)
orgHyponyms = list(reader)
with open(data_dir + '/nounCues.csv', 'rb') as f:
reader = csv.reader(f)
nounCues = list(reader)
peopleHyponyms = peopleHyponyms[0]
orgHyponyms = orgHyponyms[0]
nounCues = nounCues[0]
#gets datapath, creates a list of files and any nested files (only goes down by one subdirectory)
def openDirectory(datapath):
listOfFiles = []
for item in os.listdir(datapath):
if os.path.isdir(os.path.join(datapath, item)):
item = os.path.join(datapath, item)
for newItem in os.listdir(item):
newItem = os.path.join(item, newItem)
listOfFiles.append(newItem)
elif os.path.isfile(os.path.join(datapath, item)):
item = os.path.join(datapath, item)
listOfFiles.append(item)
return listOfFiles
#open verb file, extract what we need and create a verbs list
def openVerbCues(verbCuesFile):
verbsList = []
with open(os.path.join(data_dir, verbCuesFile), 'rb') as f:
reader = csv.reader(f)
verbsList = list(reader)
newVerbsList = []
for indx, verb in enumerate(verbsList):
metadata = verb[1].split(';')
sentID = metadata[0]
tokID = metadata[1]
fileName = metadata[2]
newVerbsList.append([verb[0], sentID, tokID, fileName, verb[2]])
return newVerbsList
def chunks(l, n):
n = max(1, n)
return (l[i:i+n] for i in xrange(0, len(l), n))
def workerFunction(myFile, listOfAnnotatedFiles, listOfRawFiles, output, verbCuesFile, return_list):
flagNoLabels = False
files = len(listOfNLPFiles)
filename = myFile.split('/')[-1]
fileNoXML = filename.split('.xml')[0]
print filename
myAnnotatedFile = None
#extract the PARC filename that match the title of the NLP filename
myAnnotatedFile = [s for s in listOfAnnotatedFiles if filename in s]
myRawFile = [s for s in listOfRawFiles if fileNoXML in s][0]
print myAnnotatedFile
if len(myAnnotatedFile) == 1:
myAnnotatedFile = myAnnotatedFile[0]
flagNoLabels = True
else:
#didn't find a file
print 'error opening Annotated File'
return return_list
print('opening file: ' + myFile + ' ' + str(j) + ' out of ' + str(files))
#extract the verbs whose metadata filename matches this NLP file
specificFileVerbs = []
for verb in verbList:
if (verb[3] == filename):
specificFileVerbs.append(verb)
#open the file, extract the features and return all the rows
fileRows = openFile(myFile, myAnnotatedFile, myRawFile, specificFileVerbs)
return_list += fileRows
#get the files, open them, extract verbs and features and create a large array of rows
def findFiles(listOfNLPFiles, listOfAnnotatedFiles, listOfRawFiles, output, verbCuesFile):
verbList = openVerbCues(verbCuesFile)
splitLists = list(chunks(coreNlPFiles, len(coreNlPFiles)/10))
j = 0
lastList = splitLists[-1]
del splitLists[-1]
lengthLists = len(splitLists[0])
jobs = []
manager = Manager()
return_list = manager.list()
if listOfAnnotatedFiles == None:
flagNoLabels = True
else:
flagNoLabels = False
#first lists are all equally sized, pick one from each at each iteration
for i in range(lengthLists):
if i == -1:
break
for thisList in splitLists:
myFile = thisList[i]
p = multiprocessing.Process(target = workerFunction, args=(myFile, listOfAnnotatedFiles, listOfRawFiles, output, verbCuesFile, return_list))
jobs.append(p)
p.start()
#append the files from last list (remainder of total files divided by 10)
for myFile in lastList:
p = multiprocessing.Process(target = workerFunction, args=(myFile, listOfAnnotatedFiles, listOfRawFiles, output, verbCuesFile, return_list))
jobs.append(p)
p.start()
for proc in jobs:
proc.join()
open(os.path.join(data_dir, output), 'w').close()
writeToTXT(return_list, os.path.join(data_dir, output), flagNoLabels)
def openFile(coreNLPFileName, annotatedFileNamnscccccce, raw_file, verbList):
allrows = []
#open annotated if it exists
if annotatedFileName != None:
try:
parc_xml = open(annotatedFileName).read()
corenlp_xml = open(coreNLPFileName).read()
raw_text = open(raw_file).read()
annotated_text = A(corenlp_xml)
article = P(corenlp_xml, parc_xml, raw_text)
except:
print 'error opening file'
return rows
else:
parc_xml = None
corenlp_xml = open(coreNLPFileName).read()
raw_text = open(raw_file).read()
annotated_text = A(corenlp_xml)
article = P(corenlp_xml, parc_xml, raw_text)
filename = coreNLPFileName.split('/')[-1]
rows = findFeatures(filename, article, annotated_text, verbList, annotatedFileName)
allrows += rows
return rows, article
def writeToTXT(rows, filename, flagNoLabels):
#if the data is unlabelled, we create a second metadata file that stores the word
#as well as the filename and sentence ID
#this file will be used to reconstitute the spans once CRFsuite gets through them
if flagNoLabels == True:
newRows = []
metadataRows = []
token = ''
for row in rows:
row = row.split('\t')
metadata = row[-1]
for column in row:
if 'word[0]=' in column and 'word[-1]|word[0]=' not in column:
token = column
metadataRows.append(metadata + '\t' + token)
del row[-1]
row = '\t'.join(row)
newRows.append(row)
rows = newRows
#make a new filename with METADATA in it
fileRow = filename.split('/')
thisfile = fileRow[-1]
del fileRow[-1]
thisfile = 'METADATA' + thisfile
fileRow.append(thisfile)
metafile = '/'.join(fileRow)
with open(metafile, 'w') as myfile:
for row in metadataRows:
myfile.write(row + '\n')
myfile.close()
else:
newRows = []
for row in rows:
row = row.split('\t')
del row[-1]
row = '\t'.join(row)
newRows.append(row)
rows = newRows
#write all the tokens and their features to a txt
with open(filename, 'w') as myfile:
for row in rows:
myfile.write(row + '\n')
myfile.close()
print '\nData written to ' + filename + '\n'
#gather all the features and create rows
def findFeatures(filename, article, corenlp_xml, verbsList, annotatedFileName):
print filename
rows = []
#find the constituency parse of the sentences
listOfParse = []
sent_tags = corenlp_xml.soup.find('sentences').find_all('sentence')
for s in sent_tags:
listOfParse.append(s.find('parse').text)
i = 0
print('extracting features ......')
openQuotes = 'false'
lastLabel = 'O'
#begin extracting features
for sentence in article.sentences:
lengthOfSentence = len(sentence['tokens'])
idOfSentence = sentence['id']
currentSentPers = 'false'
beginningQuote = 'false'
parseTree = listOfParse[i]
i = i + 1
#these are the features that will stay the same across each token in the sentence
#e.g. containsOrganization, containsNamedEntity etc.
#returns the array for this sentence of tokens, pos, lemma which will be used to
#constitute the token based features
rowSentFeats = ''
tokenArray, posArray, lemmaArray, peopleHyponym, orgHyponym, rowSentFeats = \
getSentenceFeatures(sentence, rowSentFeats)
#get verb cue, sentence wide features, e.g. containsVerbCue, verbCueNearTheEnd?
rowSentFeats = getVerbListSentenceFeatures(sentence, verbsList, rowSentFeats)
#rowSentFeats now contains a string that looks like
#'containsOrg='True'\tcontainsVerbCue='True'\t.....'
prevSyntactic = ''
for token in sentence['tokens']:
row = rowSentFeats
word = str(token['word'])
pos = str(token['pos'])
lemma = str(token['lemma'])
idOfToken = token['id']
if annotatedFileName != None:
#assign labels
label = token['attribution']
role = token['role']
if label == None:
row = 'O\t' + row
lastLabel = 'O'
elif role == 'content' and lastLabel == 'O':
row = 'B\t' + row
lastLabel = 'B'
elif role == 'content' and lastLabel == 'B':
row = 'I\t' + row
lastLabel = 'I'
elif role == 'content':
row = 'I\t' + row
lastLabel = 'I'
else:
row = 'O\t' + row
lastLabel = 'O'
else:
row = '\t' + row
if "''" in str(token['word']):
openQuotes = 'false'
#append the features
row += 'sentenceLength=' + str(lengthOfSentence) + '\t'
row = getTokenFeatures(idOfToken, tokenArray, row, 'word')
row = getTokenFeatures(idOfToken, posArray, row, 'pos')
row = getTokenFeatures(idOfToken, lemmaArray, row, 'lemma')
row = getTokenPairs(idOfToken, tokenArray, row, 'word')
row = getTokenPairs(idOfToken, posArray, row, 'pos')
row = getTokenPairs(idOfToken, lemmaArray, row, 'lemma')
row = findRelations(token, row)
for (idHypo, hyponym) in peopleHyponym:
row += 'personHyponym[' + str(idHypo - idOfToken) + ']=' + hyponym + '\t'
for (idHypo, hyponym) in orgHyponym:
row += 'organizationHyponym[' + str(idHypo - idOfToken) + ']=' + hyponym + '\t'
#the inside quote labels
if openQuotes == 'true' and beginningQuote == 'true':
row += "insidequotes='true'\t"
if "``" in str(token['word']):
openQuotes = 'true'
beginningQuote = 'true'
row = getConstituentLabels(parseTree, token, sentence, row)
prevSyntactic, row = getSyntactic(parseTree, token, sentence, row, verbsList, prevSyntactic)
row += 'filename=' + filename + '\tsentenceID=' + str(idOfSentence) + '\ttokenID=' + str(idOfToken)
rows.append(row)
return rows
#get verbCue sentence wide features
def getVerbListSentenceFeatures(sentence, verbs, rowSentFeats):
containsVerbCue = False
verbCueNearEnd = False
sentenceID = sentence['id']
sentenceLen = len(sentence['tokens'])
nearEnd = sentenceLen - min(4, sentenceLen/2)
for verb in verbs:
if str(verb[1]) == str(sentenceID):
sentVerb = sentence['tokens'][int(verb[2])]['word']
if sentVerb == verb[0]:
if verb[4] == 'Y':
containsVerbCue = True
rowSentFeats += '''containsVerbCue='true'\t'''
if int(verb[2]) >= nearEnd:
rowSentFeats += '''verbCueNearEnd='true'\t'''
return rowSentFeats
#identifies which relations the token has with its parents and children
#appends seperate features for the relation as well as the relation with the word itself
def findRelations(token, row):
listRelations = ['acl', 'acl:relcl', 'advcl', 'advmod', 'amod', 'appos', 'aux', 'auxpass', 'case', 'cc', 'cc:preconj',
'ccomp', 'compound', 'compound:prt', 'conj', 'cop', 'csubj', 'csubjpass', 'dep', 'det', 'det:predet',
'discourse', 'dislocated', 'dobj', 'expl', 'foreign', 'goeswith', 'iobj', 'list', 'mark', 'mwe', 'name',
'neg', 'nmod', 'nmod:npmod', 'nmod:poss', 'nmod:tmod', 'nsubj', 'nsubjpass', 'nummod', 'parataxis',
'punct', 'remnant', 'reparandum', 'root', 'vocative', 'xcomp']
if (token.has_key('parents')):
for parents in token['parents']:
relation, parent = parents
if relation in listRelations:
row += 'p-Relation=' + relation + '\t'
row += 'p-Relation|p-token=' + relation + '|' + parent['word'] + '\t'
else:
rel = relation.split(':')
row += 'p-Relation=' + rel[0] + '\t'
row += 'p-Relation|p-token=' + rel[0] + '|' + parent['word'] + '\t'
if (token.has_key('children')):
for aChild in token['children']:
relation, child = aChild
if relation in listRelations:
row += 'c-Relation=' + relation + '\t'
row += 'c-Relation|c-token=' + relation + '|' + child['word'] + '\t'
else:
rel = relation.split(':')
row += 'c-Relation=' + rel[0] + '\t'
row += 'c-Relation|c-token=' + rel[0] + '|' + child['word'] + '\t'
return row
#gets individual features, position indexed
#part of speech, lemma, word
def getTokenFeatures(idOfToken, array, row, name):
bottomBound = -5
if idOfToken < 5:
bottomBound = 0 - idOfToken
topBound = len(array) - idOfToken
if topBound > 5:
topBound = 6
j = idOfToken
while (bottomBound < topBound):
row += name + '[' + str(bottomBound) + ']=' + array[j + bottomBound] + '\t'
bottomBound = bottomBound + 1
return row
#gets the pairs of features from -5 to 5, position indexed
#works for PartOfSpeech, Lemma, Word
def getTokenPairs(idOfToken, array, row, name):
bottomBound = -5
if idOfToken < 5:
bottomBound = 0 - idOfToken
topBound = len(array) - idOfToken
if topBound > 5:
topBound = 6
j = idOfToken
while (bottomBound < topBound - 1):
row += name + '[' + str(bottomBound) + ']|' + name + '[' + str(bottomBound + 1) \
+ ']=' + array[j + bottomBound] + '|' + array[j + bottomBound + 1] + '\t'
bottomBound = bottomBound + 1
return row
#gets a series of trues and falses depending on whether the sentence contains any
#of the key features
def getSentenceFeatures(sentence, row):
tokenArray = []
posArray = []
lemmaArray = []
peopleHyponym = []
orgHyponym = []
foundPerson=False
foundOrganization=False
foundPronoun=False
foundQuotes=False
foundAccording = False
possibleNounCue = False
foundAny = False
for token in sentence['tokens']:
namedEnt = str(token['ner'])
if (namedEnt == 'PERSON' and foundPerson==False):
row += '''containsPerson='true'\t'''
foundPerson = True
elif (namedEnt == 'ORGANIZATION' and foundOrganization==False):
row += '''containsOrganization='true'\t'''
foundOrganization = True
pos = str(token['pos'])
if 'PRP' in pos and foundPronoun==False:
row += '''containsPronoun='true'\t'''
foundPronoun=True
word = str(token['word'])
if "''" in word and foundQuotes==False:
row += '''containsQuotes='true'\t'''
foundQuotes=True
tokenArray = tokenArray + [word]
posArray = posArray + [pos]
lemmaArray = lemmaArray + [str(token['lemma'])]
#get positions of possible hyponyms within sentence
if word.lower() in peopleHyponyms:
peopleHyponym.append((token['id'], word))
if word.lower() in orgHyponyms:
orgHyponym.append((token['id'], word))
if (word.lower() != 'to' and foundAccording == True):
foundAccording = False
if (word.lower() == 'according'):
foundAccording = True
if (word.lower() == 'to' and foundAccording == True):
row += '''containsAccordingTo='true'\t'''
foundAccording = False
if foundPerson == True or foundOrganization == True or foundPronoun == True or foundQuotes == True or foundAccording == True:
row += '''foundAnySentenceFeatures='true'\t'''
foundAny = True
#if word.lower() in nounCues and '''containsNounCue='true''' not in row:
# row += '''containsNounCue='true'\t'''
return tokenArray, posArray, lemmaArray, peopleHyponym, orgHyponym, row
#use the parse tree to set up finding the constituencies
def getConstituentLabels(parseTree, token, sentence, row):
subTree = sentence['parse']
listOfWords = []
listofConstituences = getPaths(subTree, listOfWords, token, sentence)
if (listofConstituences != None):
for (lab, dep) in listofConstituences:
row += 'const=(' + lab + ',' + str(dep) + ')\t'
return row
#use a stack, go through each word
def getPaths(treeDict, listOfWords, token, sentence):
targetWord = str(token['word'])
word = treeDict['word']
s = Stack()
s.push(treeDict)
currIdentity = len(sentence['tokens'])
while not (s.isEmpty()):
currTreeDict = s.pop()
thisWord = currTreeDict['word']
if thisWord != None:
currIdentity = currIdentity - 1
#if we found the token's word
if thisWord == targetWord and currIdentity == token['id']:
OGdepth = currTreeDict['depth']
parent = currTreeDict['parent']
#finding each parent and their constituents
if parent.has_key('depth') and parent['depth'] != 0:
while (parent['depth'] != 1):
code = str(parent['code'])
depth = parent['depth'] - 1
constTuple = (code, depth)
parent = parent['parent']
listOfWords.append(constTuple)
if len(listOfWords) == OGdepth - 2:
myList = listOfWords
return myList
else:
return listOfWords
#push all the children onto the stack
else:
for child in currTreeDict['children']:
s.push(child)
#use the parse tree to find all the syntactic info
def getSyntactic(parseTree, token, sentence, row, verbsList, prevSyntactic):
targetWord = str(token['word'])
idOfWord = token['id']
for item in sentence['tokens']:
pos = item['pos']
if '(' in item['word']:
parseTree = parseTree.replace('(' + pos + ' ()', '(' + pos + ' -LRB-)')
elif ')' in item['word']:
parseTree = parseTree.replace('(' + pos + ' ))', '(' + pos + ' -RRB-)')
tree = ParentedTree.fromstring(parseTree)
#reformat the text to match properly
if targetWord == '(':
targetWord = '-LRB-'
if targetWord == ')':
targetWord = '-RRB-'
#get the indices for all the leaves that match this token
indices = [i for i, x in enumerate(tree.leaves()) if x == targetWord]
occurence = 0
scopingId = 0
if idOfWord != tree.leaves().index(targetWord):
occurence = indices.index(idOfWord)
scopingId = occurence
#if there aren't multiple occurences of the same token
if occurence == 0:
gen = tree.subtrees(lambda tree2: str(tree2.leaves()[0]) == targetWord)
try:
subtree = gen.next()
except:
print sys.exc_info()[0]
print 'error collecting subtree'
return prevSyntactic, row
#find correct token within the sentence
else:
next = 'false'
for mytree in tree.subtrees(lambda tree2: str(tree2.leaves()[0]) == targetWord):
if next == 'true' and occurence == 0:
subtree = mytree
break
else:
next = 'false'
if mytree.height() == 2:
next = 'true'
occurence = occurence - 1
#get subtree's label, length of span and depth
flattened = subtree.flatten()
label = flattened.label()
lengthSpan = len(flattened.leaves())
depth = len(subtree.treeposition())
#find the ID in the original sentence so that we can find out whether any of the words are verb cues
tokenArray = []
idOfWord = None
for token in sentence['tokens']:
word = token['word']
if word == '(':
word = '-LRB-'
if word == ')':
word = '-RRB-'
if targetWord == word and scopingId == 0:
idOfWord = token['id']
break
elif targetWord == word:
scopingId = scopingId - 1
else:
continue
tokenArray = tree.leaves()
#check if any tokens in the span are verb cues and append if found
constHasSpan = False
for verb in verbsList:
verbWord = verb[0]
verbSent = int(verb[1])
verbTok = int(verb[2])
verbLabel = verb[4]
if verbSent != sentence['id']:
continue
else:
for i in range(len(flattened.leaves())):
if i + idOfWord == verbTok and tokenArray[i + idOfWord] == verbWord and verbLabel == 'Y':
row += '''constSpanVC='true'\t'''
constHasSpan = True
row += 'constLabel=' + label + '\t' + 'constSpanLength=' + str(lengthSpan) + '\t' + 'depthSpan=' + str(depth) + '\t'
#get the subtree's parent tree
parentTreePosList = list(subtree.treeposition())
#no parent, return the row as it is
if len(parentTreePosList) == 0:
return prevSyntactic, row
elif targetWord == '-LRB-' or targetWord == 'RRB':
return prevSyntactic, row
parentTreePosList.pop()
parentTreeHead = tuple(parentTreePosList)
parentTree = tree[parentTreePosList]
parentFlat = parentTree.flatten()
parentLabel = parentFlat.label()
lengthSpanParent = len(parentFlat.leaves())
parentDepth = len(parentTree.treeposition())
#find correct word id that begins the span
begIndex = None
for indx, word in enumerate(tokenArray):
i = 0
if parentFlat.leaves()[0] == word:
for item in parentFlat.leaves():
if i + indx == len(tokenArray):
continue
if item == tokenArray[i + indx] and i == len(parentFlat.leaves()) - 1:
begIndex = indx
if item == tokenArray[i + indx]:
i = i + 1
#find out if any of these are verbs
for verb in verbsList:
verbWord = verb[0]
verbSent = int(verb[1])
verbTok = int(verb[2])
verbLabel = verb[4]
if verbSent != sentence['id']:
continue
else:
for i in range(len(parentFlat.leaves())):
if i + begIndex == verbTok and tokenArray[i + begIndex] == verbWord and verbLabel == 'Y':
row += '''parentConstSpanVC='true'\t'''
#no need to add it twice
constHasSpan = False
#if the child tree had a verb cue, then we know the parent does
if constHasSpan == True:
row += '''parentConstSpanVC='true'\t'''
row += 'parentConstLabel=' + parentLabel + '\t' + 'parentConstSpanLength=' + \
str(lengthSpanParent) + '\t' + 'parentDepthSpan=' + str(parentDepth) + '\t'
return prevSyntactic, row
#parse command line arguments
def main():
usageMessage = '\nCorrect usage of the Content Span Extractor command is as follows: \n' + \
'\n\n WHEN AN ANNOTATED FILESET EXISTS TO GET LABELS FROM:\n' + \
'To extract tokens and their features: \n python source/intermediaries/contentSpanExtractor.py -labelled /pathToCoreNLPDirectory /pathToAnnotatedFilesDirectory /pathToRawDirectory nameCorrespondingTaggedVerbCuesFile nameOfOutputFile.txt \n' + \
'\nTo use the default path names for the PARC training data, and filename PARCtrainContentSpans.txt please use the command with the label -default, as follows: \n' + \
'\t python source/intermediaries/contentSpanExtractor.py -labelled -default' + \
'\n\n WHEN THE LABELS ARE UNKNOWN:\n' + \
'To extract tokens and their features: \n python source/intermediaries/contentSpanExtractor.py -unlabelled /pathToCoreNLPDirectory /pathToRawDirectory nameCorrespondingTaggedVerbCuesFile nameOfOutputFile.txt \n' + \
'\nFor reference, the path to the CoreNLP file is: /home/ndg/dataset/ptb2-corenlp/CoreNLP/ + train, test or dev depending on your needs. \n' + \
'The path to the Parc3 files is /home/ndg/dataset/parc3/ + train, test or dev depending on your needs.\n'
args = sys.argv
if len(args) == 7:
flag = args[1]
pathToCORENLP = args[2]
pathToAnnotatedFiles = args[3]
pathToRaw = argsg[4]
verbCuesFile = args[5]
nameTxtOutput = args[6]
if flag != '-labelled':
print usageMessage
return
if os.path.isdir(pathToCORENLP):
print 'valid path to a directory'
else:
print 'ERROR: The path to this coreNLP directory does not exist.'
print usageMessage
return
if os.path.isdir(pathToAnnotatedFiles):
print 'valid path to a directory'
else:
print 'ERROR: The path to this annotated file directory does not exist.'
print usageMessage
return
if os.path.isfile(data_dir + nameTxtOutput):
print "That file already exists, you probably don't want to overwrite it"
var = raw_input("Are you sure you want to overwrite this file? Please answer Y or N\n")
if var == 'Y' or var == 'y':
coreNLPFiles = openDirectory(pathToCORENLP)
annotatedFiles = openDirectory(pathToAnnotatedFiles)
rawFiles = openDirectory(pathToRaw)
findFiles(coreNLPFiles, annotatedFiles, rawFiles, nameTxtOutput, verbCuesFile)
return
else:
return
else:
print 'valid filename'
coreNLPFiles = openDirectory(pathToCORENLP)
annotatedFiles = openDirectory(pathToAnnotatedFiles)
rawFiles = openDirectory(pathToRaw)
findFiles(coreNLPFiles, annotatedFiles, rawFiles, nameTxtOutput, verbCuesFile)
elif len(args) == 6:
pathToCORENLP = args[2]
pathToRaw = args[3]
verbCuesFile = args[4]
nameTxtOutput = args[5]
if args[1] != '-unlabelled':
print usageMessage
return
if os.path.isdir(pathToCORENLP):
print 'valid path to a directory'
else:
print 'ERROR: The path to this coreNLP directory does not exist.'
print usageMessage
return
if os.path.isfile(data_dir + nameTxtOutput):
print "That file already exists, you probably don't want to overwrite it"
var = raw_input("Are you sure you want to overwrite this file? Please answer Y or N\n")
if var == 'Y' or var == 'y':
coreNLPFiles = openDirectory(pathToCORENLP)
rawFiles = openDirectory(pathToRaw)
findFiles(coreNLPFiles, None, rawFiles, nameTxtOutput, verbCuesFile)
return
else:
return
coreNLPFiles = openDirectory(pathToCORENLP)
rawFiles = openDirectory(pathToRaw)
findFiles(coreNLPFiles, None, rawFiles, nameTxtOutput, verbCuesFile)
elif len(args) == 3:
if args[1] == '-labelled' and args[2] == '-default':
pathToCORENLP = '/home/ndg/dataset/ptb2-corenlp/CoreNLP_tokenized/train/'
pathToAnnotatedFiles = '/home/ndg/dataset/parc3/train/'
pathToRaw = '/home/ndg/dataset/ptb2-corenlp/masked_raw/train/'
verbCuesFile = 'train/PARCTrainVerbFeatsFOR_SPAN_EXTRACTOR.csv'
nameTxtOutput = 'PARCTrainContentSpans.txt'
coreNLPFiles = openDirectory(pathToCORENLP)
annotatedFiles = openDirectory(pathToAnnotatedFiles)
rawFiles = openDirectory(pathToRaw)
findFiles(coreNLPFiles, annotatedFiles, rawFiles, nameTxtOutput, verbCuesFile)
else:
print usageMessage
else:
print usageMessage
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
if __name__ == '__main__':
main()
|
random_job6.py | # 1584927559
import task_submit_fix
from task_submit_fix import VGGTask,RESTask,RETask,DENTask,XCETask
import random
import kubernetes
import influxdb
import kubernetes
import signal
from TimeoutException import TimeoutError,Myhandler
import yaml
import requests
from multiprocessing import Process
import multiprocessing
import urllib
import urllib3
import time
import operator
import numpy as np
# from utils import Timer
from sklearn.externals import joblib
from sklearn.ensemble import GradientBoostingRegressor,RandomForestRegressor
import time
np.set_printoptions(suppress=True) #设置print选项的参数
'''
初始配置节点数量实验,对于节点资源分配,因为手动分配会造成错误,我认为统计本方法资源效率即可证明了
本设置为不考虑资源情况,仅考虑完成率的问题
'''
import os
import json
import math
import pandas as pd
import argparse
import random
import multiprocessing
import time
from pytz import UTC
from dateutil import parser
from datetime import datetime
import psutil
import socket
from max_heap import MaxHeap
import worker_queue
# from worker_queue import value_free_load,value_weight_load
from Global_client import Global_Influx
aToken = 'eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJhZG1pbi11c2VyLXRva2VuLTJ3dGRuIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImFkbWluLXVzZXIiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiI5YWE4ZTc4OS0zODM1LTExZWEtYWZlMi1mYTE2M2UzMzBlYWEiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6a3ViZS1zeXN0ZW06YWRtaW4tdXNlciJ9.qzHVo1KysWhnSAMwKAcaKLWkqOxBlSBr7qR4LtldusdM0Z9dDQVH2TMmtvmkBDyfqVKQttMmTGXDHhW-dOD9uJVn8w84zitd7eAgVCrHm2nhTMbsf2ZKH0DuU6t_SGYkyBWVIedMpZis-K2mzCjmSq5TAd67cMSCqGHQVMtjEsqpPyBeY_nrqgzWWwX3X3E0hHGk7CvICndFiqUeI9xKVluA-TdR6HzPXbaCIGAcvSHeIlc4GdhmDTJ47U4rQON3IL0dhC6Adom7c65I5pwBdYpfqkDhKld1o7ErhXS8Qhcv0BHhfuj-Bdn6MMsH7PXpH-7I5dxoKDVlTC-q7KV9EQ'
aTokenw = 'eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJhZG1pbi11c2VyLXRva2VuLTJ3dGRuIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImFkbWluLXVzZXIiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiI5YWE4ZTc4OS0zODM1LTExZWEtYWZlMi1mYTE2M2UzMzBlYWEiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6a3ViZS1zeXN0ZW06YWRtaW4tdXNlciJ9.qzHVo1KysWhnSAMwKAcaKLWkqOxBlSBr7qR4LtldusdM0Z9dDQVH2TMmtvmkBDyfqVKQttMmTGXDHhW-dOD9uJVn8w84zitd7eAgVCrHm2nhTMbsf2ZKH0DuU6t_SGYkyBWVIedMpZis-K2mzCjmSq5TAd67cMSCqGHQVMtjEsqpPyBeY_nrqgzWWwX3X3E0hHGk7CvICndFiqUeI9xKVluA-TdR6HzPXbaCIGAcvSHeIlc4GdhmDTJ47U4rQON3IL0dhC6Adom7c65I5pwBdYpfqkDhKld1o7ErhXS8Qhcv0BHhfuj-Bdn6MMsH7PXpH-7I5dxoKDVlTC-q7KV9EQ'
LOSSHOST = '192.168.128.5'
LOSSPORT = 12527
DNA_SIZE = 3
XBOUND = [0.765,1.36] #1.6
XBOUND2 = [0.5,0.95]
YBOUND2 = [0.725,0.95]
YBOUND = [1,1.4] #1.72
CROSSOVER_RATE = 0.8
CROSS_RATE=0.8
POP_SIZE = 8
N_GENERATIONS = 4
# 205.7142857
sleep_last_length = (78.6/3)
pop_total = []
rfr2 = joblib.load('rfr_batch.pkl')
def load_config(config_file):
f = open(config_file,encoding='utf-8')
res = f.read()
config_content = json.loads(res)
f.close()
return config_content
def save_config(config,filename):
config_content = {}
for key,value in config.items():
# if key != 'job' and key != 'ns':
config_content[key] = value
# task_content['task_id'] = tasks['task_id']
fw = open(filename, 'w', encoding='utf-8')
# ensure_ascii:默认值True,如果dict内含有non-ASCII的字符,则会类似\uXXXX的显示数据,设置成False后,就能正常显示
dic_json = json.dumps(config_content, ensure_ascii=False, indent=4) # 字典转成json,字典转成字符串
fw.write(dic_json)
fw.close()
def reload_jobs_aim(job_name,task_id):
save_job_path = '/tfdata/k8snfs/%s/%s.json' % (job_name, job_name)
save_res_path = '/tfdata/k8snfs/%s/%s_res.json' % (job_name, job_name)
save_mod_path = '/tfdata/k8snfs/%s/%s_mod.json' % (job_name,job_name)
# with open(full_flie_name,'r') as yaml_job:
#job_obj = yaml.load(yaml_job.read())
job_config = load_config(save_job_path)
job_res_config = load_config(save_res_path)
try:
job_mod_config = load_config(save_mod_path)
except Exception as ee1:
print(ee1)
job_mod_config = {'mod': -1, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
save_config(job_mod_config,save_mod_path)
params_dic = {}
params_dic['mod'] = job_mod_config['mod']
keys = job_config.keys()
for key in keys:
params_dic[key] = job_config[key]
# params_dic['v1'] = v1
if task_id != -1:
params_dic['task_id'] = task_id
params_dic['rtimes'] = task_id
if job_config['template_id'] == 1:
job_reload = VGGTask(**params_dic)
job_reload.measure = "VGG %d" % job_reload.task_id
elif job_config['template_id'] == 2:
job_reload = RESTask(**params_dic)
job_reload.measure = "RES %d" % job_reload.task_id
elif job_config['template_id'] == 3:
job_reload = RETask(**params_dic)
job_reload.measure = "RE %d" % job_reload.task_id
elif job_config['template_id'] == 4:
job_reload = XCETask(**params_dic)
job_reload.measure = "XCE %d" % job_reload.task_id
else:
job_reload = DENTask(**params_dic)
job_reload.measure = "DEN %d" % job_reload.task_id
# job_reload.template = job_obj
#job_res_config = {'deadline':job.deadline,'start_time':job.starttime,'cpu_source':job.cpu_allocate,
# 'mem_source':job.memory_allocate,'cpu_high':cpu_base}
job_reload.cpu_allocate = job_res_config['cpu_source']
job_reload.memory_allocate = job_res_config['mem_source']
job_reload.deadline = job_res_config['deadline']
job_reload.starttime = job_res_config['start_time']
return job_reload
def reload_jobs(job_name,task_id):
save_job_path = '/tfdata/k8snfs/setbase/%s/%s.json' % (job_name, job_name)
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job_name, job_name)
save_mod_path = '/tfdata/k8snfs/setbase/%s/%s_mod.json' % (job_name,job_name)
# with open(full_flie_name,'r') as yaml_job:
#job_obj = yaml.load(yaml_job.read())
job_config = load_config(save_job_path)
job_res_config = load_config(save_res_path)
try:
job_mod_config = load_config(save_mod_path)
except Exception as ee1:
print(ee1)
job_mod_config = {'mod': -1, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
save_config(job_mod_config,save_mod_path)
params_dic = {}
params_dic['mod'] = job_mod_config['mod']
keys = job_config.keys()
for key in keys:
params_dic[key] = job_config[key]
# params_dic['v1'] = v1
if task_id != -1:
params_dic['task_id'] = task_id
params_dic['rtimes'] = task_id
if job_config['template_id'] == 1:
job_reload = VGGTask(**params_dic)
job_reload.measure = "VGG %d" % job_reload.task_id
elif job_config['template_id'] == 2:
job_reload = RESTask(**params_dic)
job_reload.measure = "RES %d" % job_reload.task_id
elif job_config['template_id'] == 3:
job_reload = RETask(**params_dic)
job_reload.measure = "RE %d" % job_reload.task_id
elif job_config['template_id'] == 4:
job_reload = XCETask(**params_dic)
job_reload.measure = "XCE %d" % job_reload.task_id
else:
job_reload = DENTask(**params_dic)
job_reload.measure = "DEN %d" % job_reload.task_id
# job_reload.template = job_obj
#job_res_config = {'deadline':job.deadline,'start_time':job.starttime,'cpu_source':job.cpu_allocate,
# 'mem_source':job.memory_allocate,'cpu_high':cpu_base}
job_reload.cpu_allocate = job_res_config['cpu_source']
job_reload.memory_allocate = job_res_config['mem_source']
job_reload.deadline = job_res_config['deadline']
job_reload.starttime = job_res_config['start_time']
return job_reload
job_basic0 = reload_jobs_aim("res-292-292",-1)
basic_job_cpu = job_basic0.total_cpu
basic_job_mem = job_basic0.total_mem
def deletehelp(delete_job_name,v1):
try:
v1.delete_namespace(delete_job_name)
except Exception as eeeeee:
print(eeeeee)
command0 = "kubectl get namespace " + delete_job_name + " -o json > /tfdata/tfcnn/deletebuf/" + delete_job_name + ".json"
os.system(command0)
tmp = load_config("/tfdata/tfcnn/deletebuf/" + delete_job_name + ".json")
tmp["spec"]["finalizers"] = []
save_config(tmp, "/tfdata/tfcnn/deletebuf/" + delete_job_name + ".json")
try:
command1 = 'curl -k -H "Content-Type: application/json" -X PUT --data-binary @/tfdata/tfcnn/deletebuf/' + delete_job_name + '.json http://127.0.0.1:8081/api/v1/namespaces/'+delete_job_name+'/finalize'
os.system(command1)
except Exception as helpe:
print(helpe)
commandopen = 'kubectl proxy --port=8081'
os.system(commandopen)
os.system(command1)
def deletehelp2(delete_job_name,v1):
v1.delete_namespace(delete_job_name)
command0 = "kubectl get namespace " + delete_job_name + " -o json > /tfdata/tfcnn/deletebuf/" + delete_job_name + ".json"
os.system(command0)
tmp = load_config("/tfdata/tfcnn/deletebuf/" + delete_job_name + ".json")
tmp["spec"]["finalizers"] = []
save_config(tmp, "/tfdata/tfcnn/deletebuf/" + delete_job_name + ".json")
command1 = 'curl -k -H "Content-Type: application/json" -X PUT --data-binary @/tfdata/tfcnn/deletebuf/' + delete_job_name + '.json http://127.0.0.1:8081/api/v1/namespaces/' + delete_job_name + '/finalize'
try:
command1 = 'curl -k -H "Content-Type: application/json" -X PUT --data-binary @/tfdata/tfcnn/deletebuf/' + delete_job_name + '.json http://127.0.0.1:8081/api/v1/namespaces/' + delete_job_name + '/finalize'
os.system(command1)
except Exception as helpe:
print(helpe)
commandopen = 'kubectl proxy --port=8081'
os.system(commandopen)
os.system(command1)
def translateDNA(pop):
global DNA_SIZE,XBOUND,YBOUND
print(pop.shape)
#pop表示种群矩阵,一行表示一个二进制编码表示的DNA,矩阵的行数为种群数目:
x_pop = pop[:,1::2]#从第1列开始,步进为2
y_pop = pop[:,::2]#从第0列开始,步进为2
# #pop:(POP_SIZE,DNA_SIZE)*(DNA_SIZE,1) --> (POP_SIZE,1)完成解码:二进制码求相应十进制值然后压缩到相应范围内即可完成解码
x = x_pop.dot(2**np.arange(DNA_SIZE)[::-1])/float(2**DNA_SIZE-1)*(XBOUND[-1] - XBOUND[0])+XBOUND[0]
y = y_pop.dot(2**np.arange(DNA_SIZE)[::-1])/float(2**DNA_SIZE-1)*(YBOUND[-1] - YBOUND[0])+YBOUND[0]
# print("a translateDNA process finished")
return x,y
def existss(pop_total,gene,init=1):
if init == 0:
gene10 = gene.dot(2 ** np.arange(2 * DNA_SIZE)[::-1])
pop_total = list(gene10)
return pop_total
else:
gene10 = int(gene.dot(2 ** np.arange(2 * DNA_SIZE)[::-1]))
if gene10 in pop_total:
return True
else:
pop_total.append(gene10)
return False
def translateDNA2(pop):
global DNA_SIZE,XBOUND2,YBOUND2
print(pop.shape)
x_pop = pop[:, 1::2] # 从第1列开始,步进为2
y_pop = pop[:, ::2] # 从第0列开始,步进为2
# #pop:(POP_SIZE,DNA_SIZE)*(DNA_SIZE,1) --> (POP_SIZE,1)完成解码:二进制码求相应十进制值然后压缩到相应范围内即可完成解码
x = x_pop.dot(2 ** np.arange(DNA_SIZE)[::-1]) / float(2 ** DNA_SIZE - 1) * (XBOUND2[-1] - XBOUND2[0]) + XBOUND2[0]
y = y_pop.dot(2 ** np.arange(DNA_SIZE)[::-1]) / float(2 ** DNA_SIZE - 1) * (YBOUND2[-1] - YBOUND2[0]) + YBOUND2[0]
# print("a translateDNA2 process finished")
return x, y
def predict_min_map1(job_exp):
job_name = job_exp['name']
cpu = job_exp['cpu']
mem = job_exp['mem']
ps = job_exp['ps']
worker = job_exp['worker']
global rfr2
global basic_job_cpu
global basic_job_mem
job_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job_name, job_name)
job_config = load_config(job_path)
batch = job_config['batch_res']
flops = job_config['flops_res']
params = job_config['params_res']
cpu_high = job_config['cpu_high']
mem_base = job_config['memory_base']
cpu_alpha = cpu/ cpu_high
mem_alpha = mem/ mem_base
# bfp = list(zip(list(res['batch']),list(res['flops']),list(res['params']),list(res['cpu_alpha']),list(res['mem_alpha'])))
data = np.array([batch, flops, params, cpu_alpha, mem_alpha])
data = np.mat(data)
data = data.A
iteration = rfr2.predict(data)
iteration = float(iteration)
pred = (0 - iteration) * (
(ps * 720 + worker * cpu) / basic_job_cpu + (ps * 2048 + worker * mem) / basic_job_mem)
return pred
def predict_min_map3(job_exp):
job_name = job_exp['name']
cpu = job_exp['cpu']
mem = job_exp['mem']
global rfr2
global basic_job_cpu
global basic_job_mem
job_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job_name, job_name)
job_config = load_config(job_path)
batch = job_config['batch_res']
flops = job_config['flops_res']
params = job_config['params_res']
cpu_high = job_config['cpu_high']
mem_base = job_config['memory_base']
cpu_alpha = cpu/ cpu_high
mem_alpha = mem/ mem_base
# bfp = list(zip(list(res['batch']),list(res['flops']),list(res['params']),list(res['cpu_alpha']),list(res['mem_alpha'])))
data = np.array([batch, flops, params, cpu_alpha, mem_alpha])
data = np.mat(data)
data = data.A
iteration = rfr2.predict(data)
iteration = float(iteration)
pred = 0 - iteration
# pred = (0 - iteration) * (
# (ps * 700 + worker * cpu) / basic_job_cpu + (ps * 2048 + worker * mem) / basic_job_mem)
return pred
def predict_min_map4(job_exp):
job_name = job_exp['name']
cpu = job_exp['cpu']
mem = job_exp['mem']
global rfr2
global basic_job_cpu
global basic_job_mem
job_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job_name, job_name)
job_config = load_config(job_path)
batch = job_config['batch_res']
flops = job_config['flops_res']
params = job_config['params_res']
cpu_high = job_config['cpu_high']
mem_base = job_config['memory_base']
cpu_alpha = cpu/ cpu_high
mem_alpha = mem/ mem_base
# bfp = list(zip(list(res['batch']),list(res['flops']),list(res['params']),list(res['cpu_alpha']),list(res['mem_alpha'])))
data = np.array([batch, flops, params, cpu_alpha, mem_alpha])
data = np.mat(data)
data = data.A
iteration = rfr2.predict(data)
iteration = float(iteration)
worker = job_exp['worker']
mini0 = job_exp['mini0']
cpu_allocate = job_exp['callo']
mem_allocate = job_exp['mallo']
# mini_batch = predict_min(aim, cpu_pre[i], mem_pre[i], rfr)
score = worker * (0.75 * (cpu_allocate - cpu) / basic_job_cpu + 0.25 * (mem_allocate - mem) / basic_job_mem)
minik = iteration / mini0
score = score / minik
return score
def get_fitness1(aim,pop,cpu_now,mem_now,cpu_base,mem_base,worker,ps):
global XBOUND,YBOUND
cpu_alpha,mem_alpha = translateDNA(pop)
# print("catch cpu_alpha:")
# print(cpu_alpha)
# cpu_pre = cpu_now*cpu_alpha
cpu_pre = cpu_now*cpu_alpha
# print(type(cpu_pre))
# mem_pre = mem_base*mem_alpha
cpu_pre_limit = math.ceil(XBOUND[-1]*1.478*cpu_base)
mem_pre = mem_now*mem_alpha
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * mem_base)
for i in range(len(cpu_pre)):
if cpu_pre[i] > cpu_pre_limit:
cpu_pre[i] = cpu_pre_limit
if mem_pre[i] > mem_pre_limit:
mem_pre[i] = mem_pre_limit
job_exp_list = []
# job_name = job_exp['name']
# cpu = job_exp['cpu']
# mem = job_exp['mem']
for i in range(len(cpu_pre)):
# if cpu_pre[i] > cpu_pre_limit and mem_pre[i] <= mem_pre_limit:
job_exp_list.append({'name':aim,'cpu':cpu_pre[i],'mem':mem_pre[i],'ps':ps,'worker':worker})
# pred = []
pool_fit = multiprocessing.Pool(6)
# print("start to a get_fitness1 map")
pred = pool_fit.map(predict_min_map1,job_exp_list)
# print("end a get_fitness1 map")
pool_fit.close()
pool_fit.join()
pred = np.array(pred)
# print("a get_fitness1 procedure end!")
# pred = mini_batch
return (pred - min(pred))+1e-4 ##减去最小的适应度是为了防止适应度出现负数,通过这一步fitness的范围为[0, np.max(pred)-np.min(pred)],最后在加上一个很小的数防止出现为0的适应度
def get_fitness3(aim,pop,cpu_now,mem_now,cpu_base,mem_base):
#任务完成不了了,所以直接看minbatch可以减少多少而不是资源利用
global XBOUND, YBOUND
cpu_alpha, mem_alpha = translateDNA(pop)
cpu_pre = cpu_now * cpu_alpha
# print(type(cpu_pre))
# mem_pre = mem_base*mem_alpha
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * cpu_base)
mem_pre = mem_now * mem_alpha
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * mem_base)
for i in range(len(cpu_pre)):
if cpu_pre[i] > cpu_pre_limit:
cpu_pre[i] = cpu_pre_limit
if mem_pre[i] > mem_pre_limit:
mem_pre[i] = mem_pre_limit
job_exp_list = []
for i in range(len(cpu_pre)):
job_exp_list.append({'name':aim,'cpu':cpu_pre[i],'mem':mem_pre[i]})
pool_fit = multiprocessing.Pool(6)
# print("start to a get_fitness3 map")
pred = pool_fit.map(predict_min_map3, job_exp_list)
# print("end a get_fitness3 map")
pool_fit.close()
pool_fit.join()
pred = np.array(pred)
# print("a get_fitness3 process finished")
# pred = mini_batch
return (pred - min(pred))+1e-4 ##减去最小的适应度是为了防止适应度出现负数,通过这一步fitness的范围为[0, np.max(pred)-np.min(pred)],最后在加上一个很小的数防止出现为0的适应度
def get_fitness4(aim,pop,cpu_base,mem_base,cpu_allocate,mem_allocate,worker,mini0):
#任务可以完成,现在要减少资源,当然就是看减少资源的总量和减少资源造成的minibatch之间的权衡
cpu_alpha,mem_alpha = translateDNA2(pop)
# print("catch cpu_alpha:")
# print(cpu_alpha)
cpu_pre = cpu_allocate*cpu_alpha
# print(type(cpu_pre))
mem_pre = mem_allocate*mem_alpha
job_exp_list = []
for i in range(len(cpu_pre)):
if cpu_pre[i] < 0.475 * cpu_base:
cpu_pre[i] = math.ceil(0.475 * cpu_base)
if mem_pre[i] < 1.03 * mem_base:
mem_pre[i] = math.ceil(1.03 * mem_base)
job_exp_list.append({'name': aim, 'cpu': cpu_pre[i], 'mem': mem_pre[i],'worker':worker,'mini0':mini0,'callo':cpu_allocate,'mallo':mem_allocate})
pool_fit = multiprocessing.Pool(6)
# print("start to get_fitness4 map")
pred = pool_fit.map(predict_min_map4, job_exp_list)
# print("end get_fitness4 map")
pool_fit.close()
pool_fit.join()
pred = np.array(pred)
# print("a get_fitness4 is finished")
return (pred - min(pred)) + 1e-4
def select(pop,fitness):
global POP_SIZE
idx = np.random.choice(np.arange(pop.shape[0]),size=POP_SIZE,replace=True,p=fitness/fitness.sum())
# 不熟悉numpy的朋友可以查阅一下这个函数,主要是使用了choice里的最后一个参数p,参数p描述了从np.arange(POP_SIZE)里选择每一个元素的概率,
# 概率越高约有可能被选中,最后返回被选中的个体即可。
return pop[idx]
def predict_min_first(rfr,cpu_alpha,mem_alpha,batch,flops,params):
data = np.array([batch, flops, params, cpu_alpha, mem_alpha])
data = np.mat(data)
data = data.A
iteration = rfr.predict(data)
iteration = float(iteration)
return iteration
def predict_min(job_name,cpu,mem, rfr):
job_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job_name, job_name)
job_config = load_config(job_path)
batch = job_config['batch_res']
flops = job_config['flops_res']
params = job_config['params_res']
cpu_high = job_config['cpu_high']
mem_base = job_config['memory_base']
cpu_alpha = cpu/ cpu_high
mem_alpha = mem/ mem_base
# bfp = list(zip(list(res['batch']),list(res['flops']),list(res['params']),list(res['cpu_alpha']),list(res['mem_alpha'])))
data = np.array([batch, flops, params, cpu_alpha, mem_alpha])
data = np.mat(data)
data = data.A
iteration = rfr.predict(data)
iteration = float(iteration)
return iteration
def crossover_and_mutation(pair):
global pop_total
global POP_SIZE,N_GENERATIONS,CROSS_RATE
new_pop = []
i = 0
# pop_sizes = len(pop)
father = pair[0]
mother = pair[1]
# print(father)
# 遍历种群中的每一个个体,将该个体作为父亲
# 孩子先得到父亲的全部基因(这里我把一串二进制串的那些0,1称为基因)
child = np.array(list(father)[:])
i = i + 1
child2 = []
# print(child.shape)
cross = False
if np.random.rand() < CROSS_RATE:
cross = True
# # 产生子代时不是必然发生交叉,而是以一定的概率发生交叉
# mother = pop[np.random.randint(POP_SIZE)] # 再种群中选择另一个个体,并将该个体作为母亲
# # if i == len(pop):
# # i = 0
# # mother = pop[i]
child2 = np.array(list(mother)[:])
cross_points = np.random.randint(low=0, high=DNA_SIZE * 2) # 随机产生交叉的点
child[cross_points:] = mother[cross_points:] # 孩子得到位于交叉点后的母亲的基因
child2[cross_points:] = father[cross_points:]
mutation(child) # 每个后代有一定的机率发生变异
exist_res = existss(pop_total, child)
if exist_res:
new_pop.append(father)
else:
if cross:
# print(child2)
# print(child2.shape)
mutation(child2)
exist_res = existss(pop_total, child2)
if not exist_res:
new_pop.append(child2)
new_pop.append(child)
# new_pop.append(child2)
# print(child)
# print(father)
if not operator.eq(list(child), list(father)) and not operator.eq(list(child2), list(father)):
new_pop.append(father)
return new_pop
# def make_new_pop(inpop):
def mutation(child, MUTATION_RATE=0.003):
if np.random.rand() < MUTATION_RATE: #以MUTATION_RATE的概率进行变异
mutate_point = np.random.randint(0, 2*DNA_SIZE-1) #随机产生一个实数,代表要变异基因的位置
child[mutate_point] = child[mutate_point]^1 #将变异点的二进制为反转
def kongxian(res_cpu,res_mem,cpu_allocae,mem_allocate,cpu_base,mem_base,layout_config,pop):
cpu_alpha,mem_alpha = translateDNA(pop)
layout_key = layout_config.keys()
delete_pop = []
for i in range(len(cpu_alpha)):
for lay in layout_key:
if res_cpu[lay]+layout_config[lay]['worker']*(cpu_allocae-math.ceil(cpu_alpha[i]*cpu_allocae)) > 0 and res_mem[lay]+layout_config[lay]['worker']*(mem_allocate-mem_alpha[i]*mem_allocate)>0:
continue
else:
delete_pop.append(i)
break
return delete_pop
def kongxian2(node_list,res_cpu,res_mem,ps,cpu_allocate,mem_allocate):
res_load = [res_cpu[i] for i in node_list]
list.sort(res_load)
if res_load[-1] >= cpu_allocate:
res_load[-1] = res_load[-1] - cpu_allocate
list.sort(res_load)
if res_load[-1] > 500*ps:
return True
else:
return False
else:
return False
def finish(res_iter,pop,res_time,cpu_allocate,mem_allocate,cpu_base,mem_base,rfr,aim):
cpu_alpha,mem_alpha = translateDNA2(pop)
delete_pop = []
cpu_pre = cpu_allocate*cpu_alpha
mem_pre = mem_allocate*mem_alpha
for i in range(len(cpu_pre)):
if cpu_pre[i] < 0.475 * cpu_base:
cpu_pre[i] = math.ceil(0.475 * cpu_base)
if mem_pre[i] < 1.03 * mem_base:
mem_pre[i] = math.ceil(1.03 * mem_base)
mini_batch = predict_min(aim,cpu_pre[i],mem_pre[i],rfr)
if mini_batch*res_iter > res_time:
delete_pop.append(i)
return delete_pop
def finish2(total_step,res_time,reload_point,worker,ps,change_ps,mini_batch):
if worker == 1:
return False
if ps - change_ps <= 0:
return False
need_time = mini_batch*((total_step*worker/(worker-1)) - reload_point)
if res_time >= need_time:
return True
else:
return False
def assign_jobs(tasks, rfr, lock):
global DNA_SIZE, POP_SIZE, N_GENERATIONS
global XBOUND, YBOUND
global pop_total
# 选择标准有两个:
'''
1.对于每次选择,选择无法按时完成的任务,使用deadline
为保证规模并不过分高,则每次选择的是最紧急的任务要进行调整
2.对于系统负载而言,如果系统资源负载不高的话,则可以考虑调整资源,使其负载率较高
3.对于系统而言,如果资源利用率持续低于某个阈值的话可以考虑增加某个任务的负载
4.每次在调增任务时尝试选择调减任务,然后减少其资源的分配
:return:
'''
step_influx_client = influxdb.InfluxDBClient(host='192.168.128.10', username='admin', password='admin',
database='PREDICT')
piotential = []
job_basic = reload_jobs_aim(tasks['last'], -1)
print("reload a job success!!")
node_list_global = job_basic.node_list
res_cpu = job_basic.node_cpu
res_mem = job_basic.node_memory
res_config0 = {}
layout_config0 = {}
lock.acquire()
tmp_ns = tasks['ns']
tmp_layout = tasks['nslayout']
tmp_layout_key = tmp_layout.keys()
for i in tmp_ns:
layout_file = '/tfdata/k8snfs/setbase/%s/layout.json' % i
res_file = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (i, i)
job_file = '/tfdata/k8snfs/setbase/%s/%s.json' % (i, i)
res_config = load_config(res_file)
job_config = load_config(job_file)
# "ps_replicas": 2,
# "worker_replicas": 5,
res_config0[i] = res_config
res_config0[i]['ps'] = job_config["ps_replicas"]
res_config0[i]['worker'] = job_config["worker_replicas"]
layout_config0[i] = {}
if os.path.exists(layout_file):
tmp_cpu = {}
tmp_mem = {}
tmp_config = load_config(layout_file)
tmp_layout_config = {}
tmp_key = list(tmp_config.keys())
for tk in tmp_key:
tmp_cpu[tmp_config[tk]] = 0
tmp_mem[tmp_config[tk]] = 0
tmp_layout_config[tmp_config[tk]] = {'ps': 0, 'worker': 0}
for tk in tmp_key:
if 'ps' in tk:
tmp_cpu[tmp_config[tk]] += 750
tmp_mem[tmp_config[tk]] += 2048
tmp_layout_config[tmp_config[tk]]['ps'] += 1
else:
# "cpu_source": 6046,
# "mem_source": 19225,
tmp_cpu[tmp_config[tk]] += res_config['cpu_source']
tmp_mem[tmp_config[tk]] += res_config['mem_source']
tmp_layout_config[tmp_config[tk]]['worker'] += 1
tmp_cpu_key = list(tmp_cpu.keys())
for tck in tmp_cpu_key:
res_cpu[tck] = res_cpu[tck] - tmp_cpu[tck]
res_mem[tck] = res_mem[tck] - tmp_mem[tck]
layout_config0[i] = tmp_layout_config
if (i in tmp_layout_key) and tmp_layout[i]:
piotential.append(i)
lock.release()
print("The aim can choose to modulate:")
print(piotential)
print("The modulation base config:")
print(res_config0)
print("The system machine resource condition:")
print("CPU condition:")
print(res_cpu)
print("Memory condition:")
print(res_mem)
print("Layout condition:")
print(layout_config0)
if not piotential:
return {}, -1
assign_config = {}
# for i in piotential:
# assign_config[i] = {}
aim1 = ''
aim2 = ''
mode = 0
aim = {}
if not piotential:
print("Do not have jobs!!")
return {}, -1
for i in piotential:
reload_tmp = reload_jobs(i, -1)
lock.acquire()
tmp_ns2 = tasks['ns']
lock.release()
if i not in tmp_ns2:
piotential.remove(i)
key00 = layout_config0[i].keys()
for ke00 in key00:
res_cpu[ke00] += layout_config0[i][ke00]['worker'] * res_config0[i]['cpu_source']
res_mem[ke00] += layout_config0[i][ke00]['worker'] * res_config0[i]['mem_source']
res_cpu[ke00] += layout_config0[i][ke00]['ps'] * 650
res_mem[ke00] += layout_config0[i][ke00]['ps'] * 1536
continue
pod_status = [j.status.phase for j in reload_tmp.v1.list_namespaced_pod(i).items]
run_result = pd.value_counts(pod_status)
run_result_dict = dict(run_result)
if not run_result_dict:
piotential.remove(i)
if 'Succeeded' in pod_status or 'Failed' in pod_status:
piotential.remove(i)
# if assign_config[i]:
key00 = layout_config0[i].keys()
for ke00 in key00:
res_cpu[ke00] += layout_config0[i][ke00]['worker'] * res_config0[i]['cpu_source']
res_mem[ke00] += layout_config0[i][ke00]['worker'] * res_config0[i]['mem_source']
res_cpu[ke00] += layout_config0[i][ke00]['ps'] * 650
res_mem[ke00] += layout_config0[i][ke00]['ps'] * 15
continue
tmp_re = reload_tmp.deadline - (time.time() - reload_tmp.starttime)
tmp_iter, total_step, _ = reload_tmp.get_remain(mode=1)
reload_iter, _, reload_point = reload_tmp.get_remain(mode=0)
pre_list = reload_tmp.measure.split(" ")
measure_s = pre_list[0] + 'S' + pre_list[-1]
measure_t = pre_list[0] + 'T' + pre_list[-1]
res = step_influx_client.query(
"select * from " + measure_s + " group by nodes order by desc limit 5")
keys = list(res.keys())
dic_msg = {}
time_avg = []
now_mini = 0.0
if keys:
node_list = [b['nodes'] for a, b in keys]
print("A job node list is:")
print(node_list)
for node in node_list:
for j in range(len(keys)):
_, no = keys[j]
if no['nodes'] == node:
dic_msg[node] = list(res[keys[j]])
for node in node_list:
time_avg_list = [float(k['time_d']) for k in dic_msg[node]]
time_avg_node = np.mean(time_avg_list)
time_avg.append(time_avg_node)
print('current time condition:')
print(time_avg)
if time_avg:
# now_mini = max(time_avg)
now_mini = np.mean(time_avg)
else:
now_mini = predict_min(i, reload_tmp.cpu_allocate, reload_tmp.memory_allocate, rfr)
else:
now_mini = predict_min(i, reload_tmp.cpu_allocate, reload_tmp.memory_allocate, rfr)
need_time = tmp_iter * now_mini
res_config0[i]['need'] = need_time
res_config0[i]['remain_time'] = tmp_re
res_config0[i]['mini'] = now_mini
res_config0[i]['remain_iter'] = tmp_iter
res_config0[i]['reload_iter'] = reload_iter
res_config0[i]['total_step'] = total_step
res_config0[i]['reload_point'] = reload_point
# save_config(res_config, res_path)
rescha = need_time - tmp_re
aim_keys = list(aim.keys())
if rescha not in aim_keys:
aim[rescha] = []
aim[rescha].append(i)
aim_time = list(aim.keys())
print("The aim can go to modulate:")
print(aim)
print("The time space to be modulate:")
print(aim_time)
aim1 = ''
aim2 = ''
mode = 0
print("Something add to the base config:")
print(res_config0)
if aim_time:
list.sort(aim_time)
if aim_time[-1] <= 0:
# 所有任务都可以完成
relise_cpu = 0
relise_mem = 0
for node in node_list_global:
relise_cpu += res_cpu[node]
relise_mem += res_mem[node]
relise_cpu = relise_cpu / job_basic.total_cpu
relise_mem = relise_mem / job_basic.total_mem
relise = 0.75 * relise_cpu + 0.25 * relise_mem
if relise > 0.4:
# 若资源空闲
# 都可以完成,考虑增大资源,提高资源利用率,其中要提升的也是离deadline最近的任务和对于资源最敏感的任务
if len(aim_time) == 1 and len(aim[aim_time[-1]]) == 1:
aim1 = aim[aim_time[-1]][0]
print(aim1)
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1]['worker'] > 8 and res_config0[aim1]['cpu_source'] >= cpu_pre_limit and \
res_config0[aim1]['mem_source'] >= mem_pre_limit:
aim1 = ''
aim2 = ''
else:
aim1 = ''
ttll = len(aim_time)
print("aim_time length % d" % ttll)
tmp_rank = -1
for atkk in range(ttll - 1, -1, -1):
for using_aim in aim[aim_time[atkk]]:
print(using_aim)
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[using_aim]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[using_aim]['memory_base'])
if res_config0[using_aim]['worker'] > 8 and res_config0[using_aim][
'cpu_source'] >= cpu_pre_limit and res_config0[using_aim][
'mem_source'] >= mem_pre_limit:
continue
else:
aim1 = using_aim
tmp_rank = atkk
break
if tmp_rank >= 0:
break
aim_time_po = []
print(tmp_rank)
# up_limit = min(3, len(aim_time))
# up_limit = min(3, 0)
if tmp_rank >= 0:
up_limit = min(3, tmp_rank + 1)
# up_limit = 0 - (up_limit)
up_limit = tmp_rank - ttll + 1 - up_limit
print(up_limit)
for i in range(up_limit, tmp_rank - ttll + 1):
for j in aim[aim_time[i]]:
aim_time_po.append(j)
aim_mingan = {}
for j in aim_time_po:
print(j)
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[j]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[j]['memory_base'])
if res_config0[j]['worker'] > 8 and res_config0[j]['cpu_source'] >= cpu_pre_limit and \
res_config0[j]['mem_source'] >= mem_pre_limit:
continue
reload_tmp = reload_jobs(j, -1)
cpu_per = math.ceil((reload_tmp.cpu_allocate) / (reload_tmp.worker_replicas))
mem_per = math.ceil((reload_tmp.memory_allocate) / (reload_tmp.worker_replicas))
remain0, total0, atmp0 = reload_tmp.get_remain(mode=0)
remain1, _, _ = reload_tmp.get_remain(mode=1)
sco1 = (res_config0[j]['mini'] - predict_min(job_name=j,
cpu=(reload_tmp.cpu_allocate + cpu_per),
mem=(reload_tmp.memory_allocate + mem_per),
rfr=rfr)) / (
(0.7 * reload_tmp.cpu_allocate / reload_tmp.total_cpu) + (
0.3 * reload_tmp.memory_allocate / reload_tmp.total_mem))
if remain1 == 0:
sco2 = float('-inf')
else:
sco2 = (res_config0[j]['mini'] * (remain1 - (
(total0 * reload_tmp.worker_replicas) / (
reload_tmp.worker_replicas + 1) - atmp0))) / (remain1)
sco2 = sco2 / ((0.7 * reload_tmp.cpu_allocate / reload_tmp.total_cpu) + (
0.3 * reload_tmp.memory_allocate / reload_tmp.total_mem))
if remain1 == 0:
sco = float('-inf')
else:
# sco = max([sco1, sco2])
if res_config0[j]['worker'] > 8:
sco = sco1
elif res_config0[j]['cpu_source'] >= cpu_pre_limit and res_config0[j][
'mem_source'] >= mem_pre_limit:
sco = sco2
else:
sco = sco1
if sco2 > sco1:
sco = sco2
# mingan_key = list(aim_mingan.keys())
# if sco not in mingan_key:
# aim_mingan[sco] = []
aim_mingan[sco] = j
mingan_key = list(aim_mingan.keys())
list.sort(mingan_key)
if mingan_key[-1] < 0:
aim2 = ''
else:
aim2 = aim_mingan[mingan_key[-1]]
if aim2 == aim1:
aim2 = ''
else:
aim2 = ''
mode = 1
else:
# 资源比较紧张,此时考虑减少距离deadline最远且对资源最不敏感的任务
if len(aim_time) == 1 and len(aim[aim_time[0]]) == 1:
aim1 = aim[aim_time[0]][0]
aim2 = ''
else:
aim1 = aim[aim_time[0]][0]
aim_time_po = []
up_limit = min(3, len(aim_time))
print("up_limit mode 4: %d" % up_limit)
# up_limit = min(3, len(aim_time) - tmp_rank - 1)
# up_limit = 0 - up_limit
# for i in range(tmp_rank, tmp_rank + up_limit):
for i in range(0, up_limit):
if aim_time[i] >= 0:
break
for j in aim[aim_time[i]]:
aim_time_po.append(j)
aim_mingan = {}
for j in aim_time_po:
reload_tmp = reload_jobs(j, -1)
cpu_per = math.ceil((reload_tmp.cpu_allocate) / (reload_tmp.worker_replicas))
mem_per = math.ceil((reload_tmp.memory_allocate) / (reload_tmp.worker_replicas))
remain0, total0, atmp0 = reload_tmp.get_remain(mode=0)
remain1, _, _ = reload_tmp.get_remain(mode=1)
sco1 = (predict_min(job_name=j, cpu=(reload_tmp.cpu_allocate - cpu_per),
mem=(reload_tmp.memory_allocate - mem_per), rfr=rfr) - res_config0[j][
'mini']) / (
(0.7 * reload_tmp.cpu_allocate / reload_tmp.total_cpu) + (
0.3 * reload_tmp.memory_allocate / reload_tmp.total_mem))
if remain1 == 0 or (reload_tmp.worker_replicas - 1) == 0:
sco2 = float('inf')
else:
sco2 = (res_config0[j]['mini'] * (((total0 * reload_tmp.worker_replicas) / (
reload_tmp.worker_replicas - 1) - atmp0) - remain1)) / (remain1)
sco2 = sco2 / ((0.7 * reload_tmp.cpu_allocate / reload_tmp.total_cpu) + (
0.3 * reload_tmp.memory_allocate / reload_tmp.total_mem))
if remain1 == 0:
sco = -10
else:
# if res_config0[j]['worker'] > 8:
# sco = abs(sco1)
# elif res_config0[j]['cpu_source'] >= cpu_pre_limit and res_config0[j][
# 'mem_source'] >= mem_pre_limit:
# sco = sco2
sco = min(abs(sco1), abs(sco2))
sco = sco / ((0.7 * (
reload_tmp.cpu_allocate * reload_tmp.worker_replicas + reload_tmp.ps_replicas * 640) / reload_tmp.total_cpu) + (
0.3 * (
reload_tmp.memory_allocate * reload_tmp.worker_replicas + reload_tmp.ps_replicas * 1536) / reload_tmp.total_mem))
aim_mingan[sco] = j
mingan_key = list(aim_mingan.keys())
list.sort(mingan_key)
if mingan_key[-1] < 0:
aim2 = ''
else:
for ss in mingan_key:
if ss < 0:
mingan_key.remove(ss)
aim2 = aim_mingan[mingan_key[0]]
if aim2 == aim1:
aim2 = ''
mode = 4
elif aim_time[0] < 0:
# 有任务完不成,有任务可以完成,考虑减少资源和增大资源,减少离deadline最远且对资源最不敏感的任务,增大超时最严重的任务
# 返回任务
# 增加资源的任务为超时最严重的任务,没有疑问,减少资源的任务则为离deadline较远且对资源最不敏感的任务,即剥夺资源带来的影响最小:
if len(aim_time) == 1 and len(aim[aim_time[-1]]) == 1:
# aim1 = aim[aim_time[-1]][0]
# aim2 = ''
aim1 = aim[aim_time[-1]][0]
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1]['worker'] > 8 and res_config0[aim1]['cpu_source'] >= cpu_pre_limit and \
res_config0[aim1]['mem_source'] >= mem_pre_limit:
aim1 = ''
aim2 = ''
else:
# aim1 = aim[aim_time[-1]][0]
aim1 = ''
ttll = len(aim_time)
print("aim_time length % d" % ttll)
tmp_rank = -1
for atkk in range(ttll - 1, -1, -1):
print("into loop")
for using_aim in aim[aim_time[atkk]]:
print(using_aim)
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[using_aim]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[using_aim]['memory_base'])
if res_config0[using_aim]['worker'] > 8 and res_config0[using_aim][
'cpu_source'] >= cpu_pre_limit and res_config0[using_aim][
'mem_source'] >= mem_pre_limit:
continue
else:
aim1 = using_aim
tmp_rank = atkk
break
if tmp_rank >= 0:
break
aim_time_po = []
print("tmp rank:%d" % tmp_rank)
up_limit = min(3, len(aim_time))
# up_limit = 0 - up_limit
for i in range(0, up_limit):
if aim_time[i] >= 0:
break
for j in aim[aim_time[i]]:
aim_time_po.append(j)
aim_mingan = {}
for j in aim_time_po:
reload_tmp = reload_jobs(j, -1)
cpu_per = math.ceil((reload_tmp.cpu_allocate) / (reload_tmp.worker_replicas))
mem_per = math.ceil((reload_tmp.memory_allocate) / (reload_tmp.worker_replicas))
remain0, total0, atmp0 = reload_tmp.get_remain(mode=0)
remain1, _, _ = reload_tmp.get_remain(mode=1)
sco1 = (predict_min(job_name=j, cpu=(reload_tmp.cpu_allocate - cpu_per),
mem=(reload_tmp.memory_allocate - mem_per), rfr=rfr) - res_config0[j][
'mini']) / (
(0.7 * reload_tmp.cpu_allocate / reload_tmp.total_cpu) + (
0.3 * reload_tmp.memory_allocate / reload_tmp.total_mem))
if remain1 == 0 or (reload_tmp.worker_replicas - 1) == 0:
sco2 = float('inf')
else:
sco2 = (res_config0[j]['mini'] * (((total0 * reload_tmp.worker_replicas) / (
reload_tmp.worker_replicas - 1) - atmp0) - remain1)) / (remain1)
sco2 = sco2 / ((0.7 * reload_tmp.cpu_allocate / reload_tmp.total_cpu) + (
0.3 * reload_tmp.memory_allocate / reload_tmp.total_mem))
if remain1 == 0:
sco = -10
else:
sco = min(abs(sco1), abs(sco2))
sco = sco / ((0.7 * (
reload_tmp.cpu_allocate * reload_tmp.worker_replicas + reload_tmp.ps_replicas * 500) / reload_tmp.total_cpu) + (
0.3 * (
reload_tmp.memory_allocate * reload_tmp.worker_replicas + reload_tmp.ps_replicas * 1536) / reload_tmp.total_mem))
aim_mingan[sco] = j
mingan_key = list(aim_mingan.keys())
list.sort(mingan_key)
if mingan_key[-1] < 0:
aim2 = ''
else:
for ss in mingan_key:
if ss < 0:
mingan_key.remove(ss)
aim2 = aim_mingan[mingan_key[0]]
if aim2 == aim1:
aim2 = ''
mode = 2
elif aim_time[0] >= 0:
if len(aim_time) == 1 and len(aim[aim_time[-1]]) == 1:
aim1 = aim[aim_time[-1]][0]
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1]['worker'] > 8 and res_config0[aim1]['cpu_source'] >= cpu_pre_limit and \
res_config0[aim1]['mem_source'] >= mem_pre_limit:
aim1 = ''
aim2 = ''
else:
# 都完不成,则返回超时最严重的两个任务,开始启发式评估方案
# aim1 = aim[aim_time[-1]][0]
aim1 = ''
ttll = len(aim_time)
print("aim_time length % d" % ttll)
tmp_rank = -1
tmp_inter_at_last = 0
for atkk in range(ttll - 1, -1, -1):
tmp_inter_at = 0
for using_aim in aim[aim_time[atkk]]:
print(using_aim)
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[using_aim]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[using_aim]['memory_base'])
if res_config0[using_aim]['worker'] > 8 and res_config0[using_aim][
'cpu_source'] >= cpu_pre_limit and res_config0[using_aim][
'mem_source'] >= mem_pre_limit:
tmp_inter_at += 1
continue
else:
aim1 = using_aim
tmp_inter_at_last = tmp_inter_at
tmp_rank = atkk
break
if tmp_rank >= 0:
break
if tmp_rank >= 0:
if len(aim[aim_time[tmp_rank]]) > tmp_inter_at_last + 1:
aim2 = aim[aim_time[tmp_rank]][tmp_inter_at_last + 1]
else:
if tmp_rank > 0:
aim2 = aim[aim_time[tmp_rank - 1]][0]
else:
aim2 = ''
mode = 3
print('The mode will be used: %d' % mode)
print('The first aim and second aim:')
print(aim1)
print(aim2)
if mode == 0:
print("Mode %d Do not find fit job to get modluation!!" % mode)
return {}, mode
elif mode == 1:
if not aim1 and not aim2:
print("Mode %d Do not find aim1 and aim2 to get modulateion!!" % mode)
return {}, mode
# 具体实施方案,则为两种选择,修改节点数和增加每个节点的资源,在这里评估指标变为节约的时间/资源
# 可选方案:增加1个节点/添加相应的资源,判断方法:节约的时间/添加的资源,如果资源超过范围则丢弃该方案,直到找到合适的方案,备选方案为
# job_aim1 = reload_jobs(aim1, -1)
if aim1:
pop = np.random.randint(2, size=(POP_SIZE, 2 * DNA_SIZE))
pop_total = []
pop_total = existss(pop_total, pop, init=0)
print(len(pop_total))
for _ in range(N_GENERATIONS):
input_pop = []
for father in pop:
mother = pop[np.random.randint(POP_SIZE)]
input_pop.append([father, mother])
pool_cross = multiprocessing.Pool(6)
pop_tmp = pool_cross.map(crossover_and_mutation, input_pop)
pool_cross.close()
pool_cross.join()
# pop = crossover_and_mutation(input_pop)
pop = []
for item in pop_tmp:
for item2 in item:
pop.append(item2)
pop = np.array(pop)
# fitness = get_fitness1(aim1, pop,res_config0[aim1]['cpu_high'],res_config0[aim1]['memory_base'],res_config0[aim1]['worker'],res_config0[aim1]['ps'])
fitness = get_fitness1(aim1, pop, res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'],
res_config0[aim1]['worker'], res_config0[aim1]['ps'])
print("a fitness1:")
print(fitness)
pop = select(pop, fitness) # 选择生成新的种群
if len(pop_total) >= 2 ** (2 * DNA_SIZE) - 1:
break
print(len(pop_total))
method1 = {}
method2 = {}
if res_config0[aim1]['ps'] < math.ceil(res_config0[aim1]['worker'] / 4):
method1 = {'type': 1, 'ps': 1, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 1, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
else:
method1 = {'type': 1, 'ps': 0, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 0, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
delete_pop = kongxian(res_cpu, res_mem, res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'], layout_config0[aim1],
pop)
print("Unfit index are:")
print(delete_pop)
delete_pop = list(delete_pop)
# ac = np.delete(ac,[1,3,5],axis=0)
pop_new = np.delete(pop, delete_pop, axis=0)
if pop_new.size == 0 and not change_number:
print("Mode %d Can not find a way to aim1!!" % mode)
assign_config[aim1] = {}
elif pop_new.size == 0 and change_number:
if res_config0[aim1]['worker'] > 8:
assign_config[aim1] = {}
else:
assign_config[aim1] = method1
elif not change_number and pop_new.size > 0:
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1][
'cpu_source'] >= cpu_pre_limit and res_config0[aim1]['mem_source'] >= mem_pre_limit:
assign_config[aim1] = {}
else:
# fitness = get_fitness1(aim1, pop_new,res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'],
# res_config0[aim1]['worker'], res_config0[aim1]['ps'])
fitness = get_fitness1(aim1, pop_new, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'],
res_config0[aim1]['worker'], res_config0[aim1]['ps'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA(pop_new)
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu > cpu_pre_limit:
aim1_cpu = cpu_pre_limit
if aim1_mem > mem_pre_limit:
aim1_mem = mem_pre_limit
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
assign_config[aim1] = method2
elif change_number and pop_new.size > 0:
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1]['worker'] > 8 and res_config0[aim1]['cpu_source'] >= cpu_pre_limit and \
res_config0[aim1]['mem_source'] >= mem_pre_limit:
assign_config[aim1] = {}
else:
fitness = get_fitness1(aim1, pop_new, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'],
res_config0[aim1]['worker'], res_config0[aim1]['ps'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA(pop_new)
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu > cpu_pre_limit:
aim1_cpu = cpu_pre_limit
if aim1_mem > mem_pre_limit:
aim1_mem = mem_pre_limit
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
best_min_batch = predict_min(aim1, aim1_cpu, aim1_mem, rfr)
# method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
sco1 = res_config0[aim1]['need'] + 25 - (math.ceil(
res_config0[aim1]['total_step'] * res_config0[aim1]['worker'] / (
1 + res_config0[aim1]['worker'])) -
res_config0[aim1]['reload_point'] + 1) * res_config0[aim1][
'mini']
sco1 = sco1 / (0.75 * ((res_config0[aim1]['ps'] + method1['ps']) * 720 + (
method1['worker'] + res_config0[aim1]['worker']) * res_config0[aim1][
'cpu_source']) / job_basic.total_cpu + 0.25 * (
(res_config0[aim1]['ps'] + method1['ps']) * 1600 + (
method1['worker'] + res_config0[aim1]['worker']) * res_config0[aim1][
'mem_source']) / job_basic.total_mem)
sco2 = res_config0[aim1]['need'] - best_min_batch * res_config0[aim1]['remain_iter']
sco2 = sco2 / (0.75 * (res_config0[aim1]['ps'] * 720 + res_config0[aim1][
'worker'] * aim1_cpu) / job_basic.total_cpu + 0.25 * (
res_config0[aim1]['ps'] * 1600 + res_config0[aim1][
'worker'] * aim1_mem) / job_basic.total_mem)
# max([sco2, sco1])
if res_config0[aim1]['worker'] > 8:
if sco2 > 0:
assign_config[aim1] = method2
else:
assign_config[aim1] = {}
elif res_config0[aim1]['cpu_source'] >= cpu_pre_limit and res_config0[aim1][
'mem_source'] >= mem_pre_limit:
if sco1 > 0:
assign_config[aim1] = method1
else:
assign_config[aim1] = {}
else:
sco_tmp0 = sco1
if sco2 > sco1:
sco_tmp0 = sco2
if sco_tmp0 < 0:
print('Mode %d: Can not find useful method!!' % mode)
assign_config[aim1] = {}
else:
if sco1 > sco2:
assign_config[aim1] = method1
else:
assign_config[aim1] = method2
if assign_config[aim1]:
if assign_config[aim1]['type'] == 1:
res_condition = {}
res_load = [res_cpu[i] for i in node_list_global]
for no_k0 in node_list_global:
res_condition[res_cpu[no_k0]] = no_k0
list.sort(res_load)
deal_node = res_condition[res_load[-1]]
res_cpu[deal_node] -= res_config0[aim1]['cpu_source']
res_mem[deal_node] -= res_config0[aim1]['mem_source']
# layout_config0[aim1][deal_node]['worker']+=1
aim1_tmp_layout = layout_config0[aim1]
aim1_tlk = list(aim1_tmp_layout.keys())
if deal_node in aim1_tlk:
layout_config0[aim1][deal_node]['worker'] += 1
else:
layout_config0[aim1][deal_node] = {'ps': 0, 'worker': 1}
res_condition.pop(res_load[-1])
update_reload = res_load[-1] - res_config0[aim1]['cpu_source']
res_condition[update_reload] = deal_node
res_load[-1] = update_reload
if assign_config[aim1]['ps'] != 0:
list.sort(res_load)
deal_node = res_condition[res_load[-1]]
res_cpu[deal_node] -= 650
res_mem[deal_node] -= 1792
aim1_tmp_layout = layout_config0[aim1]
aim1_tlk = list(aim1_tmp_layout.keys())
if deal_node in aim1_tlk:
layout_config0[aim1][deal_node]['ps'] += 1
else:
layout_config0[aim1][deal_node] = {'ps': 1, 'worker': 0}
else:
update_layouts = layout_config0[aim1]
update_lay_key = list(update_layouts.keys())
for ulk in update_lay_key:
# method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
res_cpu[ulk] = res_cpu[ulk] + update_layouts[ulk]['worker'] * (
res_config0[aim1]['cpu_source'] - assign_config[aim1]['cpu'])
res_mem[ulk] = res_mem[ulk] + update_layouts[ulk]['worker'] * (
res_config0[aim1]['mem_source'] - assign_config[aim1]['mem'])
res_config0[aim1]['cpu_source'] = assign_config[aim1]['cpu']
res_config0[aim1]['mem_source'] = assign_config[aim1]['mem']
else:
assign_config[aim1] = {}
if not aim2:
assign_config[aim2] = {}
else:
aim1 = aim2
# old code
# job_aim2 = reload_jobs(aim1, -1)
pop = np.random.randint(2, size=(POP_SIZE, 2 * DNA_SIZE))
pop_total = []
pop_total = existss(pop_total, pop, init=0)
print(pop_total)
for _ in range(N_GENERATIONS):
input_pop = []
for father in pop:
mother = pop[np.random.randint(POP_SIZE)]
input_pop.append([father, mother])
pool_cross = multiprocessing.Pool(6)
pop_tmp = pool_cross.map(crossover_and_mutation, input_pop)
pool_cross.close()
pool_cross.join()
# pop = crossover_and_mutation(input_pop)
pop = []
for item in pop_tmp:
for item2 in item:
pop.append(item2)
pop = np.array(pop)
# fitness = get_fitness1(aim1, pop,res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'],
# res_config0[aim1]['worker'], res_config0[aim1]['ps'])
fitness = get_fitness1(aim1, pop, res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'],
res_config0[aim1]['worker'], res_config0[aim1]['ps'])
pop = select(pop, fitness) # 选择生成新的种群
if len(pop_total) >= 2 ** (2 * DNA_SIZE) - 1:
break
print(len(pop_total))
method1 = {}
method2 = {}
change_number = False
if res_config0[aim1]['ps'] < math.ceil(res_config0[aim1]['worker'] / 4):
method1 = {'type': 1, 'ps': 1, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 1, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
else:
method1 = {'type': 1, 'ps': 0, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 0, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
# "cpu_high": 8991,
# "memory_base": 8706,
delete_pop = kongxian(res_cpu, res_mem, res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'], layout_config0[aim1],
pop)
print("Unfit index are:")
print(delete_pop)
delete_pop = list(delete_pop)
# ac = np.delete(ac,[1,3,5],axis=0)
pop_new = np.delete(pop, delete_pop, axis=0)
if pop_new.size == 0 and not change_number:
print("Mode %d Can not find a way to aim2!!" % mode)
assign_config[aim1] = {}
elif pop_new.size == 0 and change_number:
if res_config0[aim1]['worker'] > 8:
assign_config[aim1] = {}
else:
assign_config[aim1] = method1
# assign_config[aim1] = method1
elif not change_number and pop_new.size > 0:
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1]['cpu_source'] >= cpu_pre_limit and res_config0[aim1][
'mem_source'] >= mem_pre_limit:
assign_config[aim1] = {}
# fitness = get_fitness1(aim1, pop_new,res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'],
# res_config0[aim1]['worker'], res_config0[aim1]['ps'])
else:
fitness = get_fitness1(aim1, pop_new, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'], res_config0[aim1]['cpu_high'],
res_config0[aim1]['memory_base'],
res_config0[aim1]['worker'], res_config0[aim1]['ps'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA(pop_new)
# aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_high'])
# aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['memory_base'])
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu > cpu_pre_limit:
aim1_cpu = cpu_pre_limit
if aim1_mem > mem_pre_limit:
aim1_mem = mem_pre_limit
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
assign_config[aim1] = method2
elif change_number and pop_new.size > 0:
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1]['worker'] > 8 and res_config0[aim1]['cpu_source'] >= cpu_pre_limit and \
res_config0[aim1]['mem_source'] >= mem_pre_limit:
assign_config[aim1] = {}
else:
fitness = get_fitness1(aim1, pop_new, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'], res_config0[aim1]['cpu_high'],
res_config0[aim1]['memory_base'],
res_config0[aim1]['worker'], res_config0[aim1]['ps'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA(pop_new)
# aim1_cpu = cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_high']
# aim1_mem = mem_mod[max_fitness_index] * res_config0[aim1]['memory_base']
aim1_cpu = cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source']
aim1_mem = mem_mod[max_fitness_index] * res_config0[aim1]['mem_source']
if aim1_cpu > cpu_pre_limit:
aim1_cpu = cpu_pre_limit
if aim1_mem > mem_pre_limit:
aim1_mem = mem_pre_limit
best_min_batch = predict_min(aim1, aim1_cpu, aim1_mem, rfr)
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
sco1 = res_config0[aim1]['need'] + 25 - (
math.ceil(res_config0[aim1]['total_step'] * res_config0[aim1]['worker'] / (
1 + res_config0[aim1]['worker'])) -
res_config0[aim1]['reload_point'] + 1) * res_config0[aim1]['mini']
sco1 = sco1 / (0.75 * ((res_config0[aim1]['ps'] + method1['ps']) * 720 + (
method1['worker'] + res_config0[aim1]['worker']) * res_config0[aim1][
'cpu_source']) / job_basic.total_cpu + 0.25 * (
(res_config0[aim1]['ps'] + method1['ps']) * 1600 + (
method1['worker'] + res_config0[aim1]['worker']) * res_config0[aim1][
'mem_source']) / job_basic.total_mem)
sco2 = res_config0[aim1]['need'] - best_min_batch * res_config0[aim1]['remain_iter']
sco2 = sco2 / (0.75 * (res_config0[aim1]['ps'] * 720 + res_config0[aim1][
'worker'] * aim1_cpu) / job_basic.total_cpu + 0.25 * (
res_config0[aim1]['ps'] * 1600 + res_config0[aim1][
'worker'] * aim1_mem) / job_basic.total_mem)
if res_config0[aim1]['worker'] > 8:
if sco2 > 0:
assign_config[aim1] = method2
else:
assign_config[aim1] = {}
elif res_config0[aim1]['cpu_source'] >= cpu_pre_limit and res_config0[aim1][
'mem_source'] >= mem_pre_limit:
if sco1 > 0:
assign_config[aim1] = method1
else:
assign_config[aim1] = {}
else:
if max(sco2, sco1) < 0:
print('Mode %d: Can not find useful method!!' % mode)
assign_config[aim1] = {}
else:
if sco1 > sco2:
assign_config[aim1] = method1
else:
assign_config[aim1] = method2
elif mode == 2:
# 一增一减,结合4和3即可轻松给出了
# 首先对于aim1,增加资源:
if not aim1 and not aim2:
print("Mode %d Do not find aim1 and aim2 to get modulateion!!" % mode)
return {}, mode
if aim1:
# job_aim1 = reload_jobs(aim1, -1)
pop = np.random.randint(2, size=(POP_SIZE, 2 * DNA_SIZE))
pop_total = []
pop_total = existss(pop_total, pop, init=0)
print(pop_total)
for _ in range(N_GENERATIONS):
input_pop = []
for father in pop:
mother = pop[np.random.randint(POP_SIZE)]
input_pop.append([father, mother])
pool_cross = multiprocessing.Pool(6)
pop_tmp = pool_cross.map(crossover_and_mutation, input_pop)
pool_cross.close()
pool_cross.join()
# pop = crossover_and_mutation(input_pop)
pop = []
for item in pop_tmp:
for item2 in item:
pop.append(item2)
pop = np.array(pop)
# fitness = get_fitness3()
# fitness = get_fitness3(aim1, pop, res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'])
fitness = get_fitness3(aim1, pop, res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'])
pop = select(pop, fitness) # 选择生成新的种群
if len(pop_total) >= 2 ** (2 * DNA_SIZE) - 1:
break
print(len(pop_total))
method1 = {}
method2 = {}
change_number = False
if res_config0[aim1]['ps'] < math.ceil(res_config0[aim1]['worker'] / 4):
method1 = {'type': 1, 'ps': 1, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 1, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
else:
method1 = {'type': 1, 'ps': 0, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 0, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
if not change_number:
method1 = {'type': 1, 'ps': 0, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 0, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
# "cpu_high": 8991,
# "memory_base": 8706,
delete_pop = kongxian(res_cpu, res_mem, res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'], layout_config0[aim1],
pop)
print("Unfit index are:")
print(delete_pop)
delete_pop = list(delete_pop)
# ac = np.delete(ac,[1,3,5],axis=0)
pop_new = np.delete(pop, delete_pop, axis=0)
if pop_new.size == 0 and not change_number:
print("Mode %d Can not find a way to aim1!!" % mode)
assign_config[aim1] = {}
elif pop_new.size == 0 and change_number:
if res_config0[aim1]['worker'] > 8:
assign_config[aim1] = {}
else:
assign_config[aim1] = method1
elif not change_number and pop_new.size > 0:
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1][
'cpu_source'] >= cpu_pre_limit and res_config0[aim1]['mem_source'] >= mem_pre_limit:
assign_config[aim1] = {}
else:
# fitness = get_fitness3(aim1, pop_new,res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'])
fitness = get_fitness3(aim1, pop_new, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA(pop_new)
# aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_high'])
# aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['memory_base'])
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu > cpu_pre_limit:
aim1_cpu = cpu_pre_limit
if aim1_mem > mem_pre_limit:
aim1_mem = mem_pre_limit
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
assign_config[aim1] = method2
elif change_number and pop_new.size > 0:
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1]['worker'] > 8 and res_config0[aim1]['cpu_source'] >= cpu_pre_limit and \
res_config0[aim1]['mem_source'] >= mem_pre_limit:
assign_config[aim1] = {}
else:
# fitness = get_fitness3(aim1, pop_new, res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'])
fitness = get_fitness3(aim1, pop_new, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA(pop_new)
# aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_high'])
# aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['memory_base'])
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu > cpu_pre_limit:
aim1_cpu = cpu_pre_limit
if aim1_mem > mem_pre_limit:
aim1_mem = mem_pre_limit
best_min_batch = predict_min(aim1, aim1_cpu, aim1_mem, rfr)
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
# sco1 = res_config0[aim1]['ne']
# res_config0[i]['need'] = need_time
# res_config0[i]['remain_time'] = tmp_re
# res_config0[i]['mini'] = now_mini
# res_config0[i]['remain_iter'] = tmp_iter
# res_config0[i]['reload_iter'] = reload_iter
# res_config0[i]['total_step'] = total_step
# res_config0[i]['ps'] = job_config["ps_replicas"]
# res_config0[i]['worker'] = job_config["worker_replicas"]
# "cpu_source": 6046,
# "mem_source": 19225,
sco1 = res_config0[aim1]['need'] + 25 - (math.ceil(
res_config0[aim1]['total_step'] * res_config0[aim1]['worker'] / (
1 + res_config0[aim1]['worker'])) -
res_config0[aim1][
'reload_point'] + 1) * res_config0[aim1]['mini']
# sco1 = sco1 / (0.75 * ((res_config0[aim1]['ps'] + method1['ps']) * 1000 + (
# method1['worker1'] + res_config0[aim1]['worker']) * res_config0[aim1][
# 'cpu_source']) / job_basic.total_cpu + 0.25 * (
# (res_config0[aim1]['ps'] + method1['ps']) * 2048 + (
# method1['worker'] + res_config0[aim1]['worker']) * res_config0[aim1][
# 'mem_source']) / job_basic.total_mem)
sco2 = res_config0[aim1]['need'] - best_min_batch * res_config0[aim1]['remain_iter']
# sco2 = sco2 / (0.75 * (res_config0[aim1]['ps'] * 1000 + res_config0[aim1][
# 'worker'] * aim1_cpu) / job_basic.total_cpu + 0.25 * (
# res_config0[aim1]['ps'] * 2048 + res_config0[aim1][
# 'worker'] * aim1_mem) / job_basic.total_mem)
if res_config0[aim1]['worker'] > 8:
if sco2 > 0:
assign_config[aim1] = method2
else:
assign_config[aim1] = {}
elif res_config0[aim1]['cpu_source'] >= cpu_pre_limit and res_config0[aim1][
'mem_source'] >= mem_pre_limit:
if sco1 > 0:
assign_config[aim1] = method1
else:
assign_config[aim1] = {}
else:
if max(sco2, sco1) < 0:
print('Mode %d: Can not find useful method!!' % mode)
assign_config[aim1] = {}
else:
if sco1 > sco2:
assign_config[aim1] = method1
else:
assign_config[aim1] = method2
# print("最优的基因型:", pop[max_fitness_index])
# print("(x, y):", (x[max_fitness_index], y[max_fitness_index]))
if assign_config[aim1]:
if assign_config[aim1]['type'] == 1:
res_condition = {}
res_load = [res_cpu[i] for i in node_list_global]
for no_k0 in node_list_global:
res_condition[res_cpu[no_k0]] = no_k0
print("Now res_condition:")
print(res_condition)
list.sort(res_load)
deal_node = res_condition[res_load[-1]]
print("Add a worker to %s" % deal_node)
res_cpu[deal_node] -= res_config0[aim1]['cpu_source']
res_mem[deal_node] -= res_config0[aim1]['mem_source']
aim1_tmp_layout = layout_config0[aim1]
aim1_tlk = list(aim1_tmp_layout.keys())
if deal_node in aim1_tlk:
layout_config0[aim1][deal_node]['worker'] += 1
else:
layout_config0[aim1][deal_node] = {'ps': 0, 'worker': 1}
res_condition.pop(res_load[-1])
update_reload = res_load[-1] - res_config0[aim1]['cpu_source']
res_condition[update_reload] = deal_node
res_load[-1] = update_reload
if assign_config[aim1]['ps'] != 0:
list.sort(res_load)
deal_node = res_condition[res_load[-1]]
print("Add a worker to %s" % deal_node)
res_cpu[deal_node] -= 650
res_mem[deal_node] -= 1792
aim1_tmp_layout = layout_config0[aim1]
aim1_tlk = list(aim1_tmp_layout.keys())
if deal_node in aim1_tlk:
layout_config0[aim1][deal_node]['ps'] += 1
else:
layout_config0[aim1][deal_node] = {'ps': 1, 'worker': 0}
else:
update_layouts = layout_config0[aim1]
# update_lay_key = list(update_layouts.keys())
update_lay_key = list(update_layouts.keys())
for ulk in update_lay_key:
# method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
res_cpu[ulk] = res_cpu[ulk] + update_layouts[ulk]['worker'] * (
res_config0[aim1]['cpu_source'] - assign_config[aim1]['cpu'])
res_mem[ulk] = res_mem[ulk] + update_layouts[ulk]['worker'] * (
res_config0[aim1]['mem_source'] - assign_config[aim1]['mem'])
res_config0[aim1]['cpu_source'] = assign_config[aim1]['cpu']
res_config0[aim1]['mem_source'] = assign_config[aim1]['mem']
if not aim2:
assign_config[aim2] = {}
else:
aim1 = aim2
# job_aim2 = reload_jobs(aim1, -1)
pop = np.random.randint(2, size=(POP_SIZE, 2 * DNA_SIZE))
pop_total = []
pop_total = existss(pop_total, pop, init=0)
print(pop_total)
for _ in range(N_GENERATIONS):
input_pop = []
for father in pop:
mother = pop[np.random.randint(POP_SIZE)]
input_pop.append([father, mother])
pool_cross = multiprocessing.Pool(6)
pop_tmp = pool_cross.map(crossover_and_mutation, input_pop)
pool_cross.close()
pool_cross.join()
# pop = crossover_and_mutation(input_pop)
pop = []
for item in pop_tmp:
for item2 in item:
pop.append(item2)
pop = np.array(pop)
# fitness = get_fitness3()
fitness = get_fitness4(aim1, pop, res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'],
res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['worker'], res_config0[aim1]['mini'])
pop = select(pop, fitness) # 选择生成新的种群
if len(pop_total) >= 2 ** (2 * DNA_SIZE) - 1:
break
print(len(pop_total))
method1 = {}
method2 = {}
change_number = False
if res_config0[aim1]['ps'] > math.ceil(res_config0[aim1]['worker'] / 2):
method1 = {'type': 1, 'ps': -1, 'worker': -1}
change_number = finish2(res_config0[aim1]['total_step'], res_config0[aim1]['remain_time'],
res_config0[aim1]['reload_point'], res_config0[aim1]['worker'],
res_config0[aim1]['ps'], 1, res_config0[aim1]['mini'])
else:
method1 = {'type': 1, 'ps': 0, 'worker': -1}
change_number = finish2(res_config0[aim1]['total_step'], res_config0[aim1]['remain_time'],
res_config0[aim1]['reload_point'], res_config0[aim1]['worker'],
res_config0[aim1]['ps'], 0, res_config0[aim1]['mini'])
delete_pop = finish(res_config0[aim1]['remain_iter'], pop, res_config0[aim1]['remain_time'],
res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'], rfr, aim1)
print("Unfit index are:")
print(delete_pop)
delete_pop = list(delete_pop)
# ac = np.delete(ac,[1,3,5],axis=0)
pop_new = np.delete(pop, delete_pop, axis=0)
if pop_new.size == 0 and not change_number:
print("Mode %d Can not find a way to aim1!!" % mode)
assign_config[aim1] = {}
elif pop_new.size == 0 and change_number:
assign_config[aim1] = method1
elif not change_number and pop_new.size > 0:
fitness = get_fitness4(aim1, pop_new, res_config0[aim1]['cpu_high'],
res_config0[aim1]['memory_base'], res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'], res_config0[aim1]['worker'],
res_config0[aim1]['mini'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA2(pop_new)
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu < 0.475 * res_config0[aim1]['cpu_high']:
aim1_cpu = math.ceil(0.475 * res_config0[aim1]['cpu_high'])
if aim1_mem < 1.03 * res_config0[aim1]['memory_base']:
aim1_mem = math.ceil(1.03 * res_config0[aim1]['memory_base'])
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
assign_config[aim1] = method2
elif change_number and pop_new.size > 0:
fitness = get_fitness4(aim1, pop_new, res_config0[aim1]['cpu_high'],
res_config0[aim1]['memory_base'],
res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'], res_config0[aim1]['worker'],
res_config0[aim1]['mini'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA2(pop_new)
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu < 0.475 * res_config0[aim1]['cpu_high']:
aim1_cpu = math.ceil(0.475 * res_config0[aim1]['cpu_high'])
if aim1_mem < 1.03 * res_config0[aim1]['memory_base']:
aim1_mem = math.ceil(1.03 * res_config0[aim1]['memory_base'])
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
sco1 = 0.75 * (abs(method1['ps']) * 720 + abs(method1['worker']) * res_config0[aim1][
'cpu_source']) / job_basic.total_cpu + 0.25 * (
abs(method1['ps']) * 1792 + abs(method1['worker']) * res_config0[aim1][
'mem_source']) / job_basic.total_mem
sco2 = 0.75 * (res_config0[aim1]['worker'] * (
res_config0[aim1]['cpu_source'] - aim1_cpu)) / job_basic.total_cpu + 0.25 * (
res_config0[aim1]['worker'] * (
res_config0[aim1]['mem_source'] - aim1_mem)) / job_basic.total_mem
if sco1 > sco2:
assign_config[aim1] = method1
else:
assign_config[aim1] = method2
elif mode == 3:
if not aim1 and not aim2:
print("Mode %d Do not find aim1 and aim2 to get modulateion!!" % mode)
return {}, mode
# 具体实施方案,则为两种选择,修改节点数和增加每个节点的资源,在这里评估指标变为节约的时间/资源
# 可选方案:增加1个节点/添加相应的资源,判断方法:节约的时间/添加的资源,如果资源超过范围则丢弃该方案,直到找到合适的方案,备选方案为
# job_aim1 = reload_jobs(aim1, -1)
if aim1:
pop = np.random.randint(2, size=(POP_SIZE, 2 * DNA_SIZE))
pop_total = []
pop_total = existss(pop_total, pop, init=0)
print(pop_total)
for _ in range(N_GENERATIONS):
input_pop = []
for father in pop:
mother = pop[np.random.randint(POP_SIZE)]
input_pop.append([father, mother])
pool_cross = multiprocessing.Pool(6)
pop_tmp = pool_cross.map(crossover_and_mutation, input_pop)
# pop = crossover_and_mutation(input_pop)
pool_cross.close()
pool_cross.join()
pop = []
for item in pop_tmp:
for item2 in item:
pop.append(item2)
pop = np.array(pop)
fitness = get_fitness3(aim1, pop, res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'])
pop = select(pop, fitness) # 选择生成新的种群
if len(pop_total) >= 2 ** (2 * DNA_SIZE) - 1:
break
print(len(pop_total))
method1 = {}
method2 = {}
change_number = False
if res_config0[aim1]['ps'] < math.ceil(res_config0[aim1]['worker'] / 4):
method1 = {'type': 1, 'ps': 1, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 1, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
else:
method1 = {'type': 1, 'ps': 0, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 0, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
if not change_number:
method1 = {'type': 1, 'ps': 0, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 0, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
# "cpu_high": 8991,
# "memory_base": 8706,
delete_pop = kongxian(res_cpu, res_mem, res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'], layout_config0[aim1],
pop)
print("Unfit index are:")
print(delete_pop)
delete_pop = list(delete_pop)
# ac = np.delete(ac,[1,3,5],axis=0)
pop_new = np.delete(pop, delete_pop, axis=0)
if pop_new.size == 0 and not change_number:
print("Mode %d Can not find a way to aim1!!" % mode)
assign_config[aim1] = {}
elif pop_new.size == 0 and change_number:
if res_config0[aim1]['worker'] > 8:
assign_config[aim1] = {}
else:
assign_config[aim1] = method1
elif not change_number and pop_new.size > 0:
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1][
'cpu_source'] >= cpu_pre_limit and res_config0[aim1]['mem_source'] >= mem_pre_limit:
assign_config[aim1] = {}
else:
fitness = get_fitness3(aim1, pop_new, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA(pop_new)
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu > cpu_pre_limit:
aim1_cpu = cpu_pre_limit
if aim1_mem > mem_pre_limit:
aim1_mem = mem_pre_limit
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
assign_config[aim1] = method2
elif change_number and pop_new.size > 0:
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1]['worker'] > 8 and res_config0[aim1]['cpu_source'] >= cpu_pre_limit and \
res_config0[aim1]['mem_source'] >= mem_pre_limit:
assign_config[aim1] = {}
else:
fitness = get_fitness3(aim1, pop_new, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA(pop_new)
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu > cpu_pre_limit:
aim1_cpu = cpu_pre_limit
if aim1_mem > mem_pre_limit:
aim1_mem = mem_pre_limit
best_min_batch = predict_min(aim1, aim1_cpu, aim1_mem, rfr)
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
sco1 = res_config0[aim1]['need'] + 25 - (math.ceil(
res_config0[aim1]['total_step'] * res_config0[aim1]['worker'] / (
1 + res_config0[aim1]['worker'])) -
res_config0[aim1][
'reload_point'] + 1) * res_config0[aim1]['mini']
# sco1 = sco1 / (0.75 * ((res_config0[aim1]['ps'] + method1['ps']) * 1000 + (
# method1['worker1'] + res_config0[aim1]['worker']) * res_config0[aim1][
# 'cpu_source']) / job_basic.total_cpu + 0.25 * (
# (res_config0[aim1]['ps'] + method1['ps']) * 2048 + (
# method1['worker'] + res_config0[aim1]['worker']) * res_config0[aim1][
# 'mem_source']) / job_basic.total_mem)
sco2 = res_config0[aim1]['need'] - best_min_batch * res_config0[aim1]['remain_iter']
# sco2 = sco2 / (0.75 * (res_config0[aim1]['ps'] * 1000 + res_config0[aim1][
# 'worker'] * aim1_cpu) / job_basic.total_cpu + 0.25 * (
# res_config0[aim1]['ps'] * 2048 + res_config0[aim1][
# remain_iter
# 'worker'] * aim1_mem) / job_basic.total_mem)
if res_config0[aim1]['worker'] > 8:
if sco2 > 0:
assign_config[aim1] = method2
else:
assign_config[aim1] = {}
elif res_config0[aim1]['cpu_source'] >= cpu_pre_limit and res_config0[aim1][
'mem_source'] >= mem_pre_limit:
if sco1 > 0:
assign_config[aim1] = method1
else:
assign_config[aim1] = {}
else:
if max(sco2, sco1) < 0:
print('Mode %d: Can not find useful method!!' % mode)
assign_config[aim1] = {}
else:
if sco1 > sco2:
assign_config[aim1] = method1
else:
assign_config[aim1] = method2
# print("最优的基因型:", pop[max_fitness_index])
# print("(x, y):", (x[max_fitness_index], y[max_fitness_index]))
if assign_config[aim1]:
if assign_config[aim1]['type'] == 1:
res_condition = {}
res_load = [res_cpu[i] for i in node_list_global]
for no_k0 in node_list_global:
res_condition[res_cpu[no_k0]] = no_k0
list.sort(res_load)
deal_node = res_condition[res_load[-1]]
res_cpu[deal_node] -= res_config0[aim1]['cpu_source']
res_mem[deal_node] -= res_config0[aim1]['mem_source']
# layout_config0[aim1][deal_node]['worker']+=1
aim1_tmp_layout = layout_config0[aim1]
aim1_tlk = list(aim1_tmp_layout.keys())
if deal_node in aim1_tlk:
layout_config0[aim1][deal_node]['worker'] += 1
else:
layout_config0[aim1][deal_node] = {'ps': 0, 'worker': 1}
res_condition.pop(res_load[-1])
update_reload = res_load[-1] - res_config0[aim1]['cpu_source']
res_condition[update_reload] = deal_node
res_load[-1] = update_reload
if assign_config[aim1]['ps'] != 0:
list.sort(res_load)
deal_node = res_condition[res_load[-1]]
res_cpu[deal_node] -= 650
res_mem[deal_node] -= 1792
aim1_tmp_layout = layout_config0[aim1]
aim1_tlk = list(aim1_tmp_layout.keys())
if deal_node in aim1_tlk:
layout_config0[aim1][deal_node]['ps'] += 1
else:
layout_config0[aim1][deal_node] = {'ps': 1, 'worker': 0}
else:
update_layouts = layout_config0[aim1]
# update_lay_key = list(update_layouts)
update_lay_key = list(update_layouts.keys())
for ulk in update_lay_key:
# method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
res_cpu[ulk] = res_cpu[ulk] + update_layouts[ulk]['worker'] * (
res_config0[aim1]['cpu_source'] - assign_config[aim1]['cpu'])
res_mem[ulk] = res_mem[ulk] + update_layouts[ulk]['worker'] * (
res_config0[aim1]['mem_source'] - assign_config[aim1]['mem'])
res_config0[aim1]['cpu_source'] = assign_config[aim1]['cpu']
res_config0[aim1]['mem_source'] = assign_config[aim1]['mem']
else:
assign_config[aim1] = {}
if not aim2:
assign_config[aim2] = {}
else:
aim1 = aim2
# job_aim2 = reload_jobs(aim1, -1)
pop = np.random.randint(2, size=(POP_SIZE, 2 * DNA_SIZE))
pop_total = []
pop_total = existss(pop_total, pop, init=0)
print(pop_total)
for _ in range(N_GENERATIONS):
input_pop = []
for father in pop:
mother = pop[np.random.randint(POP_SIZE)]
input_pop.append([father, mother])
pool_cross = multiprocessing.Pool(6)
pop_tmp = pool_cross.map(crossover_and_mutation, input_pop)
pool_cross.close()
pool_cross.join()
# pop = crossover_and_mutation(input_pop)
pop = []
for item in pop_tmp:
for item2 in item:
pop.append(item2)
pop = np.array(pop)
fitness = get_fitness3(aim1, pop, res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'],
res_config0[aim1]['memory_base'])
pop = select(pop, fitness) # 选择生成新的种群
if len(pop_total) >= 2 ** (2 * DNA_SIZE) - 1:
break
print(len(pop_total))
method1 = {}
method2 = {}
change_number = False
if res_config0[aim1]['ps'] < math.ceil(res_config0[aim1]['worker'] / 4):
method1 = {'type': 1, 'ps': 1, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 1, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
else:
method1 = {'type': 1, 'ps': 0, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 0, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
if not change_number:
method1 = {'type': 1, 'ps': 0, 'worker': 1}
change_number = kongxian2(node_list_global, res_cpu, res_mem, 0, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'])
delete_pop = kongxian(res_cpu, res_mem, res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'], layout_config0[aim1],
pop)
print("Unfit index are:")
print(delete_pop)
delete_pop = list(delete_pop)
# ac = np.delete(ac,[1,3,5],axis=0)
pop_new = np.delete(pop, delete_pop, axis=0)
if pop_new.size == 0 and not change_number:
print("Mode %d Can not find a way to aim1!!" % mode)
assign_config[aim1] = {}
elif pop_new.size == 0 and change_number:
if res_config0[aim1]['worker'] > 8:
assign_config[aim1] = {}
else:
assign_config[aim1] = method1
elif not change_number and pop_new.size > 0:
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1][
'cpu_source'] >= cpu_pre_limit and res_config0[aim1]['mem_source'] >= mem_pre_limit:
assign_config[aim1] = {}
else:
fitness = get_fitness3(aim1, pop_new, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'], res_config0[aim1]['cpu_high'],
res_config0[aim1]['memory_base'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA(pop_new)
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu > cpu_pre_limit:
aim1_cpu = cpu_pre_limit
if aim1_mem > mem_pre_limit:
aim1_mem = mem_pre_limit
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
assign_config[aim1] = method2
elif change_number and pop_new.size > 0:
cpu_pre_limit = math.ceil(XBOUND[-1] * 1.478 * res_config0[aim1]['cpu_high'])
mem_pre_limit = math.ceil(YBOUND[-1] * 1.682 * res_config0[aim1]['memory_base'])
if res_config0[aim1]['worker'] > 8 and res_config0[aim1]['cpu_source'] >= cpu_pre_limit and \
res_config0[aim1]['mem_source'] >= mem_pre_limit:
assign_config[aim1] = {}
else:
fitness = get_fitness3(aim1, pop_new, res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'], res_config0[aim1]['cpu_high'],
res_config0[aim1]['memory_base'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA(pop_new)
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu > cpu_pre_limit:
aim1_cpu = cpu_pre_limit
if aim1_mem > mem_pre_limit:
aim1_mem = mem_pre_limit
best_min_batch = predict_min(aim1, aim1_cpu, aim1_mem, rfr)
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
sco1 = res_config0[aim1]['need'] + 25 - (
math.ceil(res_config0[aim1]['total_step'] * res_config0[aim1]['worker'] / (
1 + res_config0[aim1]['worker'])) -
res_config0[aim1]['reload_point'] + 1) * res_config0[aim1]['mini']
# sco1 = sco1 / (0.75 * ((res_config0[aim1]['ps'] + method1['ps']) * 1000 + (
# method1['worker1'] + res_config0[aim1]['worker']) * res_config0[aim1][
# 'cpu_source']) / job_basic.total_cpu + 0.25 * (
# (res_config0[aim1]['ps'] + method1['ps']) * 2048 + (
# method1['worker'] + res_config0[aim1]['worker']) * res_config0[aim1][
# 'mem_source']) / job_basic.total_mem)
sco2 = res_config0[aim1]['need'] - best_min_batch * res_config0[aim1]['remain_iter']
# sco2 = sco2 / (0.75 * (res_config0[aim1]['ps'] * 1000 + res_config0[aim1][
# 'worker'] * aim1_cpu) / job_basic.total_cpu + 0.25 * (
# res_config0[aim1]['ps'] * 2048 + res_config0[aim1][
# 'worker'] * aim1_mem) / job_basic.total_mem)
if res_config0[aim1]['worker'] > 8:
if sco2 > 0:
assign_config[aim1] = method2
else:
assign_config[aim1] = {}
elif res_config0[aim1]['cpu_source'] >= cpu_pre_limit and res_config0[aim1][
'mem_source'] >= mem_pre_limit:
if sco1 > 0:
assign_config[aim1] = method1
else:
assign_config[aim1] = {}
else:
if max(sco2, sco1) < 0:
print('Mode %d: Can not find useful method!!' % mode)
assign_config[aim1] = {}
else:
if sco1 > sco2:
assign_config[aim1] = method1
else:
assign_config[aim1] = method2
elif mode == 4:
if not aim1 and not aim2:
print("Mode %d Do not find aim1 and aim2 to get modulateion!!" % mode)
return {}, mode
if aim1:
# job_aim1 = reload_jobs(aim1, -1)
pop = np.random.randint(2, size=(POP_SIZE, 2 * DNA_SIZE))
pop_total = []
pop_total = existss(pop_total, pop, init=0)
print(pop_total)
for _ in range(N_GENERATIONS):
input_pop = []
for father in pop:
mother = pop[np.random.randint(POP_SIZE)]
input_pop.append([father, mother])
pool_cross = multiprocessing.Pool(6)
pop_tmp = pool_cross.map(crossover_and_mutation, input_pop)
pool_cross.close()
pool_cross.join()
# pop = crossover_and_mutation(input_pop)
pop = []
for item in pop_tmp:
for item2 in item:
pop.append(item2)
pop = np.array(pop)
# fitness = get_fitness3()
fitness = get_fitness4(aim1, pop, res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'],
res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['worker'], res_config0[aim1]['mini'])
pop = select(pop, fitness) # 选择生成新的种群
if len(pop_total) >= 2 ** (2 * DNA_SIZE) - 1:
break
print(len(pop_total))
method1 = {}
method2 = {}
change_number = False
if res_config0[aim1]['ps'] > math.ceil(res_config0[aim1]['worker'] / 2):
method1 = {'type': 1, 'ps': -1, 'worker': -1}
change_number = finish2(res_config0[aim1]['total_step'], res_config0[aim1]['remain_time'],
res_config0[aim1]['reload_point'], res_config0[aim1]['worker'],
res_config0[aim1]['ps'], 1, res_config0[aim1]['mini'])
else:
method1 = {'type': 1, 'ps': 0, 'worker': -1}
change_number = finish2(res_config0[aim1]['total_step'], res_config0[aim1]['remain_time'],
res_config0[aim1]['reload_point'], res_config0[aim1]['worker'],
res_config0[aim1]['ps'], 0, res_config0[aim1]['mini'])
delete_pop = finish(res_config0[aim1]['remain_iter'], pop, res_config0[aim1]['remain_time'],
res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'], rfr, aim1)
print("Unfit index are:")
print(delete_pop)
delete_pop = list(delete_pop)
# ac = np.delete(ac,[1,3,5],axis=0)
pop_new = np.delete(pop, delete_pop, axis=0)
if pop_new.size == 0 and not change_number:
print("Mode %d Can not find a way to aim1!!" % mode)
assign_config[aim1] = {}
elif pop_new.size == 0 and change_number:
assign_config[aim1] = method1
elif not change_number and pop_new.size > 0:
fitness = get_fitness4(aim1, pop_new, res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'],
res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'], res_config0[aim1]['worker'],
res_config0[aim1]['mini'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA2(pop_new)
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu < 0.475 * res_config0[aim1]['cpu_high']:
aim1_cpu = math.ceil(0.475 * res_config0[aim1]['cpu_high'])
if aim1_mem < 1.03 * res_config0[aim1]['memory_base']:
aim1_mem = math.ceil(1.03 * res_config0[aim1]['memory_base'])
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
assign_config[aim1] = method2
elif change_number and pop_new.size > 0:
fitness = get_fitness4(aim1, pop_new, res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'],
res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'], res_config0[aim1]['worker'],
res_config0[aim1]['mini'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA2(pop_new)
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu < 0.475 * res_config0[aim1]['cpu_high']:
aim1_cpu = math.ceil(0.475 * res_config0[aim1]['cpu_high'])
if aim1_mem < 1.03 * res_config0[aim1]['memory_base']:
aim1_mem = math.ceil(1.03 * res_config0[aim1]['memory_base'])
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
sco1 = 0.75 * (abs(method1['ps']) * 740 + abs(method1['worker']) * res_config0[aim1][
'cpu_source']) / job_basic.total_cpu + 0.25 * (
abs(method1['ps']) * 1800 + abs(method1['worker']) * res_config0[aim1][
'mem_source']) / job_basic.total_mem
sco2 = 0.75 * (res_config0[aim1]['worker'] * (
res_config0[aim1]['cpu_source'] - aim1_cpu)) / job_basic.total_cpu + 0.25 * (
res_config0[aim1]['worker'] * (
res_config0[aim1]['mem_source'] - aim1_mem)) / job_basic.total_mem
if sco1 > sco2:
assign_config[aim1] = method1
else:
assign_config[aim1] = method2
else:
assign_config[aim1] = {}
if not aim2:
assign_config[aim2] = {}
else:
aim1 = aim2
# job_aim2 = reload_jobs(aim1, -1)
pop = np.random.randint(2, size=(POP_SIZE, 2 * DNA_SIZE))
pop_total = []
pop_total = existss(pop_total, pop, init=0)
print(pop_total)
for _ in range(N_GENERATIONS):
input_pop = []
for father in pop:
mother = pop[np.random.randint(POP_SIZE)]
input_pop.append([father, mother])
pool_cross = multiprocessing.Pool(6)
pop_tmp = pool_cross.map(crossover_and_mutation, input_pop)
pool_cross.close()
pool_cross.join()
# pop = crossover_and_mutation(input_pop)
pop = []
for item in pop_tmp:
for item2 in item:
pop.append(item2)
pop = np.array(pop)
# fitness = get_fitness3()
fitness = get_fitness4(aim1, pop, res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'],
res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['worker'], res_config0[aim1]['mini'])
pop = select(pop, fitness) # 选择生成新的种群
if len(pop_total) >= 2 ** (2 * DNA_SIZE) - 1:
break
print(len(pop_total))
method1 = {}
method2 = {}
change_number = False
if res_config0[aim1]['ps'] > math.ceil(res_config0[aim1]['worker'] / 2):
method1 = {'type': 1, 'ps': -1, 'worker': -1}
change_number = finish2(res_config0[aim1]['total_step'], res_config0[aim1]['remain_time'],
res_config0[aim1]['reload_point'], res_config0[aim1]['worker'],
res_config0[aim1]['ps'], 1, res_config0[aim1]['mini'])
else:
method1 = {'type': 1, 'ps': 0, 'worker': -1}
change_number = finish2(res_config0[aim1]['total_step'], res_config0[aim1]['remain_time'],
res_config0[aim1]['reload_point'], res_config0[aim1]['worker'],
res_config0[aim1]['ps'], 0, res_config0[aim1]['mini'])
delete_pop = finish(res_config0[aim1]['remain_iter'], pop, res_config0[aim1]['remain_time'],
res_config0[aim1]['cpu_source'], res_config0[aim1]['mem_source'],
res_config0[aim1]['cpu_high'], res_config0[aim1]['memory_base'], rfr, aim1)
print("Unfit index are:")
print(delete_pop)
delete_pop = list(delete_pop)
# ac = np.delete(ac,[1,3,5],axis=0)
pop_new = np.delete(pop, delete_pop, axis=0)
if pop_new.size == 0 and not change_number:
print("Mode %d Can not find a way to aim1!!" % mode)
assign_config[aim1] = {}
elif pop_new.size == 0 and change_number:
assign_config[aim1] = method1
elif not change_number and pop_new.size > 0:
fitness = get_fitness4(aim1, pop_new, res_config0[aim1]['cpu_high'],
res_config0[aim1]['memory_base'], res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'], res_config0[aim1]['worker'],
res_config0[aim1]['mini'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA2(pop_new)
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu < 0.475 * res_config0[aim1]['cpu_high']:
aim1_cpu = math.ceil(0.475 * res_config0[aim1]['cpu_high'])
if aim1_mem < 1.03 * res_config0[aim1]['memory_base']:
aim1_mem = math.ceil(1.03 * res_config0[aim1]['memory_base'])
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
assign_config[aim1] = method2
elif change_number and pop_new.size > 0:
fitness = get_fitness4(aim1, pop_new, res_config0[aim1]['cpu_high'],
res_config0[aim1]['memory_base'],
res_config0[aim1]['cpu_source'],
res_config0[aim1]['mem_source'], res_config0[aim1]['worker'],
res_config0[aim1]['mini'])
max_fitness_index = np.argmax(fitness)
print("max_fitness:", fitness[max_fitness_index])
cpu_mod, mem_mod = translateDNA2(pop_new)
aim1_cpu = math.ceil(cpu_mod[max_fitness_index] * res_config0[aim1]['cpu_source'])
aim1_mem = math.ceil(mem_mod[max_fitness_index] * res_config0[aim1]['mem_source'])
if aim1_cpu < 0.475 * res_config0[aim1]['cpu_high']:
aim1_cpu = math.ceil(0.475 * res_config0[aim1]['cpu_high'])
if aim1_mem < 1.03 * res_config0[aim1]['memory_base']:
aim1_mem = math.ceil(1.03 * res_config0[aim1]['memory_base'])
method2 = {'type': 2, 'cpu': aim1_cpu, 'mem': aim1_mem}
sco1 = 0.75 * (abs(method1['ps']) * 740 + abs(method1['worker']) * res_config0[aim1][
'cpu_source']) / job_basic.total_cpu + 0.25 * (
abs(method1['ps']) * 1800 + abs(method1['worker']) * res_config0[aim1][
'mem_source']) / job_basic.total_mem
sco2 = 0.75 * (res_config0[aim1]['worker'] * (
res_config0[aim1]['cpu_source'] - aim1_cpu)) / job_basic.total_cpu + 0.25 * (
res_config0[aim1]['worker'] * (
res_config0[aim1]['mem_source'] - aim1_mem)) / job_basic.total_mem
if sco1 > sco2:
assign_config[aim1] = method1
else:
assign_config[aim1] = method2
else:
print("Mode %d Do not find fit job to get modluation!!" % mode)
return {}, mode
return assign_config, mode
def parse():
parser = argparse.ArgumentParser(description="Node Monitor")
parser.add_argument('--save_path', default='/tfdata/nodebase', help='save path')
parser.add_argument('--database',default="NODEMESSAGE",help="save database")
parser.add_argument('--derivation',default=10,help='sampling rate')
parser.add_argument('--measurement',default="NODEMESSAGE",help="save measurement")
# parser.add_argument('--train_pg', action='store_true', help='whether train policy gradient')
# parser.add_argument('--train_dqn', action='store_true', help='whether train DQN')
# parser.add_argument('--test_pg', action='store_true', help='whether test policy gradient')
# parser.add_argument('--test_dqn', action='store_true', help='whether test DQN')
args = parser.parse_args()
return args
def update_token():
cacheData = os.popen(
"echo $(kubectl describe secret $(kubectl get secret -n kube-system | grep ^admin-user | awk '{print $1}') -n kube-system | grep -E '^token'| awk '{print $2}')").read()
cacheToken = cacheData[:-1]
newToken = str(cacheToken)
return newToken
def make_headers(Token):
text = 'Bearer ' + Token
headers = {'Authorization': text}
return headers
def catch_message(url):
global aToken
aToken = update_token()
headers = make_headers(aToken)
response = requests.get(url,headers=headers,verify=False)
res_json = response.json()
return res_json
def database_create(databasename):
database_list = Global_Influx.Client_all.get_list_database()
creating = True
for db in database_list:
dbl = list(db.values())
if databasename in dbl:
creating = False
break
if creating:
Global_Influx.Client_all.create_database(databasename)
def match_cpu(raw_data):
cache = raw_data[:-1]
matched_data = math.ceil(int(cache)/1e6)
return matched_data
def match_memory(raw_data):
cache = raw_data[:-2]
matched_data = math.ceil(int(cache)/1024)
return matched_data
def match_timestamp(raw_data):
EPOCH = UTC.localize(datetime.utcfromtimestamp(0))
timestamp = parser.parse(raw_data)
if not timestamp.tzinfo:
print("XXX")
timestamp = UTC.localize(timestamp)
s = (timestamp - EPOCH).total_seconds()
return int(s)
def make_label_to_nodes(tasks2,base_job_name):
print("start a labeling function!!!")
base_job = reload_jobs_aim(base_job_name,-1)
print("reload success!!!")
try:
tasks2["label"] = True
print("start to label nodes!!!")
point_base, cpu_base, memory_base, point_base_list = base_job.schedule_label()
# tasks2[(str())]
keyss = list(point_base.keys())
tmp_tasks = tasks2['rank']
tmp_task2 = tasks2['cpu']
tmp_task3 = tasks2['mem']
for kk in keyss:
tmp_tasks[kk] = point_base_list.index(point_base[kk])
tmp_task2[kk] = base_job.node_cpu[kk] - cpu_base[kk]*base_job.node_cpu[kk]
tmp_task3[kk] = base_job.node_memory[kk] - memory_base[kk]*base_job.node_memory[kk]
tasks2['rank'] = tmp_tasks
tasks2['cpu'] = tmp_task2
tasks2['mem'] = tmp_task3
time.sleep(1.5)
tasks2["label"] = False
print("finish a label procedure")
time.sleep(30.5)
except Exception as eee:
print("label nodes have errors:" + str(eee))
# print(eee)
tasks2["label"] = False
# time.sleep(45)
print("try with err again!!!")
while True:
time.sleep(72)
try:
tasks2["label"] = True
print("start to label nodes!!!")
point_base, cpu_base, memory_base, point_base_list = base_job.schedule_label()
# tasks2[(str())]
keyss = list(point_base.keys())
tmp_tasks = tasks2['rank']
tmp_task2 = tasks2['cpu']
tmp_task3 = tasks2['mem']
for kk in keyss:
tmp_tasks[kk] = point_base_list.index(point_base[kk])
tmp_task2[kk] = base_job.node_cpu[kk] - cpu_base[kk]*base_job.node_cpu[kk]
tmp_task3[kk] = base_job.node_memory[kk] - memory_base[kk]*base_job.node_memory[kk]
tasks2['rank'] = tmp_tasks
tasks2['cpu'] = tmp_task2
tasks2['mem'] = tmp_task3
time.sleep(1.5)
tasks2["label"] = False
print("finish a label procedure")
time.sleep(72)
except Exception as eee:
print("label nodes have errors:"+str(eee))
# print(eee)
tasks2["label"] = False
time.sleep(45)
print("try with err again!!!")
def generate_item(response,measurement):
node_cpu = {}
node_cpu['k8s-master'] = 64000 - 2500
node_cpu['k8s-worker0'] = 24000 - 240
node_cpu['k8s-worker2'] = 24000 - 650
node_cpu['k8s-worker1'] = 16000 - 300
node_cpu['k8s-worker3'] = 24000 - 360
node_cpu['k8s-worker4'] = 24000 - 360
node_cpu['k8s-worker5'] = 32000 - 320
node_cpu['k8s-worker6'] = 24000 - 240
node_cpu['k8s-worker7'] = 24000 - 240
node_cpu['k8s-worker8'] = 24000 - 240
# node_cpu['k8s-worker9'] = 16000 - 240
node_cpu['k8s-worker10'] = 24000 - 200
node_cpu['k8s-worker11'] = 24000 - 200
node_cpu['k8s-worker12'] = 24000 - 240
node_cpu['k8s-worker13'] = 24000 - 240
node_cpu['k8s-worker14'] = 24000 - 240
node_cpu['k8s-worker15'] = 32000 - 220
node_cpu['k8s-worker16'] = 24000 - 240
node_cpu['k8s-worker17'] = 24000 - 210
# node_cpu['k8s-worker18'] = 16000 - 150
node_cpu['k8s-worker19'] = 32000 - 240
# node_cpu['k8s-worker20'] = 24000 - 150
node_memory = {}
node_memory['k8s-master'] = float(251 * 1024 - 12000)
node_memory['k8s-worker0'] = float(94 * 1024 - 1400)
node_memory['k8s-worker2'] = float(94 * 1024 - 4200)
node_memory['k8s-worker1'] = float(125 * 1024 - 1200)
node_memory['k8s-worker3'] = float(94 * 1024 - 1800)
node_memory['k8s-worker4'] = float(188 * 1024 - 1000)
node_memory['k8s-worker5'] = float(125 * 1024 - 1800)
node_memory['k8s-worker6'] = float(94 * 1024 - 1200)
node_memory['k8s-worker7'] = float(94 * 1024 - 3000)
node_memory['k8s-worker8'] = float(94 * 1024 - 1250)
# node_memory['k8s-worker9'] = float(62 * 1024 - 1600)
node_memory['k8s-worker10'] = float(94 * 1024 - 1200)
node_memory['k8s-worker11'] = float(94 * 1024 - 1400)
# node_memory['k8s-worker12'] = float(62 * 1024 - 2000)
# node_memory['k8s-worker13'] = float(62 * 1024 - 2000)
node_memory['k8s-worker12'] = float(94 * 1024 - 1500)
node_memory['k8s-worker13'] = float(94 * 1024 - 1400)
node_memory['k8s-worker14'] = float(94 * 1024 - 1800)
# node_memory['k8s-worker15'] = float(62 * 1024 - 2000)
node_memory['k8s-worker15'] = float(125 * 1024 - 1800)
# node_memory['k8s-worker16'] = float(62 * 1024 - 2000)
node_memory['k8s-worker16'] = float(94 * 1024 - 1800)
# node_memory['k8s-worker17'] = float(94 * 1024 - 2000)
node_memory['k8s-worker17'] = float(94 * 1024 - 1400)
# node_memory['k8s-worker18'] = float(62 * 1024 - 2000)
node_memory['k8s-worker19'] = float(125 * 1024 - 1400)
points = []
# content = {}
timestamp = response['items'][0]['metadata']['creationTimestamp']
for item in response['items']:
content = {
'measurement': measurement,
'tags':{
"nodes": item['metadata']['name']
},
'fields': {
'cpu': match_cpu(item['usage']['cpu']),
'memory': match_memory(item['usage']['memory']),
'cpu_percent': float(match_cpu(item['usage']['cpu'])/node_cpu[item['metadata']['name']]),
'memory_percent': float(match_memory(item['usage']['memory']) / node_memory[item['metadata']['name']])
},
'time': match_timestamp(timestamp)
}
points.append(content)
return points
def DeletefromDB(Client,DatabaseName):
databases = Client.get_list_database()
for Cn in databases:
if DatabaseName in Cn.values():
Client.drop_database(DatabaseName)
break
class Node_mess(multiprocessing.Process):
def __init__(self,url,args,tasks,v1):
multiprocessing.Process.__init__(self)
self.url = url
self.args = args
self.derivation = args.derivation
self.time_mess = {}
self.cpu_mess = {}
self.memory_mess = {}
self.cpu_per = {}
self.memory_per = {}
self.node_cpu = {}
self.node_cpu['k8s-master'] = 64000 - 2500
self.node_cpu['k8s-worker0'] = 24000 - 240
self.node_cpu['k8s-worker2'] = 24000 - 650
self.node_cpu['k8s-worker1'] = 16000 - 300
self.node_cpu['k8s-worker3'] = 24000 - 360
self.node_cpu['k8s-worker4'] = 24000 - 360
self.node_cpu['k8s-worker5'] = 32000 - 320
self.node_cpu['k8s-worker6'] = 24000 - 240
self.node_cpu['k8s-worker7'] = 24000 - 240
self.node_cpu['k8s-worker8'] = 24000 - 240
# self.node_cpu['k8s-worker9'] = 16000 - 240
self.node_cpu['k8s-worker10'] = 24000 - 200
self.node_cpu['k8s-worker11'] = 24000 - 200
self.node_cpu['k8s-worker12'] = 24000 - 240
self.node_cpu['k8s-worker13'] = 24000 - 240
self.node_cpu['k8s-worker14'] = 24000 - 240
self.node_cpu['k8s-worker15'] = 32000 - 220
self.node_cpu['k8s-worker16'] = 24000 - 240
self.node_cpu['k8s-worker17'] = 24000 - 210
# node_cpu['k8s-worker18'] = 16000 - 150
self.node_cpu['k8s-worker19'] = 32000 - 240
self.node_memory = {}
self.node_memory['k8s-master'] = float(251 * 1024 - 10000)
self.node_memory['k8s-worker0'] = float(94 * 1024 - 1400)
self.node_memory['k8s-worker2'] = float(94 * 1024 - 3200)
self.node_memory['k8s-worker1'] = float(125 * 1024 - 1600)
self.node_memory['k8s-worker3'] = float(94 * 1024 - 1200)
self.node_memory['k8s-worker4'] = float(188 * 1024 - 1200)
self.node_memory['k8s-worker5'] = float(125 * 1024 - 1800)
self.node_memory['k8s-worker6'] = float(94 * 1024 - 1200)
self.node_memory['k8s-worker7'] = float(94 * 1024 - 1400)
self.node_memory['k8s-worker8'] = float(94 * 1024 - 1250)
# self.node_memory['k8s-worker9'] = float(62 * 1024 - 1600)
self.node_memory['k8s-worker10'] = float(94 * 1024 - 1200)
self.node_memory['k8s-worker11'] = float(94 * 1024 - 1400)
# node_memory['k8s-worker12'] = float(62 * 1024 - 2000)
# node_memory['k8s-worker13'] = float(62 * 1024 - 2000)
self.node_memory['k8s-worker12'] = float(94 * 1024 - 1500)
self.node_memory['k8s-worker13'] = float(94 * 1024 - 1400)
self.node_memory['k8s-worker14'] = float(94 * 1024 - 1800)
# node_memory['k8s-worker15'] = float(62 * 1024 - 2000)
self.node_memory['k8s-worker15'] = float(125 * 1024 - 1800)
# node_memory['k8s-worker16'] = float(62 * 1024 - 2000)
self.node_memory['k8s-worker16'] = float(94 * 1024 - 1800)
# node_memory['k8s-worker17'] = float(94 * 1024 - 2000)
self.node_memory['k8s-worker17'] = float(94 * 1024 - 1400)
# node_memory['k8s-worker18'] = float(62 * 1024 - 2000)
self.node_memory['k8s-worker19'] = float(125 * 1024 - 1400)
self.arg = args
self.tasks = tasks
self.v1 = v1
self.database = args.database
self.measurement = args.measurement
self.save_path = args.save_path
if not os.path.exists(self.arg.save_path):
os.makedirs(self.arg.save_path)
database_create(self.database)
self.client = influxdb.InfluxDBClient('192.168.128.10',port=8086,username='admin',password='admin',database=self.database)
def run(self):
print(multiprocessing.current_process().pid)
print(os.getpid())
response = catch_message(self.url)
self.time_mess['creation'] = [response['items'][0]['metadata']['creationTimestamp']]
self.cpu_mess['creation'] = [response['items'][0]['metadata']['creationTimestamp']]
self.memory_mess['creation'] = [response['items'][0]['metadata']['creationTimestamp']]
self.cpu_per['creation'] = [response['items'][0]['metadata']['creationTimestamp']]
self.memory_per['creation'] = [response['items'][0]['metadata']['creationTimestamp']]
for item in response['items']:
self.time_mess[item['metadata']['name']] = [item['timestamp']]
self.cpu_mess[item['metadata']['name']] = [match_cpu(item['usage']['cpu'])]
self.memory_mess[item['metadata']['name']] = [match_memory(item['usage']['memory'])]
self.cpu_per[item['metadata']['name']] = [float(match_cpu(item['usage']['cpu'])/self.node_cpu[item['metadata']['name']])]
self.memory_per[item['metadata']['name']] = [float(match_memory(item['usage']['memory']) / self.node_memory[item['metadata']['name']])]
self.client.write_points(generate_item(response,self.measurement),'s',database=self.database)
time.sleep(self.derivation)
while True:
try:
response = catch_message(self.url)
self.time_mess['creation'].append(response['items'][0]['metadata']['creationTimestamp'])
self.cpu_mess['creation'].append(response['items'][0]['metadata']['creationTimestamp'])
self.memory_mess['creation'].append(response['items'][0]['metadata']['creationTimestamp'])
self.cpu_per['creation'].append(response['items'][0]['metadata']['creationTimestamp'])
self.memory_per['creation'].append(response['items'][0]['metadata']['creationTimestamp'])
for item in response['items']:
self.time_mess[item['metadata']['name']].append(item['timestamp'])
self.cpu_mess[item['metadata']['name']].append(match_cpu(item['usage']['cpu']))
self.memory_mess[item['metadata']['name']].append(match_memory(item['usage']['memory']))
self.cpu_per[item['metadata']['name']].append(
float(match_cpu(item['usage']['cpu']) / self.node_cpu[item['metadata']['name']]))
self.memory_per[item['metadata']['name']].append(
float(match_memory(item['usage']['memory']) / self.node_memory[item['metadata']['name']]))
self.client.write_points(generate_item(response, self.measurement), 's', database=self.database)
if len(self.time_mess['creation']) % 45 == 0 and len(self.time_mess['creation']) > 0:
frame_key = list(self.time_mess.keys())
frame_lens = [len(self.time_mess[fkey]) for fkey in frame_key]
frame_len = min(frame_lens)
for fk in frame_key:
self.time_mess[fk] = self.time_mess[fk][-frame_len:]
data_frame = pd.DataFrame(self.time_mess)
data_frame.to_csv(self.save_path + '/' + 'struct2.csv', mode='a+', index=False, sep=',')
print(self.cpu_mess)
print(len(self.cpu_mess))
for keyss in self.cpu_mess:
print(keyss + ": " + str(len(self.cpu_mess[keyss])))
frame_key = list(self.cpu_mess.keys())
frame_lens = [len(self.cpu_mess[fkey]) for fkey in frame_key]
frame_len = min(frame_lens)
for fk in frame_key:
self.cpu_mess[fk] = self.cpu_mess[fk][-frame_len:]
data_frame2 = pd.DataFrame(self.cpu_mess)
data_frame2.to_csv(self.save_path + '/' + 'node6_cpu.csv', mode='a+', index=False, sep=',')
frame_key = list(self.memory_mess.keys())
frame_lens = [len(self.memory_mess[fkey]) for fkey in frame_key]
frame_len = min(frame_lens)
for fk in frame_key:
self.memory_mess[fk] = self.memory_mess[fk][-frame_len:]
data_frame3 = pd.DataFrame(self.memory_mess)
data_frame3.to_csv(self.save_path + '/' + 'node6_memory.csv', mode='a+', index=False, sep=',')
frame_key = list(self.cpu_per.keys())
frame_lens = [len(self.cpu_per[fkey]) for fkey in frame_key]
frame_len = min(frame_lens)
for fk in frame_key:
self.cpu_per[fk] = self.cpu_per[fk][-frame_len:]
data_frame4 = pd.DataFrame(self.cpu_per)
data_frame4.to_csv(self.save_path + '/' + 'node6_cpu_per.csv', mode='a+', index=False, sep=',')
frame_key = list(self.memory_per.keys())
frame_lens = [len(self.memory_per[fkey]) for fkey in frame_key]
frame_len = min(frame_lens)
for fk in frame_key:
self.memory_per[fk] = self.memory_per[fk][-frame_len:]
data_frame5 = pd.DataFrame(self.memory_per)
data_frame5.to_csv(self.save_path + '/' + 'node6_memory_per.csv', mode='a+', index=False, sep=',')
f1 = open('/tfdata/nodebase/node6.json', 'r', encoding='utf-8')
res = f1.read()
a = json.loads(res)
f1.close()
node_layout = {}
node_list = [i.metadata.name for i in self.v1.list_node().items]
for node in node_list:
node_layout[node] = []
for ns in tasks['ns']:
tmp_layout = tasks['nslayout']
if tmp_layout[ns]:
pod_list = [i for i in self.v1.list_namespaced_pod(ns).items]
for pod in pod_list:
try:
node_layout[pod.spec.node_name].append(pod.metadata.name)
except Exception as e0:
print(e0)
a.append(node_layout)
f2 = open('/tfdata/nodebase/node6.json', 'w', encoding='utf-8')
node_json = json.dumps(a, ensure_ascii=False, indent=4) # list转成json,字典转成字符串
f2.write(node_json)
f2.close()
for key in self.time_mess:
self.time_mess[key] = []
self.cpu_mess[key] = []
self.memory_mess[key] = []
self.memory_per[key] = []
self.cpu_per[key] = []
time.sleep(self.derivation)
except Exception as exeee:
print(exeee)
time.sleep(self.derivation)
def get_ns(v1):
ns_list = []
for i in v1.list_namespace().items:
ns_list.append(i.metadata.name)
return ns_list
# def get_layout():
# def get_remain():
def Monitor_job(tasks,lock,v1,jobs):
time.sleep(10)
while True:
if tasks['start'] == False:
break
ns_list = get_ns(v1)
# print(ns_list)
if tasks['start'] == True and tasks['count'] == 0:
time.sleep(30)
pass
else:
for ns in tasks['ns']:
# print(ns+'If in list:'+str(ns in ns_list))
if ns not in ns_list and ns not in tasks['retry'] and not tasks['modulate']:
try_times = 5
while try_times > 0:
time.sleep(float(random.randint(3, 5)))
ns_list = get_ns(v1)
if ns in ns_list:
break
try_times=try_times-1
if try_times <=0 :
lock.acquire()
ns_tmp = tasks['ns']
if ns in ns_tmp:
ns_tmp.remove(ns)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
is_layout_keys = list(is_layout.keys())
if ns in is_layout_keys:
is_layout.pop(ns)
tasks['nslayout'] = is_layout
count_tmp = len(ns_tmp)
tasks['count'] = count_tmp
lock.release()
def make_time_query(time_base,mode=0):
if mode == 0:
time_query = (math.floor(time_base-1))
time_query_str = str(time_query)+'000000000'
else:
time_query = (math.ceil(time_base+1))
time_query_str = str(time_query)+'000000000'
return time_query_str
def catch_node_step_msg(jobs,job_name,tasks,lock,batch,flops,params,mode,task2):
node_influx_client = influxdb.InfluxDBClient(host='192.168.128.10',username='admin',password='admin',database='NODEMESSAGE')
step_influx_client = influxdb.InfluxDBClient(host='192.168.128.10',username='admin',password='admin',database='PREDICT')
global XBOUND,XBOUND2
global YBOUND,YBOUND2
jieshu = False
lock.acquire()
for jo in jobs:
if jo == job_name:
job = reload_jobs(job_name,-1)
print('reload job success!')
break
lock.release()
print("kaishi: %s" % job_name)
job_measure = job.measure
print("job measure: %s" % job.measure)
pre_list = job_measure.split(' ')
measure_s = pre_list[0] + 'S' + pre_list[-1]
measure_load = pre_list[0] + 'L' + pre_list[-1]
measure_t = pre_list[0] + 'T' + pre_list[-1]
count = 0
count2 = 0
count23 = 0
count000 = 0
count0000 = 0
countt00 = 0
count111 = 0
job.set_mod(11)
save_mode_change(11,job.name,float(time.time()))
time.sleep(10.5)
tktkt = -1
# tktkm =
while True:
pod_status = [i.status.phase for i in job.v1.list_namespaced_pod(job.name).items]
run_result = pd.value_counts(pod_status)
run_result_dict = dict(run_result)
run_result_dict_c = run_result_dict.copy()
run_result_dict['job'] = job.name
print(run_result_dict)
print(run_result_dict_c)
if 'Running' in pod_status and run_result_dict['Running'] == (job.ps_replicas + job.worker_replicas):
if int(job.mod) != 5:
job.set_mod(5)
save_mode_change(5, job.name, float(time.time()))
count2 = 0
count000 = 0
countt00 = 0
count111 = 0
count = 0
time.sleep(4.4)
lock.acquire()
print("Select the loayout!")
tmp_layout = tasks['nslayout']
tmp_keys = list(tmp_layout.keys())
if job_name in tmp_keys and tmp_layout[job_name] == False:
tmp_layout_config = {}
for i in job.v1.list_namespaced_pod(job_name).items:
tmp_layout_config[i.metadata.name] = i.spec.node_name
fp = open('/tfdata/k8snfs/setbase/' + job_name + '/layout.json', 'w', encoding='utf-8')
# ensure_ascii:默认值True,如果dict内含有non-ASCII的字符,则会类似\uXXXX的显示数据,设置成False后,就能正常显示
dicc_json = json.dumps(tmp_layout_config, ensure_ascii=False, indent=4) # 字典转成json,字典转成字符串
fp.write(dicc_json)
fp.close()
tmp_layout[job_name] = True
tasks['nslayout'] = tmp_layout
lock.release()
break
# elif 'Running' in pod_status:
elif 'Succeeded' in pod_status or 'Failed' in pod_status:
countt00 = 0
count111 = 0
count = 0
if 'Pending' not in pod_status:
count2 = 0
if 'Succeeded' in pod_status:
tktkt = 1
if count000 <= 6:
count000+=1
time.sleep(4.32)
print("slepp waiting success or failed")
continue
else:
jieshu = True
print("Exception exit! Pending Problem!")
lock.acquire()
tmp_reload_ns = tasks['retry']
lock.release()
print("Retrying jobs is:")
print(tmp_reload_ns)
print(not tasks['modulate'])
print(job.name not in tmp_reload_ns and not tasks['modulate'])
try:
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job.name, job.name)
res_job_config = load_config(save_res_path)
res_job_config_keys = list(res_job_config.keys())
if 'endtime' not in res_job_config_keys:
res_job_config['endtime'] = time.time() - 30
save_config(res_job_config, save_res_path)
if int(job.mod) != 6 and int(job.mod)!=7:
if tktkt:
job.set_mod(6)
save_mode_change(6, job.name, float(res_job_config['endtime']))
else:
job.set_mod(7)
save_mode_change(7, job.name, float(res_job_config['endtime']))
print("save end time success!!")
except Exception as eee:
print("Delete Problem:")
print(eee)
time.sleep(3.2)
if job.name not in tmp_reload_ns and not tasks['modulate']:
time.sleep(3.8)
try:
exit_reason = [i.status.container_statuses[0].state.terminated.reason for i in
v1.list_namespaced_pod(job.name).items]
print(exit_reason)
exit_ict = {'reasons': exit_reason}
exit_path = '/tfdata/k8snfs/setbase/%s/exit_reason.json' % ns
exit_json = json.dumps(exit_ict, ensure_ascii=False, indent=4)
fw_exit = open(exit_path, 'w', encoding='utf-8')
fw_exit.write(exit_json)
fw_exit.close()
except Exception as e:
print(e)
time.sleep(3.2)
lock.acquire()
try:
try:
command = 'kubectl delete -f /tfdata/tfcnn/expjobbase/' + job.name + '.yaml'
os.system(command)
except Exception as ess2:
print(ess2)
deletehelp2(job.name, v1)
# v1.delete_namespace(job.name)
ns_tmp = tasks['ns']
ns_tmp.remove(job.name)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
is_layout.pop(job.name)
if job.name in jobs:
jobs.remove(job.name)
tasks['nslayout'] = is_layout
tasks['count'] -= 1
if 'Failed' in pod_status and 'Succeeded' not in pod_status:
fails = tasks['fail']
fails.append(job.name)
tasks['fail'] = fails
finishes = tasks['finish']
finishes.append(job.name)
tasks['finish'] = finishes
print("finish remove %s from jobs!" % job.name)
lock.release()
except Exception as ee33:
print(ee33)
ns_tmp = tasks['ns']
if job.name in ns_tmp:
ns_tmp.remove(job.name)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
if job.name in list(is_layout.keys()):
is_layout.pop(job.name)
tasks['nslayout'] = is_layout
# if job.name in jobs:
# jobs.remove(job.name)
if job.name in jobs:
jobs.remove(job.name)
ns_tmp = tasks['ns']
tasks['count'] = len(ns_tmp)
if 'Failed' in pod_status and 'Succeeded' not in pod_status:
fails = tasks['fail']
fails.append(job.name)
tasks['fail'] = fails
finishes = tasks['finish']
if job.name not in finishes:
finishes.append(job.name)
tasks['finish'] = finishes
print("finish remove %s from jobs!" % job.name)
lock.release()
return
else:
time.sleep(3.6)
elif 'Pending' in pod_status and 'Succeeded' not in pod_status and 'Failed' not in pod_status:
countt00 = 0
count111 = 0
count = 0
# count000
if 'Succeeded' not in pod_status and 'Failed' not in pod_status:
count000 = 0
# pod_status = [i.status.phase for i in job.v1.list_namespaced_pod(job_name).items]
tmp_layout = tasks['nslayout']
tmp_keys = list(tmp_layout.keys())
if job_name in tmp_keys:
tmp_layout_config = {}
for i in job.v1.list_namespaced_pod(job_name).items:
if i.status.phase == 'Running':
tmp_layout_config[i.metadata.name] = i.spec.node_name
if tmp_layout_config:
fp = open('/tfdata/k8snfs/setbase/' + job_name + '/layout.json', 'w', encoding='utf-8')
# ensure_ascii:默认值True,如果dict内含有non-ASCII的字符,则会类似\uXXXX的显示数据,设置成False后,就能正常显示
dicc_json = json.dumps(tmp_layout_config, ensure_ascii=False, indent=4) # 字典转成json,字典转成字符串
fp.write(dicc_json)
fp.close()
if int(job.mod)!=4:
job.set_mod(4)
save_mode_change(4, job.name, float(time.time()))
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job.name, job.name)
res_config = load_config(save_res_path)
keys_res = res_config.keys()
if 'reloadtime' not in keys_res:
res_config['reloadtime'] = []
# 'cpu_high': cpu_base, 'memory_base': mem_base
if count2 < 3:
count23 = count23 + 1
if count2 == 0:
time.sleep(1.3)
if count23 % 5 == 0:
print("apply resource!")
if job.cpu_allocate > res_config['cpu_high']:
if math.ceil(job.cpu_allocate * 0.892) >= res_config['cpu_high']:
kpk = random.randint(2, 7) / 100
# job.retry
# job.repeat
tmp_mem_using = math.ceil(job.memory_allocate * (1 + kpk))
if job.retry <= 1:
if tmp_mem_using > res_config['memory_base'] * 1.22:
tmp_mem_using = math.ceil(res_config['memory_base'] * 1.22)
save_job_change_resource(job.name, math.ceil(job.cpu_allocate * 0.892), tmp_mem_using)
job.assignment_resource(math.ceil(job.cpu_allocate * 0.892), tmp_mem_using)
else:
if tmp_mem_using > res_config['memory_base'] * YBOUND[-1]:
tmp_mem_using = math.ceil(res_config['memory_base'] * YBOUND[-1])
save_job_change_resource(job.name, math.ceil(job.cpu_allocate * 0.892), tmp_mem_using)
job.assignment_resource(math.ceil(job.cpu_allocate * 0.892), tmp_mem_using)
else:
if job.retry <= 1:
kpk = random.randint(2, 7) / 100
tmp_mem_using = math.ceil(job.memory_allocate * (1 + kpk))
if tmp_mem_using > res_config['memory_base'] * 1.22:
tmp_mem_using = math.ceil(res_config['memory_base'] * 1.22)
save_job_change_resource(job.name, res_config['cpu_high'], tmp_mem_using)
job.assignment_resource(res_config['cpu_high'], tmp_mem_using)
else:
kpk = random.randint(2, 7) / 100
tmp_mem_using = math.ceil(job.memory_allocate * (1 + kpk))
if tmp_mem_using > res_config['memory_base'] * YBOUND[-1]:
tmp_mem_using = math.ceil(res_config['memory_base'] * YBOUND[-1])
save_job_change_resource(job.name, res_config['cpu_high'], tmp_mem_using)
job.assignment_resource(res_config['cpu_high'], tmp_mem_using)
else:
kpk = random.randint(2, 7) / 100
tmp_mem_using = math.ceil(job.memory_allocate * (1 + kpk))
if job.retry <= 1:
if tmp_mem_using > res_config['memory_base'] * 1.22:
tmp_mem_using = math.ceil(res_config['memory_base'] * 1.22)
else:
if tmp_mem_using > res_config['memory_base'] * YBOUND[-1]:
tmp_mem_using = math.ceil(res_config['memory_base'] * YBOUND[-1])
tmp_cpu_using = math.ceil(job.cpu_allocate * 0.925)
if tmp_cpu_using <= math.ceil(0.475 * res_config['cpu_high']):
tmp_cpu_using = math.ceil(0.475 * res_config['cpu_high'])
save_job_change_resource(job.name, tmp_cpu_using, tmp_mem_using)
job.assignment_resource(tmp_cpu_using, tmp_mem_using)
print("modulate the cpu!!")
if job.memory_allocate > 1.15 * res_config['memory_base']:
# "cpu_high": 15780,
# "memory_base": 32113,
if math.ceil(job.memory_allocate * 0.92) >= 1.15 * res_config['memory_base']:
save_job_change_resource(job.name, job.cpu_allocate, math.ceil(job.memory_allocate * 0.92))
job.assignment_resource(job.cpu_allocate, math.ceil(job.memory_allocate * 0.92))
elif math.ceil(job.memory_allocate * 0.95) >= 1.15 * res_config['memory_base']:
save_job_change_resource(job.name, job.cpu_allocate, math.ceil(job.memory_allocate * 0.95))
job.assignment_resource(job.cpu_allocate, math.floor(job.memory_allocate * 0.95))
else:
save_job_change_resource(job.name, job.cpu_allocate, math.ceil(job.memory_allocate * 0.985))
job.assignment_resource(job.cpu_allocate, math.ceil(job.memory_allocate * 0.985))
print("modulate the memory!!")
else:
tmp_memo_allo = math.ceil(job.memory_allocate * 0.985)
if tmp_memo_allo < math.ceil(res_config['memory_base']) * 1.077:
tmp_memo_allo = math.ceil(res_config['memory_base'] * 1.077)
# else:
# tmp_memo_allo = math.ceil(job.memory_allocate * 0.98)
save_job_change_resource(job.name, job.cpu_allocate, tmp_memo_allo)
job.assignment_resource(job.cpu_allocate, tmp_memo_allo)
time.sleep(5.1)
count2 += 1
if count2 != 0:
time.sleep(3.58)
elif count2 == 3:
count23 = count23 + 1
if count23 % 5 == 0:
print("reschedule try!!")
aim_steps = step_influx_client.query(
"select training_step from " + measure_t + " order by desc limit 1")
aim_key = aim_steps.keys()
result_inter = aim_steps[aim_key[0]]
result_items = list(result_inter)
aim_step = int(result_items[0]['training_step'])
print(aim_step)
save_job_change_layout(job.name, job.ps_replicas, job.worker_replicas, aim_step, mode=1)
# aim_step = aim_step
time_1 = 0
# lock.acquire()
while True:
lock.acquire()
if not task2['label']:
tmp_retry_job = tasks['retry']
tmp_retry_job.append(job.name)
tasks['retry'] = tmp_retry_job
tmp_layout = tasks['nslayout']
tmp_layout[job.name] = False
tasks['nslayout'] = tmp_layout
time1 = time.time()
job.retry_tf(job.cpu_allocate, job.memory_allocate, aim_step, job.worker_replicas,
(job.ps_replicas),mode=1)
time2 = time.time()
tmp_retry_job = tasks['retry']
tmp_retry_job.remove(job.name)
tasks['retry'] = tmp_retry_job
tmp_reload = res_config['reloadtime']
tmp_reload.append((time2 - time1))
res_config['reloadtime'] = tmp_reload
save_config(res_config, save_res_path)
lock.release()
break
else:
lock.release()
time.sleep(2.8)
time.sleep(4.8)
job.write_retry(mode=0)
count2 += 1
print("reschedule again done!")
time.sleep(2.2)
# if count2 != 3:
time.sleep(3.58)
elif job.worker_replicas > 1:
count23 = count23+1
if count23 % 5 == 0:
if job.ps_replicas > 1:
tmp_ps_rep = job.ps_replicas
if job.ps_replicas > job.worker_replicas:
tmp_ps_rep = job.worker_replicas
tmp_replicas = job.worker_replicas
print("reduce worker number!!")
bili = math.floor(job.worker_replicas / tmp_ps_rep)
aim_tmp_replicas = int(job.worker_replicas - bili)
if tmp_ps_rep > 1:
if aim_tmp_replicas >= 4 * (tmp_ps_rep - 1):
aim_tmp_replicas = 4 * (tmp_ps_rep - 1)
if aim_tmp_replicas <= tmp_ps_rep - 1:
aim_tmp_replicas = tmp_ps_rep - 1
else:
if aim_tmp_replicas >= 4:
aim_tmp_replicas = 4
if aim_tmp_replicas <= 1:
aim_tmp_replicas = 1
if aim_tmp_replicas < 1:
aim_tmp_replicas = 1
# aim_step = step_influx_client.query("select training_step from " + measure_t + " order by desc limit 1")
aim_steps = step_influx_client.query(
"select training_step from " + measure_t + " order by desc limit 1")
aim_key = aim_steps.keys()
result_inter = aim_steps[aim_key[0]]
result_items = list(result_inter)
aim_step = int(result_items[0]['training_step'])
print(aim_step)
# aim_step = math.ceil((aim_step * tmp_replicas) / (job.worker_replicas - 1))
aim_step = math.ceil((aim_step * tmp_replicas) / (aim_tmp_replicas))
if tmp_ps_rep > 1:
save_job_change_layout(job.name, tmp_ps_rep - 1, (aim_tmp_replicas), aim_step, mode=1)
else:
save_job_change_layout(job.name, 1, (aim_tmp_replicas), aim_step, mode=1)
# lock.acquire()
while True:
lock.acquire()
if not task2['label']:
tmp_retry_job = tasks['retry']
tmp_retry_job.append(job.name)
tasks['retry'] = tmp_retry_job
tmp_layout = tasks['nslayout']
tmp_layout[job.name] = False
tasks['nslayout'] = tmp_layout
time1 = time.time()
job.retry_tf(job.cpu_allocate, job.memory_allocate, aim_step, (aim_tmp_replicas),
tmp_ps_rep - 1)
time2 = time.time()
tmp_retry_job = tasks['retry']
tmp_retry_job.remove(job.name)
tasks['retry'] = tmp_retry_job
tmp_reload = res_config['reloadtime']
tmp_reload.append((time2 - time1))
res_config['reloadtime'] = tmp_reload
save_config(res_config, save_res_path)
lock.release()
break
else:
lock.release()
time.sleep(2.8)
time.sleep(4.9)
job.write_retry(mode=0)
# count2 += 1
print("reduce worker number successfully!!")
else:
tmp_replicas = job.worker_replicas
print("reduce worker number!!")
aim_steps = step_influx_client.query(
"select training_step from " + measure_t + " order by desc limit 1")
aim_key = aim_steps.keys()
result_inter = aim_steps[aim_key[0]]
result_items = list(result_inter)
aim_step = int(result_items[0]['training_step'])
print(aim_step)
aim_step = math.ceil((aim_step * tmp_replicas) / (job.worker_replicas - 1))
aim_worker_replicas2 = job.worker_replicas - 1
if aim_worker_replicas2 < 1:
aim_worker_replicas2 = 1
save_job_change_layout(job.name, 1, aim_worker_replicas2, aim_step, mode=1)
# lock.acquire()
while True:
lock.acquire()
if not task2['label']:
tmp_retry_job = tasks['retry']
tmp_retry_job.append(job.name)
tasks['retry'] = tmp_retry_job
tmp_layout = tasks['nslayout']
tmp_layout[job.name] = False
tasks['nslayout'] = tmp_layout
time1 = time.time()
job.retry_tf(job.cpu_allocate, job.memory_allocate, aim_step, aim_worker_replicas2,1)
time2 = time.time()
tmp_retry_job = tasks['retry']
tmp_retry_job.remove(job.name)
tasks['retry'] = tmp_retry_job
tmp_reload = res_config['reloadtime']
tmp_reload.append((time2 - time1))
res_config['reloadtime'] = tmp_reload
save_config(res_config, save_res_path)
lock.release()
break
else:
lock.release()
time.sleep(2.8)
time.sleep(4.9)
job.write_retry(mode=0)
# count2 += 1
print("reduce worker number successfully!!")
time.sleep(3.38)
elif (job.worker_replicas == 1 and job.ps_replicas == 1):
count23 = count23+1
if count23 % 5 == 0:
if count2 < 6:
kpk = random.randint(1, 4) / 100
# save_job_change_resource(job.name, math.ceil(job.cpu_allocate*0.9), math.ceil(job.memory_allocate*(1+kpk)))
tmp_reuse_mem = math.ceil(job.memory_allocate * (1 + kpk))
if tmp_reuse_mem > 1.15 * res_config['memory_base']:
tmp_reuse_mem = math.floor(1.15 * res_config['memory_base'])
tmp_reuse_cpu = math.ceil(job.cpu_allocate * 0.95)
if tmp_reuse_cpu <= 0.475 * res_config['cpu_high']:
tmp_reuse_cpu = math.ceil(0.475 * res_config['cpu_high'])
save_job_change_resource(job.name, tmp_reuse_cpu, tmp_reuse_mem)
job.assignment_resource(tmp_reuse_cpu, tmp_reuse_mem)
count2+=1
time.sleep(3.0)
print("modulate CPU before goto Next count2: %d" % count2)
if count2 == 6:
print("reschedule try before next!!")
aim_steps = step_influx_client.query(
"select training_step from " + measure_t + " order by desc limit 1")
aim_key = aim_steps.keys()
result_inter = aim_steps[aim_key[0]]
result_items = list(result_inter)
aim_step = int(result_items[0]['training_step'])
print(aim_step)
save_job_change_layout(job.name, job.ps_replicas, job.worker_replicas, aim_step, mode=1)
# aim_step = aim_step
time_1 = 0
# lock.acquire()
while True:
lock.acquire()
if not task2['label']:
tmp_retry_job = tasks['retry']
tmp_retry_job.append(job.name)
tasks['retry'] = tmp_retry_job
tmp_layout = tasks['nslayout']
tmp_layout[job.name] = False
tasks['nslayout'] = tmp_layout
time1 = time.time()
job.retry_tf(job.cpu_allocate, job.memory_allocate, aim_step, job.worker_replicas,
(job.ps_replicas), mode=1)
time2 = time.time()
tmp_retry_job = tasks['retry']
tmp_retry_job.remove(job.name)
tasks['retry'] = tmp_retry_job
tmp_reload = res_config['reloadtime']
tmp_reload.append((time2 - time1))
res_config['reloadtime'] = tmp_reload
save_config(res_config, save_res_path)
lock.release()
break
else:
lock.release()
time.sleep(2.8)
time.sleep(4.8)
job.write_retry(mode=0)
count2 += 1
print("reschedule again done before next!")
time.sleep(2.2)
if count2 > 6:
try:
aim_steps = step_influx_client.query(
"select training_step from " + measure_t + " order by desc limit 1")
aim_key = aim_steps.keys()
result_inter = aim_steps[aim_key[0]]
result_items = list(result_inter)
aim_step = int(result_items[0]['training_step'])
print(aim_step)
save_job_change_layout(job.name, 1, 1, aim_step, mode=1)
except Exception as ee32:
print(ee32)
lock.acquire()
try:
command = 'kubectl delete -f /tfdata/tfcnn/expjobbase/' + job.name + '.yaml'
os.system(command)
deletehelp2(job.name, v1)
# v1.delete_namespace(job.name)
ns_tmp = tasks['ns']
ns_tmp.remove(job.name)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
is_layout.pop(job.name)
if job.name in jobs:
jobs.remove(job.name)
tasks['nslayout'] = is_layout
# job_tmp.pop(ns)
# tasks['job'] = job_tmp
tasks['count'] -= 1
tmp_next = tasks['next']
tmp_next.append(job.name)
tmp_next_time_config = tasks['nexttimes']
tmp_next_time_config[job.name] = 0
tasks['nexttimes'] = tmp_next_time_config
tasks['next'] = tmp_next
lock.release()
except Exception as ee33:
ns_tmp = tasks['ns']
if job.name in ns_tmp:
ns_tmp.remove(job.name)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
if job.name in list(is_layout.keys()):
is_layout.pop(job.name)
tasks['nslayout'] = is_layout
if job.name in jobs:
jobs.remove(job.name)
ns_tmp = tasks['ns']
# job_tmp.pop(ns)
# tasks['job'] = job_tmp
tasks['count'] = len(ns_tmp)
tmp_next = tasks['next']
if job.name not in tmp_next:
tmp_next.append(job.name)
tasks['next'] = tmp_next
tmp_next_time_config = tasks['nexttimes']
if job.name not in list(tmp_next_time_config.keys()):
tmp_next_time_config[job.name] = 0
tasks['nexttimes'] = tmp_next_time_config
lock.release()
print(ee33)
time.sleep(5.7)
jieshu = True
print("Exception exit! Pending Problem!")
count2 += 1
return
else:
count2 += 1
# time.sleep(17.9)
time.sleep(3.58)
else:
print("%s no condition, sleep!!" % job.name)
time.sleep(10.2)
count11 = 0
countt00 = 0
count22 = 0
count223 = 0
count000 = 0
count0000 = 0
count111 = 0
tktkt = -1
while True:
tmp_retrys = tasks['retry']
# tmp_reload_ns = tasks['retry']
tmp_retry_solution = tasks['solution']
# lock.release()
solution_keys = list(tmp_retry_solution.keys())
if job.name in tmp_retrys and job.name in solution_keys:
lock.acquire()
tmp_layout = tasks['nslayout']
tmp_layout[job.name] = False
tasks['nslayout'] = tmp_layout
lock.release()
solution = tmp_retry_solution[job.name]
pod_status = [i.status.phase for i in v1.list_namespaced_pod(job.name).items]
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job.name, job.name)
res_job_config = load_config(save_res_path)
res_job_config_keys = list(res_job_config.keys())
if (not pod_status) or 'Succeeded' in pod_status or 'Failed' in pod_status:
# if 'Succeeded' in pod_status:
# tktkt = 1
if count0000 <= 3:
time.sleep(3.2)
count0000+=1
continue
else:
lock.acquire()
tmp_retry_job = tasks['retry']
tmp_retry_job.remove(job.name)
tasks['retry'] = tmp_retry_job
tmp_retry_solution3 = tasks['solution']
tmp_retry_solution3.pop(job.name)
tasks['solution'] = tmp_retry_solution3
lock.release()
else:
count0000 = 0
if int(solution['type']) == 2:
save_job_change_resource(job.name, math.ceil(solution['cpu']), math.ceil(solution['mem']))
job.set_mod(9)
save_mode_change(9,job.name,float(time.time()))
lock.acquire()
# method2 = {'type':2,'cpu':aim1_cpu,'mem':aim1_mem}
job.assignment_resource(math.ceil(solution['cpu']), math.ceil(solution['mem']))
tmp_retry_job = tasks['retry']
tmp_retry_job.remove(job.name)
tasks['retry'] = tmp_retry_job
tmp_retry_solution3 = tasks['solution']
tmp_retry_solution3.pop(job.name)
tasks['solution'] = tmp_retry_solution3
lock.release()
if int(job.mod) != 5:
job.set_mod(5)
save_mode_change(5, job.name, float(time.time()))
elif int(solution['type']) == 1:
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job.name, job.name)
# job_res_config = {'deadline':job.deadline,'start_time':job.starttime,
# 'cpu_source':job.cpu_allocate,'mem_source':job.memory_allocate,
# 'cpu_high':cpu_base,'batch_res':batch_res,
# 'flops_res':flops_res,'params_res':params_res}
res_config = load_config(save_res_path)
keys_res = res_config.keys()
if 'reloadtime' not in keys_res:
res_config['reloadtime'] = []
tmp_replicas = job.worker_replicas
aim_steps = step_influx_client.query(
"select training_step from " + measure_t + " order by desc limit 1")
aim_key = aim_steps.keys()
result_inter = aim_steps[aim_key[0]]
result_items = list(result_inter)
aim_step = int(result_items[0]['training_step'])
print(aim_step)
aim_worker_replicas = job.worker_replicas + int(solution['worker'])
if aim_worker_replicas <= 0:
aim_worker_replicas = 1
aim_step = math.ceil((aim_step * tmp_replicas) / (aim_worker_replicas))
aim_ps_replicas = job.ps_replicas + int(solution['ps'])
if aim_ps_replicas <= 0:
aim_ps_replicas = 1
if aim_worker_replicas <= 0:
aim_worker_replicas = 1
save_job_change_layout(job.name, aim_ps_replicas, aim_worker_replicas, aim_step, mode=1)
job.set_mod(8)
save_mode_change(8,job.name,float(time.time()))
# lock.acquire()
while True:
lock.acquire()
if not task2['label']:
time1 = time.time()
job.retry_tf(job.cpu_allocate, job.memory_allocate, aim_step, aim_worker_replicas,
aim_ps_replicas)
time2 = time.time()
tmp_retry_job = tasks['retry']
tmp_retry_job.remove(job.name)
tasks['retry'] = tmp_retry_job
tmp_retry_solution3 = tasks['solution']
tmp_retry_solution3.pop(job.name)
tasks['solution'] = tmp_retry_solution3
time.sleep(2.7)
lock.release()
tmp_reload = res_config['reloadtime']
tmp_reload.append((time2 - time1))
res_config['reloadtime'] = tmp_reload
save_config(res_config, save_res_path)
break
else:
lock.release()
time.sleep(2.8)
# method1 = {'type': 1, 'ps': 0, 'worker': 1}
time.sleep(3.8)
count33 = 0
while count33 < 36:
pod_status3 = [i.status.phase for i in v1.list_namespaced_pod(job.name).items]
run_result3 = pd.value_counts(pod_status3)
run_result_dict3 = dict(run_result3)
run_result_dict_c3 = run_result_dict3.copy()
run_result_dict3['job'] = job.name
print("Retry assignmenting for pods:")
print(run_result_dict3)
if 'Running' in pod_status3 and run_result_dict3['Running'] == (
job.ps_replicas + job.worker_replicas):
if int(job.mod) != 5:
job.set_mod(5)
save_mode_change(5, job.name, float(time.time()))
break
else:
count33+=1
time.sleep(2.72)
job.write_retry(mode=0)
else:
count0000 = 0
pod_status2 = [i.status.phase for i in v1.list_namespaced_pod(job.name).items]
run_result2 = pd.value_counts(pod_status2)
run_result_dict2 = dict(run_result2)
run_result_dict_c2 = run_result_dict2.copy()
run_result_dict2['job'] = job.name
print(run_result_dict2)
if 'Running' in pod_status2 and run_result_dict2['Running'] == (job.ps_replicas + job.worker_replicas) and run_result_dict2['Running']>1:
if int(job.mod) != 5:
job.set_mod(5)
save_mode_change(5, job.name, float(time.time()))
count22 = 0
count000 = 0
countt00 = 0
count111 = 0
count11 = 0
time.sleep(5.6)
lock.acquire()
print("Select the loayout!")
tmp_layout = tasks['nslayout']
lock.release()
tmp_keys = list(tmp_layout.keys())
if job_name in tmp_keys and tmp_layout[job_name] == False:
tmp_layout_config = {}
for i in job.v1.list_namespaced_pod(job_name).items:
tmp_layout_config[i.metadata.name] = i.spec.node_name
fp = open('/tfdata/k8snfs/setbase/' + job_name + '/layout.json', 'w', encoding='utf-8')
# ensure_ascii:默认值True,如果dict内含有non-ASCII的字符,则会类似\uXXXX的显示数据,设置成False后,就能正常显示
dicc_json = json.dumps(tmp_layout_config, ensure_ascii=False, indent=4) # 字典转成json,字典转成字符串
fp.write(dicc_json)
fp.close()
tmp_layout[job_name] = True
lock.acquire()
tasks['nslayout'] = tmp_layout
lock.release()
else:
time.sleep(6.9)
elif ('Succeeded' in pod_status2 or 'Failed' in pod_status2):
countt00 = 0
count111 = 0
count11 = 0
if 'Pending' not in pod_status2:
count22 = 0
if 'Succeeded' in pod_status2:
tktkt = 1
if count000 <= 6:
time.sleep(3.8)
count000+=1
print("slepp waiting success or failed")
continue
else:
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job.name, job.name)
res_job_config = load_config(save_res_path)
res_job_config_keys = list(res_job_config.keys())
if 'endtime' not in res_job_config_keys:
res_job_config['endtime'] = time.time() - 10
save_config(res_job_config, save_res_path)
if int(job.mod) != 6 and int(job.mod)!=7:
if tktkt:
job.set_mod(6)
save_mode_change(6, job.name, float(res_job_config['endtime']))
else:
job.set_mod(7)
save_mode_change(7, job.name, float(res_job_config['endtime']))
time.sleep(3)
if (job.name not in tmp_retrys) and not tasks['modulate']:
try:
exit_reason = [i.status.container_statuses[0].state.terminated.reason for i in
v1.list_namespaced_pod(job.name).items]
print(exit_reason)
exit_ict = {'reasons': exit_reason}
exit_path = '/tfdata/k8snfs/setbase/%s/exit_reason.json' % ns
exit_json = json.dumps(exit_ict, ensure_ascii=False, indent=4)
fw_exit = open(exit_path, 'w', encoding='utf-8')
fw_exit.write(exit_json)
fw_exit.close()
except Exception as e:
print(e)
time.sleep(5)
lock.acquire()
try:
command = 'kubectl delete -f /tfdata/tfcnn/expjobbase/' + job.name + '.yaml'
os.system(command)
print("delete this job %s!!!" % job.name)
deletehelp2(job.name, v1)
# v1.delete_namespace(job.name)
ns_tmp = tasks['ns']
ns_tmp.remove(job.name)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
is_layout.pop(job.name)
# for i in range(len(jobs)):
# if jobs[i] == job.name:
# jobs.pop(i)
# break
if job.name in jobs:
jobs.remove(job.name)
tasks['nslayout'] = is_layout
tasks['count'] -= 1
# jobs_tmp = jobs
# jobs_tmp.remove(job.name)
# jobs = jobs_tmp
if 'Failed' in pod_status2 and 'Succeeded' not in pod_status2:
fails = tasks['fail']
fails.append(job.name)
tasks['fail'] = fails
finishes = tasks['finish']
finishes.append(job.name)
tasks['finish'] = finishes
lock.release()
except Exception as eess:
ns_tmp = tasks['ns']
if job.name in ns_tmp:
ns_tmp.remove(job.name)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
if is_layout in list(is_layout.keys()):
is_layout.pop(job.name)
tasks['nslayout'] = is_layout
if job.name in jobs:
jobs.remove(job.name)
ns_tmp = tasks['ns']
tasks['count'] = len(ns_tmp)
if 'Failed' in pod_status2 and 'Succeeded' not in pod_status2:
fails = tasks['fail']
fails.append(job.name)
tasks['fail'] = fails
finishes = tasks['finish']
if job.name not in finishes:
finishes.append(job.name)
tasks['finish'] = finishes
lock.release()
print(eess)
break
elif 'Pending' in pod_status2 and 'Succeeded' not in pod_status2 and 'Failed' not in pod_status2:
# pod_status = [i.status.phase for i in job.v1.list_namespaced_pod(job_name).items]
tmp_layout = tasks['nslayout']
tmp_keys = list(tmp_layout.keys())
countt00 = 0
count111 = 0
count11 = 0
if 'Succeeded' not in pod_status2 and 'Failed' not in pod_status2:
count000 = 0
if job_name in tmp_keys:
lock.acquire()
tmp_layout[job_name] = False
tasks['nslayout'] = tmp_layout
lock.release()
tmp_layout_config = {}
for i in job.v1.list_namespaced_pod(job_name).items:
if i.status.phase == 'Running':
tmp_layout_config[i.metadata.name] = i.spec.node_name
if tmp_layout_config:
fp = open('/tfdata/k8snfs/setbase/' + job_name + '/layout.json', 'w', encoding='utf-8')
# ensure_ascii:默认值True,如果dict内含有non-ASCII的字符,则会类似\uXXXX的显示数据,设置成False后,就能正常显示
dicc_json = json.dumps(tmp_layout_config, ensure_ascii=False, indent=4) # 字典转成json,字典转成字符串
fp.write(dicc_json)
fp.close()
if int(job.mod) != 4:
job.set_mod(4)
save_mode_change(4, job.name, float(time.time()))
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job.name, job.name)
res_config = load_config(save_res_path)
keys_res = res_config.keys()
if 'reloadtime' not in keys_res:
res_config['reloadtime'] = []
# 'cpu_high': cpu_base, 'memory_base': mem_base
if count22 < 4:
count223 = count223 + 1
if count22 == 0:
time.sleep(1.3)
if count223 % 5 == 0:
print("apply resource!")
if job.cpu_allocate > res_config['cpu_high']:
if math.ceil(job.cpu_allocate * 0.892) >= res_config['cpu_high']:
kpk = random.randint(1, 6) / 100
tmp_mem_using = math.ceil(job.memory_allocate * (1 + kpk))
# YBOUND[-1] * 1.92 * mem_base
if tmp_mem_using > res_config['memory_base'] * YBOUND[-1] * 1.8:
tmp_mem_using = math.ceil(res_config['memory_base'] * YBOUND[-1] * 1.8)
tmp_cpu_using = math.ceil(job.cpu_allocate * 0.892)
if tmp_cpu_using <= res_config['cpu_high'] * 0.475:
tmp_cpu_using = math.ceil(res_config['cpu_high'] * 0.475)
save_job_change_resource(job.name, tmp_cpu_using, tmp_mem_using)
job.assignment_resource(tmp_cpu_using, tmp_mem_using)
else:
save_job_change_resource(job.name, res_config['cpu_high'], job.memory_allocate)
job.assignment_resource(res_config['cpu_high'], job.memory_allocate)
else:
tmp_cpu_using = math.ceil(job.cpu_allocate * 0.925)
if tmp_cpu_using <= res_config['cpu_high'] * 0.475:
tmp_cpu_using = math.ceil(res_config['cpu_high'] * 0.475)
kpk = random.randint(1, 4) / 100
tmp_mem_using = math.ceil(job.memory_allocate * (1 + kpk))
if tmp_mem_using > res_config['memory_base'] * YBOUND[-1] * 1.525:
tmp_mem_using = math.ceil(res_config['memory_base'] * YBOUND[-1] * 1.525)
# save_job_change_resource(job.name, tmp_cpu_using, tmp_mem_using)
# job.assignment_resource(tmp_cpu_using, tmp_mem_using)
save_job_change_resource(job.name, tmp_cpu_using, tmp_mem_using)
job.assignment_resource(tmp_cpu_using, tmp_mem_using)
print("modulate the cpu!!")
if job.memory_allocate > 1.15 * res_config['memory_base']:
# "cpu_high": 15780,
# "memory_base": 32113,
if math.ceil(job.memory_allocate * 0.92) >= 1.15 * res_config['memory_base']:
save_job_change_resource(job.name, job.cpu_allocate,
math.ceil(job.memory_allocate * 0.92))
job.assignment_resource(job.cpu_allocate, math.ceil(job.memory_allocate * 0.92))
elif math.ceil(job.memory_allocate * 0.95) >= 1.15 * res_config['memory_base']:
save_job_change_resource(job.name, job.cpu_allocate,
math.ceil(job.memory_allocate * 0.95))
job.assignment_resource(job.cpu_allocate, math.ceil(job.memory_allocate * 0.95))
else:
save_job_change_resource(job.name, job.cpu_allocate,
math.ceil(job.memory_allocate * 0.982))
job.assignment_resource(job.cpu_allocate, math.ceil(job.memory_allocate * 0.982))
print("modulate the memory!!")
else:
# save_job_change_resource(job.name, job.cpu_allocate, math.ceil(job.memory_allocate * 0.92))
# job.assignment_resource(job.cpu_allocate, math.ceil(job.memory_allocate * 0.92))
tmp_memo_allo = math.ceil(job.memory_allocate * 0.985)
if tmp_memo_allo < math.ceil(res_config['memory_base']) * 1.077:
tmp_memo_allo = math.ceil(res_config['memory_base'] * 1.077)
save_job_change_resource(job.name, job.cpu_allocate, tmp_memo_allo)
job.assignment_resource(job.cpu_allocate, tmp_memo_allo)
count22 += 1
if count22 != 0:
time.sleep(4)
elif count22 == 4:
count223 = count223 + 1
if count223 % 5 == 0:
print("reschedule try!!")
# aim_step = step_influx_client.query("select training_step from " + measure_t + " order by desc limit 1")
aim_steps = step_influx_client.query(
"select training_step from " + measure_t + " order by desc limit 1")
aim_key = aim_steps.keys()
result_inter = aim_steps[aim_key[0]]
result_items = list(result_inter)
aim_step = int(result_items[0]['training_step'])
print(aim_step)
save_job_change_layout(job.name, job.ps_replicas, job.worker_replicas, aim_step, mode=1)
while True:
lock.acquire()
if not task2['label']:
tmp_retry_job = tasks['retry']
tmp_retry_job.append(job.name)
tasks['retry'] = tmp_retry_job
time1 = time.time()
job.retry_tf(job.cpu_allocate, job.memory_allocate, aim_step, job.worker_replicas,
(job.ps_replicas),mode=1)
time2 = time.time()
tmp_retry_job = tasks['retry']
tmp_retry_job.remove(job.name)
tasks['retry'] = tmp_retry_job
tmp_reload = res_config['reloadtime']
tmp_reload.append((time2 - time1))
res_config['reloadtime'] = tmp_reload
save_config(res_config, save_res_path)
lock.release()
break
else:
lock.release()
time.sleep(2.8)
time.sleep(4.7)
job.write_retry(mode=0)
count22 += 1
time.sleep(2.3)
print("reschedule again done!")
time.sleep(4)
elif job.worker_replicas > 1:
count223 = count223 + 1
if count223 % 5 == 0:
tmp_ps_rep = job.ps_replicas
if tmp_ps_rep > job.worker_replicas:
tmp_ps_rep = job.worker_replicas
tmp_replicas = job.worker_replicas
print("reduce worker number!!")
# aim_step = step_influx_client.query("select training_step from " + measure_t + " order by desc limit 1")
aim_steps = step_influx_client.query(
"select training_step from " + measure_t + " order by desc limit 1")
aim_key = aim_steps.keys()
result_inter = aim_steps[aim_key[0]]
result_items = list(result_inter)
aim_step = int(result_items[0]['training_step'])
print(aim_step)
aim_tmp_replicas = job.worker_replicas - 1
if aim_tmp_replicas < 1:
aim_tmp_replicas = 1
if (aim_tmp_replicas / tmp_ps_rep) <= 2:
tmp_ps_rep = math.floor(aim_tmp_replicas/2)
if tmp_ps_rep < 1:
tmp_ps_rep = 1
aim_step = math.ceil((aim_step * tmp_replicas) / aim_tmp_replicas)
save_job_change_layout(job.name, tmp_ps_rep, aim_tmp_replicas, aim_step, mode=1)
# lock.acquire()
while True:
lock.acquire()
if not task2['label']:
tmp_retry_job = tasks['retry']
tmp_retry_job.append(job.name)
tasks['retry'] = tmp_retry_job
time1 = time.time()
job.retry_tf(job.cpu_allocate, job.memory_allocate, aim_step, aim_tmp_replicas,
tmp_ps_rep)
time2 = time.time()
tmp_retry_job = tasks['retry']
tmp_retry_job.remove(job.name)
tasks['retry'] = tmp_retry_job
tmp_reload = res_config['reloadtime']
tmp_reload.append((time2 - time1))
res_config['reloadtime'] = tmp_reload
save_config(res_config, save_res_path)
lock.release()
break
else:
lock.release()
time.sleep(2.8)
time.sleep(5.2)
job.write_retry(mode=0)
# count22 += 1
print("reduce worker number successfully!!")
time.sleep(4)
# time.sleep(17.9)
elif (job.worker_replicas == 1 and job.ps_replicas == 1):
count223 = count223+1
if count223 % 5 == 0:
if count22 < 6:
kpk = random.randint(1, 4) / 100
tmp_reuse_mem = math.ceil(job.memory_allocate * (1 + kpk))
if tmp_reuse_mem > res_config['memory_base'] * YBOUND[-1]:
tmp_reuse_mem = math.floor(res_config['memory_base'] * YBOUND[-1])
tmp_reuse_cpu = math.ceil(job.cpu_allocate * 0.95)
if tmp_reuse_cpu <= 0.475 * res_config['cpu_high']:
tmp_reuse_cpu = 0.475 * res_config['cpu_high']
save_job_change_resource(job.name, tmp_reuse_cpu, tmp_reuse_mem)
job.assignment_resource(tmp_reuse_cpu, tmp_reuse_mem)
print("modulate CPU before goto Next next22: %d" % count22)
count22+=1
if count22 == 6:
print("reschedule try before go to next!!")
# aim_step = step_influx_client.query("select training_step from " + measure_t + " order by desc limit 1")
aim_steps = step_influx_client.query(
"select training_step from " + measure_t + " order by desc limit 1")
aim_key = aim_steps.keys()
result_inter = aim_steps[aim_key[0]]
result_items = list(result_inter)
aim_step = int(result_items[0]['training_step'])
print(aim_step)
save_job_change_layout(job.name, 1, 1, aim_step, mode=1)
# aim_step = aim_step
time_1 = 0
# lock.acquire()
while True:
lock.acquire()
if not task2['label']:
tmp_retry_job = tasks['retry']
tmp_retry_job.append(job.name)
tasks['retry'] = tmp_retry_job
time1 = time.time()
job.retry_tf(job.cpu_allocate, job.memory_allocate, aim_step, 1,
1, mode=1)
time2 = time.time()
tmp_retry_job = tasks['retry']
tmp_retry_job.remove(job.name)
tasks['retry'] = tmp_retry_job
tmp_reload = res_config['reloadtime']
tmp_reload.append((time2 - time1))
res_config['reloadtime'] = tmp_reload
save_config(res_config, save_res_path)
lock.release()
break
else:
lock.release()
time.sleep(2.8)
time.sleep(4.7)
job.write_retry(mode=0)
count22 += 1
time.sleep(2.3)
print("reschedule again done before go to next!")
if count22 >= 7:
aim_steps = step_influx_client.query(
"select training_step from " + measure_t + " order by desc limit 1")
aim_key = aim_steps.keys()
result_inter = aim_steps[aim_key[0]]
result_items = list(result_inter)
aim_step = int(result_items[0]['training_step'])
print(aim_step)
save_job_change_layout(job.name, 1, 1, aim_step, mode=1)
lock.acquire()
try:
command = 'kubectl delete -f /tfdata/tfcnn/expjobbase/' + job.name + '.yaml'
os.system(command)
deletehelp2(job.name, v1)
# v1.delete_namespace(job.name)
ns_tmp = tasks['ns']
ns_tmp.remove(job.name)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
is_layout.pop(job.name)
for i in range(len(jobs)):
if jobs[i] == job.name:
jobs.pop(i)
break
tasks['nslayout'] = is_layout
tasks['count'] -= 1
tmp_next = tasks['next']
tmp_next.append(job.name)
tmp_next_time_config = tasks['nexttimes']
tmp_next_time_config[job.name] = 0
tasks['nexttimes'] = tmp_next_time_config
tasks['next'] = tmp_next
lock.release()
except Exception as eess:
ns_tmp = tasks['ns']
if job.name in ns_tmp:
ns_tmp.remove(job.name)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
if job.name in list(is_layout.keys()):
is_layout.pop(job.name)
tasks['nslayout'] = is_layout
if job.name in jobs:
jobs.remove(job.name)
# for i in range(len(jobs)):
# if jobs[i] == job.name:
# jobs.pop(i)
# break
ns_tmp = tasks['ns']
tasks['count'] = len(ns_tmp)
tmp_next = tasks['next']
if job.name not in tmp_next:
tmp_next.append(job.name)
tasks['next'] = tmp_next
tmp_next_time_config = tasks['nexttimes']
if job.name not in list(tmp_next_time_config.keys()):
tmp_next_time_config[job.name] = 0
tasks['nexttimes'] = tmp_next_time_config
lock.release()
print(eess)
time.sleep(6.5)
jieshu = True
print("Exception exit! Pending Problem!")
count22 += 1
return
else:
count22 += 1
# time.sleep(17.5)
time.sleep(4)
else:
print("%s no condition, just sleep!!!" % job.name)
time.sleep(10.2)
def get_load_value(node_index,cpu_base,memory_base,total_cpu_base,total_memory_base):
keys = node_index.keys()
alpha = 0.675
cpu_score = 0
memory_score = 0
node_use = []
node_cpu = []
node_mem = []
for key in keys:
if node_index[key] <=11:
node_use.append(key)
for key in node_use:
cpu_score+= cpu_base[key]
node_cpu.append(cpu_base[key])
memory_score+= memory_base[key]
node_mem.append(memory_base[key])
cpu_score = cpu_score/len(node_use)
memory_score = memory_score/len(node_use)
cpu_score = alpha*cpu_score+(1-alpha)*total_cpu_base
memory_score = alpha*memory_score+(1-alpha)*total_memory_base
cpu_score = cpu_score / 0.834
memory_score = memory_score / 0.834
return cpu_score,memory_score,node_cpu,node_mem
def check_path(name):
train_dir = os.path.join('/tfdata/k8snfs/setbase/', name)
print(train_dir)
if not os.path.exists(train_dir):
os.makedirs(train_dir)
return train_dir
def write_step_meg(job_name):
job = reload_jobs(job_name,-1)
measure = job.measure
client_pre = influxdb.InfluxDBClient(host=job.dbhost, port=8086, username='admin', password='admin',
database="PREDICT")
pre_list = measure.split(" ")
# measure_s = pre_list[0] + 'S' + pre_list[-1]
measure_t = pre_list[0] + 'T' + pre_list[-1]
step_items = [
{
'measurement': measure_t,
'tags': {
'task': job.task_id,
'runtimes': job.rtimes,
'retry': job.retry
},
'fields': {
'training_step': job.training_step,
'worker': job.worker_replicas,
'ps': job.ps_replicas
}
}
]
client_pre.write_points(step_items, time_precision="ms", database="PREDICT")
print('write initial measure_t success!!')
job.write_retry(mode=0)
def loss_server_conn(ADDR,measure):
loss_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
loss_client.connect(ADDR)
loss_client.send(bytes(measure, 'utf-8'))
connect_try = 5
try_times = 1
connected = False
while True:
if try_times > connect_try:
break
msg_from_server = loss_client.recv(4096)
if not msg_from_server:
break
msg_from_server_str = str(msg_from_server.decode('utf-8'))
msg_from_server_list = msg_from_server_str.split(" ")
if msg_from_server_list[0] == '400':
connected = True
break
loss_client.send(bytes(measure, 'utf-8'))
try_times = try_times + 1
return connected
def tongji_adjust_number(aim_list):
try:
tongji_wenjian = load_config('modnum.json')
except Exception as ee0:
tongji_wenjian = {}
save_config(tongji_wenjian,'modnum.json')
tongji_wenjian = load_config('modnum.json')
aim_key_lists = list(tongji_wenjian.keys())
for i in aim_list:
if i in aim_key_lists:
tongji_wenjian[i]+=1
else:
tongji_wenjian[i]=1
save_config(tongji_wenjian,'modnum.json')
def tongji_waiting_queue(submit_job_name,time_submit_now):
try:
waiting_time = load_config('waiting_time.json')
except Exception as ee0:
waiting_time = {}
save_config(waiting_time,'waiting_time.json')
waiting_time = load_config('waiting_time.json')
waited = list(waiting_time.keys())
if submit_job_name not in waited:
waiting_time[submit_job_name] = time_submit_now
save_config(waiting_time,'waiting_time.json')
def save_mode_change(mod,job_name,happen_time):
save_mod_path = '/tfdata/k8snfs/setbase/%s/%s_mod.json' % (job_name, job_name)
try:
job_mod_config = load_config(save_mod_path)
except Exception as e1:
job_mod_config = {'mod': mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
job_mod_config['mod'] = mod
try:
job_mod_config[str(mod)].append(happen_time)
except Exception as e2:
job_mod_config[str(mod)] = []
job_mod_config[str(mod)].append(happen_time)
save_config(job_mod_config,save_mod_path)
def Submit_job(tasks,lock,v1,jobs,task2):
try:
rfr = joblib.load('rfr_batch.pkl')
except Exception as e0:
print(e0)
print('start to reload')
print(jobs)
global LOSSHOST,LOSSPORT,sleep_last_length
ADDR = (LOSSHOST,LOSSPORT)
PREHOST = '192.168.128.5'
PREPORT = 12529
ADDR2 = (PREHOST,PREPORT)
max_buffer_size = 38
job_basic = reload_jobs_aim(tasks['last'],-1)
max_free_heap = MaxHeap(max_size=max_buffer_size,fn=worker_queue.value_free_load)
max_wight_heap = MaxHeap(max_size=max_buffer_size,fn=worker_queue.value_weight_load)
worker_buffer = tasks['buffer']
first_reload = False
time.sleep(14)
if worker_buffer:
first_reload = True
pool = multiprocessing.Pool(processes=32)
for job0 in jobs:
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job0, job0)
res_config = load_config(save_res_path)
batch_res = res_config['batch_res']
flops_res = res_config['flops_res']
params_res = res_config['params_res']
job01 = reload_jobs(job0,-1)
# catch_node_step_msg(jobs=,job_name=,tasks=,lock=,batch=,flops=,params=,mode=)
loss_server_conn(ADDR,job01.measure)
pool.apply_async(catch_node_step_msg,args=(jobs,job0,tasks,lock,batch_res,flops_res,params_res,-1,task2))
try:
now_create = np.load('nowcreate.npy')
except Exception as ee00:
now_create = 0
# np.save('nowcreate.npy')
np.save('nowcreate.npy',now_create)
global_count = 45
need_s = load_config("modify.json")
need_buffer = need_s['pool']
try:
makebuf = np.load("makebuf.npy")
except Exception as eee011:
makebuf = 0
np.save("makebuf.npy",makebuf)
if makebuf < 1:
print('start to make a buffer pool!!')
for bfjob in need_buffer:
aim_job = reload_jobs_aim(bfjob, -1)
save_change_path = '/tfdata/k8snfs/%s/%s_pw.json' % (aim_job.name, aim_job.name)
aim_job_step_base = load_config(save_change_path)
his_step_key = list(aim_job_step_base["changen"].keys())
his_step = []
for hsk in his_step_key:
his_step.append(float(hsk))
# list.sort(his_step)
aim_job_step_base_pre = aim_job_step_base["changen"][str(min(his_step))]
tmp_step0 = aim_job_step_base_pre["stepbefore"]
ps_r = aim_job_step_base_pre["psbefore"]
worker_r = aim_job_step_base_pre["wbefore"]
if aim_job.template_id == 1:
# def __init__(self,v1,template_id,ps_replicas,worker_replicas,training_step,batch_size,interval,task_id,rtimes,tag,repeat,channel1,channel2,channel3,channel4,channel5,channel6,channel7,channel8,dbhost='192.168.128.10', retry=0, update_min_step=400, step_update=200, update_start=0.25,
# update_end=0.75, update_delay=2.0):
job = VGGTask(template_id=aim_job.template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tmp_step0,
batch_size=aim_job.batch_size,
interval=aim_job.interval,
task_id=aim_job.task_id,
rtimes=aim_job.rtimes,
tag=aim_job.tag, channel1=aim_job.channel1, channel2=aim_job.channel2,
channel3=aim_job.channel3, channel4=aim_job.channel4, channel5=aim_job.channel5,
num_layer1=aim_job.num_layer1, num_layer2=aim_job.num_layer2,
num_layer3=aim_job.num_layer3,
num_layer4=aim_job.num_layer4, num_layer5=aim_job.num_layer5
)
job_config = {'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas,
'training_step': job.training_step,
'batch_size': job.batch_size,
'interval': job.interval, 'task_id': job.task_id,
'rtimes': job.rtimes,
'tag': job.tag, 'channel1': job.channel1, 'channel2': job.channel2,
'channel3': job.channel3,
'channel4': job.channel4, 'channel5': job.channel5,
'num_layer1': job.num_layer1, 'num_layer2': job.num_layer2,
'num_layer3': job.num_layer3,
'num_layer4': job.num_layer4,
'num_layer5': job.num_layer5,
'retry': job.retry}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
dict12 = {'batch': aim_job.batch_size, 'channel1': aim_job.channel1, 'channel2': aim_job.channel2,
'channel3': aim_job.channel3,
'channel4': aim_job.channel4,
'channel5': aim_job.channel5, 'num_layer1': aim_job.num_layer1,
'num_layer2': aim_job.num_layer2,
'num_layer3': aim_job.num_layer3, 'num_layer4': aim_job.num_layer4,
'num_layer5': aim_job.num_layer5}
elif aim_job.template_id == 2:
job = RESTask(template_id=aim_job.template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tmp_step0,
batch_size=aim_job.batch_size,
interval=aim_job.interval,
task_id=aim_job.task_id,
rtimes=aim_job.rtimes,
tag=aim_job.tag, bottle=aim_job.bottle, layer1=aim_job.layer1,
layer2=aim_job.layer2,
layer3=aim_job.layer3,
layer4=aim_job.layer4, channel1=aim_job.channel1, channel2=aim_job.channel2,
channel3=aim_job.channel3,
channel4=aim_job.channel4)
job_config = {'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas,
'training_step': job.training_step,
'batch_size': job.batch_size,
'interval': job.interval,
'task_id': job.task_id, 'rtimes': job.rtimes,
'tag': job.tag, 'bottle': job.bottle, 'layer1': job.layer1,
'layer2': job.layer2,
'layer3': job.layer3,
'layer4': job.layer4, 'channel1': job.channel1, 'channel2': job.channel2,
'channel3': job.channel3, 'channel4': job.channel4, 'retry': job.retry}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
dict12 = {'batch': aim_job.batch_size, 'channel1': aim_job.channel1, 'channel2': aim_job.channel2,
'channel3': aim_job.channel3,
'channel4': aim_job.channel4,
'layer1': aim_job.layer1, 'layer2': aim_job.layer2,
'layer3': aim_job.layer3, 'layer4': aim_job.layer4, 'bottle': aim_job.bottle}
elif aim_job.template_id == 3:
job = RETask(template_id=aim_job.template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tmp_step0,
batch_size=aim_job.batch_size,
interval=aim_job.interval,
task_id=aim_job.task_id,
rtimes=aim_job.rtimes,
tag=aim_job.tag, stack=aim_job.stack, channel1=aim_job.channel1,
channel2=aim_job.channel2,
channel3=aim_job.channel3, channel4=aim_job.channel4
)
dict12 = {'batch': aim_job.batch_size, 'channel1': aim_job.channel1, 'channel2': aim_job.channel2,
'channel3': aim_job.channel3,
'channel4': aim_job.channel4, 'stack_num': aim_job.stack}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
job_config = {
'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas, 'training_step': job.training_step,
'batch_size': job.batch_size, 'interval': job.interval,
'task_id': job.task_id, 'rtimes': job.rtimes,
'tag': job.tag, 'stack': job.stack, 'channel1': job.channel1,
'channel2': job.channel2,
'channel3': job.channel3, 'channel4': job.channel4, 'retry': job.retry
}
elif aim_job.template_id == 4:
job = XCETask(template_id=aim_job.template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tmp_step0,
batch_size=aim_job.batch_size,
interval=aim_job.interval,
task_id=aim_job.task_id,
rtimes=aim_job.rtimes,
tag=aim_job.tag,
repeat=aim_job.repeat,
channel1=aim_job.channel1, channel2=aim_job.channel2, channel3=aim_job.channel3,
channel4=aim_job.channel4, channel5=aim_job.channel5, channel6=aim_job.channel6,
channel7=aim_job.channel7,
channel8=aim_job.channel8)
job_config = {
'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas,
'training_step': job.training_step,
'batch_size': job.batch_size,
'interval': job.interval,
'task_id': job.task_id,
'rtimes': job.rtimes, 'tag': job.tag, 'repeat': job.repeat,
'channel1': job.channel1,
'channel2': job.channel2, 'channel3': job.channel3, 'channel4': job.channel4,
'channel5': job.channel5,
'channel6': job.channel6, 'channel7': job.channel7, 'channel8': job.channel8,
'retry': job.retry
}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
dict12 = {'batch': aim_job.batch_size, 'channel1': aim_job.channel1, 'channel2': aim_job.channel2,
'channel3': aim_job.channel3,
'channel4': aim_job.channel4, 'channel5': aim_job.channel5, 'channel6': aim_job.channel6,
'channel7': aim_job.channel7,
'channel8': aim_job.channel8, 'repeat': aim_job.repeat}
else:
job = DENTask(template_id=aim_job.template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tmp_step0,
batch_size=aim_job.batch_size,
interval=aim_job.interval,
task_id=aim_job.task_id,
rtimes=aim_job.rtimes,
tag=aim_job.tag, L=aim_job.L, k=aim_job.k, BC=aim_job.BC)
job_config = {
'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas, 'training_step': job.training_step,
'batch_size': job.batch_size, 'interval': job.interval, 'task_id': job.task_id,
'rtimes': job.rtimes,
'tag': job.tag, 'L': job.L, 'k': job.k, 'BC': job.BC, 'retry': job.retry
}
# batch, flops, params = denfpmodel.denfp(batch=256, BC=0, k=24, L=100, num_classes=10)
dict12 = {'batch': aim_job.batch_size, 'BC': aim_job.BC, 'k': aim_job.k, 'L': aim_job.L,
'num_classes': 10}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
measure = job.measure
time.sleep(1.5)
pre_list = measure.split(" ")
measure_t = pre_list[0] + 'T' + pre_list[-1]
allow_p = check_path(measure_t)
save_config_dir = task_submit_fix.check_path(job.name)
save_job_path = '/tfdata/k8snfs/setbase/%s/%s.json' % (job.name, job.name)
allow_path = '/tfdata/k8snfs/setbase/%s/%s.json' % (job.name, measure_t)
pre_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
pre_client.connect(ADDR2)
pre_client.send(bytes(measure, 'utf-8'))
connect_try = 5
try_times = 1
connected = False
msg_from_server_str = ''
# while True:
# if try_times > connect_try:
# break
# msg_from_server = pre_client.recv(4096)
# if not msg_from_server:
# break
# msg_from_server_str = str(msg_from_server.decode('utf-8'))
# msg_from_server_list = msg_from_server_str.split(" ")
# if msg_from_server_list[0] == '400':
# connected = True
# break
# pre_client.send(bytes(measure, 'utf-8'))
# try_times = try_times + 1
# if not connected:
# print("Connected or send message error!")
# pre_client.close()
# lock.acquire()
# if kkppkk == 0:
# tmp1 = tasks['task_id']
# tmp1[job.template_id - 1] -= 1
# tasks['task_id'] = tmp1
# tmp2 = tasks['rtimes']
# tmp2[job.template_id - 1] -= 1
# tasks['rtimes'] = tmp2
# lock.release()
# try:
# command0 = 'rm %s' % save_job_path
# aek = os.system(command0)
# command0 = 'rm %s' % allow_path
# ask = os.system(command0)
# except Exception as eee0:
# print(eee0)
# # lock.release()
# continue
# print(msg_from_server_str)
# print("connected success!")
# dict_json = json.dumps(dict12)
# pre_client.send(bytes(dict_json, 'utf-8'))
# ress = pre_client.recv(4096)
# ress_str = str(ress.decode('utf-8'))
# ress_lists = ress_str.split(' ')
# if ress_lists[0] == '400':
resource_allocation_base = '/tfdata/tfcnn/queue/%s_res.json' % bfjob
resource_allocation = load_config(resource_allocation_base)
# "flops_res": 109867927,
# "params_res": 15861810,
batch_res = int(resource_allocation["batch_res"])
flops_res = int(resource_allocation["flops_res"])
params_res = int(resource_allocation["params_res"])
# cpu_predict = float(ress_lists[-2])
# "cpu_source": 6420,
# "mem_source": 14287,
# "cpu_high": 6420,
# "memory_base": 14287,
cpu_base = math.ceil(resource_allocation["cpu_high"])
mem_base = math.ceil(resource_allocation["memory_base"])
# if job.template_id != 4:
# mem_base = math.ceil(1.672 * mem_predict)
# else:
# mem_base = math.ceil(1.872 * mem_predict)
# res_to_server = '1'
# pre_client.send(bytes(res_to_server, 'utf-8'))
# else:
# res_to_server = '0'
# pre_client.send(bytes(res_to_server, 'utf-8'))
# print("send response success!!")
# time.sleep(5.3)
# pre_client.close()
# print("some time later to try again!!")
# if kkppkk == 0:
# tmp1 = tasks['task_id']
# tmp1[job.template_id - 1] -= 1
# tasks['task_id'] = tmp1
# tmp2 = tasks['rtimes']
# tmp2[job.template_id - 1] -= 1
# tasks['rtimes'] = tmp2
#
# try:
# command0 = 'rm %s' % save_job_path
# aek = os.system(command0)
# command0 = 'rm %s' % allow_path
# ask = os.system(command0)
# except Exception as eee0:
# print(eee0)
# time.sleep(27)
# continue
# pre_client.close()
tmp_reload = tasks['reload']
if tmp_reload == 0:
alpha = random.randint(0, 7) * 0.1 + 0.5
beta = random.randint(0, 18) * 0.1 + 0.875
else:
alpha = random.randint(2, 12) * 0.1 + 0.6
beta = random.randint(0, 10) * 0.1 + 1
alpha = 1
beta = 1
job.set_resource(cpu_source=(math.ceil(cpu_base * alpha)),
mem_source=(math.ceil(mem_base * beta)))
save_config(job_config, save_job_path)
allow_read = {}
allow_read['OK'] = True
allow_read['retry'] = 0
allow_p = check_path(measure_t)
save_config(allow_read, allow_path)
mini_batch = predict_min_first(rfr=rfr, cpu_alpha=alpha, mem_alpha=beta, batch=batch_res,
flops=flops_res, params=params_res)
mini_batch = float(mini_batch)
# if kkppkk == 0:
# deadline = mini_batch * job.training_step * (random.randint(66, 244) * 0.01) + 750
# else:
# deadline = float(aim_job.deadline)
deadline = float(resource_allocation["deadline"])
print(deadline)
print(type(deadline))
# deadline = random.randint(3600, 18000)
start_time = '%.3f' % time.time()
start_time = float(start_time)
job.set_deadline(deadline=deadline, start_time=start_time)
job.set_mod(new_mod=0)
job_mod_config['0'].append(start_time)
job.set_mod(0)
job_res_config = {'deadline': job.deadline, 'start_time': job.starttime,
'cpu_source': job.cpu_allocate,
'mem_source': job.memory_allocate, 'cpu_high': cpu_base,
'memory_base': mem_base, 'batch_res': batch_res,
'flops_res': flops_res, 'params_res': params_res, 'step_base': 0,
'reloadtime': []}
save_config_dir = task_submit_fix.check_path(job.name)
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job.name, job.name)
save_mod_path = '/tfdata/k8snfs/setbase/%s/%s_mod.json' % (job.name, job.name)
save_config(job_res_config, save_res_path)
save_config(job_mod_config, save_mod_path)
now_create = now_create + 1
np.save('nowcreate.npy', now_create)
time.sleep(1.5)
job.set_mod(2)
save_mode_change(2, job.name, float(time.time()))
lock.acquire()
worker_buffer = tasks['buffer']
worker_buffer.append(job.name)
tasks['buffer'] = worker_buffer
tmp_buffer_count = tasks['buffercount']
tmp_buffer_count = tmp_buffer_count + 1
tasks['buffercount'] = tmp_buffer_count
lock.release()
print("add %d job into waiting pool success!!" % tmp_buffer_count)
time.sleep(sleep_last_length-2)
makebuf = 1
np.save("makebuf.npy",makebuf)
while True:
print("Global Count is :%d" % global_count)
if tasks['start']==False:
break
# and global_count%45 > 1
tmp_aim_set = tasks['aim']
tmp_next_set = tasks['next']
ymp_ns_set = tasks['ns']
#and global_count % 45 > 1
#and global_count % 45 > 1
# and global_count % 45 > 1
# and global_count % 45 > 1
if global_count > 4 and global_count % 11 != 0 and global_count%9 != 0 and global_count % 45 > 1:
lock.acquire()
counts = tasks['count']
bufer_count = tasks['buffercount']
lock.release()
print(bufer_count)
if tasks['next'] and counts < tasks['size']:
print("panduan tasks in next")
lock.acquire()
tmp_next = tasks['next']
job_name = tmp_next.pop(0)
job_next_time = tasks['nexttimes']
job_next_time_job_name = job_next_time[job_name]
job_next_time_job_name = job_next_time_job_name + 1
job_next_time[job_name] = job_next_time_job_name
tasks['nexttimes'] = job_next_time
tasks['next'] = tmp_next
lock.release()
job = reload_jobs(job_name, -1)
job.set_mod(1)
save_mode_change(1,job.name,float(time.time()))
print("%s in next reload!" % job_name)
node_index, cpu_nodes, memory_nodes, total_cpu_use, total_mem_use = job_basic.schedule_base()
# mem_need = job.total_mem * total_mem_use + job.worker_replicas * job.memory_allocate + 2048 * job.ps_replicas
# cpu_need = job.total_cpu * total_cpu_use + job.worker_replicas * job.cpu_allocate + 1000 * job.ps_replicas
catch_worker = 0
catch_ps = 0
node_keys = cpu_nodes.keys()
for key in node_keys:
catch_ps_c = 0
catch_ps_m = 0
catch_worker_c = 0
catch_worker_m = 0
can_use_cpu = job.node_cpu[key] * (1 - cpu_nodes[key])
can_use_mem = job.node_memory[key] * (1 - memory_nodes[key])
first_try = True
endcpu = False
endmem = False
count_trys = 0
while (not endcpu) or (not endmem):
if first_try:
if can_use_cpu - 720 > 0:
catch_ps_c += 1
can_use_cpu = can_use_cpu - 720
else:
if can_use_cpu - job.cpu_allocate > 0:
catch_worker_c += 1
can_use_cpu = can_use_cpu - job.cpu_allocate
if can_use_mem - 2000 > 0:
catch_ps_m += 1
can_use_mem = can_use_mem - 2000
else:
if can_use_mem - job.memory_allocate > 0:
catch_worker_m += 1
can_use_mem = can_use_mem - job.memory_allocate
first_try = False
else:
if can_use_cpu - job.cpu_allocate > 0:
catch_worker_c += 1
can_use_cpu = can_use_cpu - job.cpu_allocate
else:
if can_use_cpu - 720 > 0:
catch_ps_c += 1
can_use_cpu = can_use_cpu - 720
else:
endcpu = True
if can_use_mem - job.memory_allocate > 0:
catch_worker_m += 1
can_use_mem = can_use_mem - job.memory_allocate
else:
if can_use_mem - 2000 > 0:
catch_ps_m += 1
can_use_mem = can_use_mem - 2000
else:
endmem = True
if catch_worker_c < catch_worker_m:
catch_worker += catch_worker_c
else:
catch_worker += catch_worker_m
if catch_ps_c < catch_ps_m:
catch_ps += catch_ps_c
else:
catch_ps += catch_ps_m
if catch_ps >= 1 and catch_worker >= 1:
break
print("In next catch ps: %d,worker:%d" % (catch_ps, catch_worker))
if catch_ps > 0 and catch_worker > 0:
# lock.acquire()
job.update_step()
print("in next update step success!!")
write_step_meg(job.name)
connected = False
try_times = 1
while True:
if try_times > 5:
break
print(job.measure)
print(ADDR)
connected = loss_server_conn(ADDR, job.measure)
print("connect result:")
print(connected)
if connected:
break
else:
try_times += 1
if not connected:
print("Conncet error!!Try again Later!!")
# lock.release()
continue
tmpk_next = tasks['next']
while True:
lock.acquire()
if job.mod != 10:
job.set_mod(10)
save_mode_change(10, job.name, float(time.time()))
if not task2['label']:
if len(tmpk_next) >= 1 and tasks['size'] - tasks['count']>=2 and (global_count+1)%9!=0 and (global_count+1)%11!=0:
job.create_tf(mode=1)
else:
job.create_tf(mode=1)
submit_time_now = time.time()
tongji_waiting_queue(job.name, submit_time_now)
ns_tmp = tasks['ns']
ns_tmp.append(job.name)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
is_layout[job.name] = False
tasks['nslayout'] = is_layout
jobs.append(job.name)
tasks['count'] += 1
tmp_next_time_config = tasks['nexttimes']
tmp_next_time_config.pop(job_name)
tasks['nexttimes'] = tmp_next_time_config
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job.name, job.name)
res_config = load_config(save_res_path)
lock.release()
batch_res = res_config['batch_res']
flops_res = res_config['flops_res']
params_res = res_config['params_res']
pool.apply_async(catch_node_step_msg,
args=(jobs, job.name, tasks, lock, batch_res, flops_res, params_res, 1,task2))
# tasks['next'] = ''
break
else:
lock.release()
time.sleep(2.9)
else:
lock.acquire()
tmp_buffer_count0 = tasks['buffercount']
catch_tmp_nexttimes = tasks['nexttimes']
catch_tmp_ps_re_job_name = catch_tmp_nexttimes[job_name]
# tasks['nexttimes'][job.name]
if catch_tmp_ps_re_job_name >=3 and tmp_buffer_count0 < max_buffer_size:
tmp_buffer_pool = tasks['buffer']
tmp_buffer_pool.append(job.name)
job.set_mod(2)
save_mode_change(2,job.name,float(time.time()))
tasks['buffer'] = tmp_buffer_pool
tmp_buffer_count0+=1
tasks['buffercount'] = tmp_buffer_count0
tmp_next_time_config = tasks['nexttimes']
tmp_next_time_config.pop(job.name)
tasks['nexttimes'] = tmp_next_time_config
else:
tmp_next = tasks['next']
tmp_next.append(job.name)
tasks['next'] = tmp_next
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job.name, job.name)
# save_res_path = '/tfdata/tfcnn'
res_config = load_config(save_res_path)
if job.cpu_allocate > math.ceil(0.515*res_config['cpu_high']):
if math.ceil(job.cpu_allocate * 0.85) >= math.ceil(0.515*res_config['cpu_high']):
save_job_change_resource(job.name, math.ceil(job.cpu_allocate * 0.85),
job.memory_allocate)
else:
save_job_change_resource(job.name, math.ceil(0.515*res_config['cpu_high']), job.memory_allocate)
# job.assignment_resource(res_config['cpu_high'], job.memory_allocate)
print("modulate the cpu!!")
else:
if job.memory_allocate > res_config['memory_base']:
save_job_change_resource(job.name, job.cpu_allocate, 1.093*res_config['memory_base'])
# job.assignment_resource(job.cpu_allocate, res_config['memory_base'])
print("modulate the memory!!")
lock.release()
time.sleep(18.5)
elif counts < tasks['size'] and bufer_count>0:
lock.acquire()
tmp_buffer_count = tasks['buffercount']
worker_buffer = tasks['buffer']
lock.release()
node_index, cpu_nodes, memory_nodes, total_cpu_use, total_mem_use = job_basic.schedule_base()
cpu_value, mem_value, cpu_node_value, mem_node_value = get_load_value(node_index=node_index,
cpu_base=cpu_nodes,
memory_base=memory_nodes,
total_cpu_base=total_cpu_use,
total_memory_base=total_mem_use)
if cpu_value < 0.4:
selected = False
selected_job_name = ''
for job_name in worker_buffer:
rea = max_free_heap.add(job_name)
if rea is not None:
selected_job_name = rea
selected = True
break
if not selected:
selected_job_name = max_free_heap.items[0]
print(selected_job_name)
worker_buffer = max_free_heap.items
print(worker_buffer)
if not selected:
ceshi_name = worker_buffer.pop(0)
# tmp_buffer = tasks['buffer']
# tmp_buffer.remove(selected_job_name)
print(ceshi_name)
tasks['buffer'] = worker_buffer[:]
# tmp_buffer_size =
max_free_heap.clear()
if selected:
tasks['buffercount'] = max_buffer_size
else:
tmp_buffer_count = tmp_buffer_count - 1
tasks['buffercount'] = tmp_buffer_count
else:
selected = False
selected_job_name = ''
for job_name in worker_buffer:
# max_wight_heap
rea = max_wight_heap.add(job_name)
if rea is not None:
selected_job_name = rea
selected = True
break
if not selected:
selected_job_name = max_wight_heap.items[0]
worker_buffer = max_wight_heap.items
print(worker_buffer)
print(selected_job_name)
if not selected:
ceshi_name = worker_buffer.pop(0)
# tmp_buffer = tasks['buffer']
# tmp_buffer.remove(selected_job_name)
print(ceshi_name)
tasks['buffer'] = worker_buffer[:]
# tmp_buffer_size =
max_wight_heap.clear()
if selected:
tasks['buffercount'] = max_buffer_size
else:
tmp_buffer_count = tmp_buffer_count - 1
tasks['buffercount'] = tmp_buffer_count
job = reload_jobs(selected_job_name, -1)
job.set_mod(1)
save_mode_change(1,job.name,float(time.time()))
tmp_ps_replicas = job.ps_replicas
tmp_worker_replicas = job.worker_replicas
selected_res_config_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (selected_job_name, selected_job_name)
selected_res_config2 = load_config(selected_res_config_path)
using_flops = selected_res_config2['flops_res']
using_param = selected_res_config2["params_res"]
using_cpu_base = selected_res_config2['cpu_high']
using_mem_base = selected_res_config2['memory_base']
using_min_batch = predict_min_first(rfr=rfr,cpu_alpha=job.cpu_allocate/using_cpu_base,mem_alpha=job.memory_allocate/using_mem_base,batch=job.batch_size,flops=using_flops,params=using_param)
using_min_batch = float(using_min_batch)
tmp_rest = job.deadline + job.starttime - time.time()
if tmp_rest > 0:
_,_,atmp = job.get_remain(mode=0)
worker_need = math.ceil(
(job.training_step - atmp) * job.worker_replicas * using_min_batch / ((tmp_rest)))
worker_need_total = worker_need
if job.training_step - atmp <= 2:
job.worker_replicas = 1
else:
job.worker_replicas = worker_need_total
if cpu_value < 0.4:
if worker_need >= 6:
job.worker_replicas = 6
elif cpu_value < 0.7:
if worker_need >= 4:
job.worker_replicas = 4
else:
if worker_need >= 2:
job.worker_replicas = 2
# job.get_remain()
else:
if cpu_value < 0.4:
job.worker_replicas = random.randint(3, 5)
elif cpu_value < 0.7:
job.worker_replicas = random.randint(2, 3)
else:
job.worker_replicas = random.randint(1, 2)
# job.worker_replicas = 2
catch_tmp_ps_re = random.randint(math.floor(job.worker_replicas / 4),math.ceil(job.worker_replicas / 2))
# catch_tmp_ps_re = 1
if catch_tmp_ps_re < 1:
catch_tmp_ps_re = 1
job.ps_replicas = catch_tmp_ps_re
job.training_step = math.ceil(job.training_step * tmp_worker_replicas / job.worker_replicas)
save_job_change_layout(job.name, job.ps_replicas, job.worker_replicas, job.training_step)
mem_need = job.total_mem * total_mem_use + job.worker_replicas * job.memory_allocate + 2048 * job.ps_replicas
cpu_need = job.total_cpu * total_cpu_use + job.worker_replicas * job.cpu_allocate + 750 * job.ps_replicas
catch_worker = 0
catch_ps = 0
node_keys = cpu_nodes.keys()
reach_ps = False
reach_worker = False
for key in node_keys:
catch_ps_c = 0
catch_ps_m = 0
catch_worker_c = 0
catch_worker_m = 0
can_use_cpu = job.node_cpu[key] * (1 - cpu_nodes[key])
can_use_mem = job.node_memory[key] * (1 - memory_nodes[key])
first_try = True
endcpu = False
endmem = False
while (not endcpu) or (not endmem):
if first_try:
if can_use_cpu - 720 > 0 and not reach_ps:
catch_ps_c += 1
can_use_cpu = can_use_cpu - 720
else:
if can_use_cpu - job.cpu_allocate > 0 and not reach_worker:
catch_worker_c += 1
can_use_cpu = can_use_cpu - job.cpu_allocate
if can_use_mem - 2000 > 0 and not reach_ps:
catch_ps_m += 1
can_use_mem = can_use_mem - 2000
else:
if can_use_mem - job.memory_allocate > 0 and not reach_worker:
catch_worker_m += 1
can_use_mem = can_use_mem - job.memory_allocate
first_try = False
else:
if can_use_cpu - job.cpu_allocate > 0 and not reach_worker:
catch_worker_c += 1
can_use_cpu = can_use_cpu - job.cpu_allocate
else:
if can_use_cpu - 720 > 0 and not reach_ps:
catch_ps_c += 1
can_use_cpu = can_use_cpu - 720
else:
endcpu = True
if can_use_mem - job.memory_allocate > 0 and not reach_worker:
catch_worker_m += 1
can_use_mem = can_use_mem - job.memory_allocate
else:
if can_use_mem - 2000 > 0 and not reach_ps:
catch_ps_m += 1
can_use_mem = can_use_mem - 2000
else:
endmem = True
if catch_worker_c < catch_worker_m:
catch_worker += catch_worker_c
else:
catch_worker += catch_worker_m
if catch_ps_c < catch_ps_m:
catch_ps += catch_ps_c
else:
catch_ps += catch_ps_m
if catch_ps >= job.ps_replicas:
reach_ps = True
if catch_worker >= job.worker_replicas:
reach_worker = True
if catch_ps >= job.ps_replicas and catch_worker >= job.worker_replicas:
break
print("catch_ps: %d catch_worker: %d" % (catch_ps, catch_worker))
if catch_ps < job.ps_replicas or catch_worker < job.worker_replicas:
tmp_ps = job.ps_replicas
tmp_worker = job.worker_replicas
if catch_ps > 0 and catch_worker > 0:
if catch_worker > job.worker_replicas:
catch_worker = job.worker_replicas
if catch_ps > job.ps_replicas:
catch_ps = job.ps_replicas
job.ps_replicas = catch_ps
job.worker_replicas = catch_worker
job.training_step = math.ceil(job.training_step * tmp_worker / job.worker_replicas)
# lock.acquire()
save_job_change_layout(job.name, catch_ps, catch_worker, job.training_step)
job.update_step()
write_step_meg(job.name)
# lock.release()
connected = False
try_times = 1
while True:
if try_times > 5:
break
connected = loss_server_conn(ADDR, job.measure)
if connected:
break
else:
try_times += 1
if not connected:
print("Conncet error!!Try again Later!!")
# lock.release()
continue
while True:
lock.acquire()
if job.mod != 10:
job.set_mod(10)
save_mode_change(10, job.name, float(time.time()))
if not task2['label']:
if tasks['buffercount'] >= 2 and tasks['size']-tasks['count']>=2 and (global_count+1)%9!=0 and (global_count+1)%11!=0:
job.create_tf(mode=1)
else:
job.create_tf()
submit_time_now = time.time()
tongji_waiting_queue(job.name, submit_time_now)
ns_tmp = tasks['ns']
ns_tmp.append(job.name)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
is_layout[job.name] = False
tasks['nslayout'] = is_layout
jobs.append(job.name)
tasks['count'] += 1
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job.name, job.name)
res_config = load_config(save_res_path)
lock.release()
batch_res = res_config['batch_res']
flops_res = res_config['flops_res']
params_res = res_config['params_res']
pool.apply_async(catch_node_step_msg,
args=(
jobs, job.name, tasks, lock, batch_res, flops_res, params_res, 1,task2))
break
else:
lock.release()
time.sleep(2.9)
else:
job.ps_replicas = 1
job.worker_replicas = 1
job.training_step = job.training_step = math.ceil(job.training_step * tmp_worker)
save_job_change_layout(job.name, 1, 1, training_step=job.training_step)
job.set_mod(3)
save_mode_change(3,job.name,float(time.time()))
# tasks['next'] = job.name
lock.acquire()
tmp_next = tasks['next']
tmp_next.append(job.name)
tmp_next_time_config = tasks['nexttimes']
tmp_next_time_config[job.name] = 0
tasks['nexttimes'] = tmp_next_time_config
tasks['next'] = tmp_next
lock.release()
else:
# lock.acquire()
job.update_step()
write_step_meg(job.name)
connected = False
try_times = 1
while True:
if try_times > 5:
break
connected = loss_server_conn(ADDR, job.measure)
if connected:
break
else:
try_times += 1
if not connected:
print("Conncet error!!Try again Later!!")
# lock.release()
continue
while True:
lock.acquire()
if job.mod != 10:
job.set_mod(10)
save_mode_change(10, job.name, float(time.time()))
if not task2['label']:
if tasks['buffercount'] >= 2 and tasks['size'] - tasks['count']>=2 and (global_count+1)%9!=0 and (global_count+1)%11!=0:
job.create_tf(mode=1)
else:
job.create_tf()
submit_time_now = time.time()
tongji_waiting_queue(job.name, submit_time_now)
# lock.acquire()
ns_tmp = tasks['ns']
ns_tmp.append(job.name)
tasks['ns'] = ns_tmp
# job_tmp = tasks['job']
# job_tmp[job.name] = job
# tasks['job'] = job_tmp
is_layout = tasks['nslayout']
is_layout[job.name] = False
tasks['nslayout'] = is_layout
jobs.append(job.name)
tasks['count'] += 1
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job.name, job.name)
res_config = load_config(save_res_path)
lock.release()
batch_res = res_config['batch_res']
flops_res = res_config['flops_res']
params_res = res_config['params_res']
pool.apply_async(catch_node_step_msg,
args=(
jobs, job.name, tasks, lock, batch_res, flops_res, params_res, 1,task2))
break
else:
lock.release()
time.sleep(2.9)
global_count+=1
time.sleep(sleep_last_length)
# or global_count%45==1
# or global_count % 45 == 1
# or global_count % 45 == 1
# or global_count % 45 == 1
if global_count % 9 == 0 or global_count<=4 or global_count % 45 == 1:
print('start to submit a job!!')
for _ in range(10):
lock.acquire()
counts = tasks['count']
bufer_count = tasks['buffercount']
lock.release()
if ((counts >= tasks['size']) and (bufer_count >= max_buffer_size)) or (now_create>=27 and (not tmp_aim_set)):
time.sleep(float(random.randint(2,3)))
pass
else:
print('select a job!!')
time.sleep(29)
kkppkk = 0
if tasks['aim']:
kkppkk = 1
tmp_jobs = tasks['aim']
aim_job0 = tmp_jobs[0]
tmp_jobs.pop(0)
tasks['aim'] = tmp_jobs
aim_job = reload_jobs_aim(aim_job0, -1)
save_change_path = '/tfdata/k8snfs/%s/%s_pw.json' % (aim_job.name, aim_job.name)
aim_job_step_base = load_config(save_change_path)
his_step_key = list(aim_job_step_base["changen"].keys())
his_step = []
for hsk in his_step_key:
his_step.append(float(hsk))
# list.sort(his_step)
aim_job_step_base_pre = aim_job_step_base["changen"][str(min(his_step))]
# tmp_step0 = aim_job_step_base_pre["stepbefore"]*aim_job_step_base_pre["wbefore"]
# tmp_step0 = math.ceil(tmp_step0/2)
# ps_r = 1
# worker_r = 2
tmp_step0 = aim_job_step_base_pre["stepbefore"]
# tmp_step0 = aim_job_step_base_pre["stepbefore"]*aim_job_step_base_pre["wbefore"]
# tmp_step0 = math.ceil(tmp_step0/2)
# "psbefore"
ps_r = aim_job_step_base_pre["psbefore"]
worker_r = aim_job_step_base_pre["wbefore"]
if aim_job.template_id == 1:
# def __init__(self,v1,template_id,ps_replicas,worker_replicas,training_step,batch_size,interval,task_id,rtimes,tag,repeat,channel1,channel2,channel3,channel4,channel5,channel6,channel7,channel8,dbhost='192.168.128.10', retry=0, update_min_step=400, step_update=200, update_start=0.25,
# update_end=0.75, update_delay=2.0):
job = VGGTask(template_id=aim_job.template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tmp_step0,
batch_size=aim_job.batch_size,
interval=aim_job.interval,
task_id=aim_job.task_id,
rtimes=aim_job.rtimes,
tag=aim_job.tag, channel1=aim_job.channel1, channel2=aim_job.channel2,
channel3=aim_job.channel3,channel4=aim_job.channel4, channel5=aim_job.channel5,
num_layer1=aim_job.num_layer1, num_layer2=aim_job.num_layer2, num_layer3=aim_job.num_layer3,
num_layer4=aim_job.num_layer4,num_layer5=aim_job.num_layer5
)
job_config = {'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas,
'training_step': job.training_step,
'batch_size': job.batch_size,
'interval': job.interval, 'task_id': job.task_id,
'rtimes': job.rtimes,
'tag': job.tag, 'channel1': job.channel1, 'channel2': job.channel2,
'channel3': job.channel3,
'channel4': job.channel4, 'channel5': job.channel5,
'num_layer1': job.num_layer1, 'num_layer2': job.num_layer2,
'num_layer3': job.num_layer3,
'num_layer4': job.num_layer4,
'num_layer5': job.num_layer5,
'retry': job.retry}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
dict12 = {'batch': aim_job.batch_size, 'channel1': aim_job.channel1, 'channel2': aim_job.channel2,
'channel3': aim_job.channel3,
'channel4': aim_job.channel4,
'channel5': aim_job.channel5, 'num_layer1': aim_job.num_layer1, 'num_layer2': aim_job.num_layer2,
'num_layer3': aim_job.num_layer3, 'num_layer4': aim_job.num_layer4, 'num_layer5': aim_job.num_layer5}
elif aim_job.template_id == 2:
job = RESTask(template_id=aim_job.template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tmp_step0,
batch_size=aim_job.batch_size,
interval=aim_job.interval,
task_id=aim_job.task_id,
rtimes=aim_job.rtimes,
tag=aim_job.tag, bottle=aim_job.bottle, layer1=aim_job.layer1,
layer2=aim_job.layer2,
layer3=aim_job.layer3,
layer4=aim_job.layer4, channel1=aim_job.channel1, channel2=aim_job.channel2, channel3=aim_job.channel3,
channel4=aim_job.channel4)
job_config = {'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas,
'training_step': job.training_step,
'batch_size': job.batch_size,
'interval': job.interval,
'task_id': job.task_id, 'rtimes': job.rtimes,
'tag': job.tag, 'bottle': job.bottle, 'layer1': job.layer1,
'layer2': job.layer2,
'layer3': job.layer3,
'layer4': job.layer4, 'channel1': job.channel1, 'channel2': job.channel2,
'channel3': job.channel3, 'channel4': job.channel4, 'retry': job.retry}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
dict12 = {'batch': aim_job.batch_size, 'channel1': aim_job.channel1, 'channel2': aim_job.channel2,
'channel3': aim_job.channel3,
'channel4': aim_job.channel4,
'layer1': aim_job.layer1, 'layer2': aim_job.layer2,
'layer3': aim_job.layer3, 'layer4': aim_job.layer4, 'bottle': aim_job.bottle}
elif aim_job.template_id == 3:
job = RETask(template_id=aim_job.template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tmp_step0,
batch_size=aim_job.batch_size,
interval=aim_job.interval,
task_id=aim_job.task_id,
rtimes=aim_job.rtimes,
tag=aim_job.tag, stack=aim_job.stack, channel1=aim_job.channel1,
channel2=aim_job.channel2,
channel3=aim_job.channel3, channel4=aim_job.channel4
)
dict12 = {'batch': aim_job.batch_size, 'channel1': aim_job.channel1, 'channel2': aim_job.channel2,
'channel3': aim_job.channel3,
'channel4': aim_job.channel4, 'stack_num': aim_job.stack}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
job_config = {
'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas, 'training_step': job.training_step,
'batch_size': job.batch_size, 'interval': job.interval,
'task_id': job.task_id, 'rtimes': job.rtimes,
'tag': job.tag, 'stack': job.stack, 'channel1': job.channel1,
'channel2': job.channel2,
'channel3': job.channel3, 'channel4': job.channel4, 'retry': job.retry
}
elif aim_job.template_id == 4:
job = XCETask(template_id=aim_job.template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tmp_step0,
batch_size=aim_job.batch_size,
interval=aim_job.interval,
task_id=aim_job.task_id,
rtimes=aim_job.rtimes,
tag=aim_job.tag,
repeat=aim_job.repeat,
channel1=aim_job.channel1, channel2=aim_job.channel2, channel3=aim_job.channel3,
channel4=aim_job.channel4, channel5=aim_job.channel5, channel6=aim_job.channel6,
channel7=aim_job.channel7,
channel8=aim_job.channel8)
job_config = {
'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas,
'training_step': job.training_step,
'batch_size': job.batch_size,
'interval': job.interval,
'task_id': job.task_id,
'rtimes': job.rtimes, 'tag': job.tag, 'repeat': job.repeat,
'channel1': job.channel1,
'channel2': job.channel2, 'channel3': job.channel3, 'channel4': job.channel4,
'channel5': job.channel5,
'channel6': job.channel6, 'channel7': job.channel7, 'channel8': job.channel8,
'retry': job.retry
}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
dict12 = {'batch': aim_job.batch_size, 'channel1': aim_job.channel1, 'channel2': aim_job.channel2,
'channel3': aim_job.channel3,
'channel4': aim_job.channel4, 'channel5': aim_job.channel5, 'channel6': aim_job.channel6,
'channel7': aim_job.channel7,
'channel8': aim_job.channel8, 'repeat': aim_job.repeat}
else:
job = DENTask(template_id=aim_job.template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tmp_step0,
batch_size=aim_job.batch_size,
interval=aim_job.interval,
task_id=aim_job.task_id,
rtimes=aim_job.rtimes,
tag=aim_job.tag, L=aim_job.L, k=aim_job.k, BC=aim_job.BC)
job_config = {
'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas, 'training_step': job.training_step,
'batch_size': job.batch_size, 'interval': job.interval, 'task_id': job.task_id,
'rtimes': job.rtimes,
'tag': job.tag, 'L': job.L, 'k': job.k, 'BC': job.BC, 'retry': job.retry
}
# batch, flops, params = denfpmodel.denfp(batch=256, BC=0, k=24, L=100, num_classes=10)
dict12 = {'batch': aim_job.batch_size, 'BC': aim_job.BC, 'k': aim_job.k, 'L': aim_job.L, 'num_classes': 10}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
measure = job.measure
time.sleep(2.5)
# aim_job.retry = 0
else:
template_id = random.randint(1, 4)
if tasks['reload'] == 0:
template_id = random.randint(1, 4)
if template_id <= 2:
template_id = 1
else:
template_id = 4
tmp_worker_replicas = 4
# if template_id == 3:
# template_id = random.randint(1,2)
print(template_id)
lock.acquire()
tmp1 = tasks['task_id']
tmp1[template_id - 1] += 1
tasks['task_id'] = tmp1
tmp2 = tasks['rtimes']
tmp2[template_id - 1] += 1
tasks['rtimes'] = tmp2
lock.release()
ps_r = random.randint(1, 3)
worker_r = random.randint(1, 5)
batch = random.randint(64, 1024)
measure = "VGG 1"
print(tasks)
if template_id == 1:
channels = [24, 32, 40, 48, 64, 72, 80, 96, 120, 128, 160, 192, 240, 256, 320, 384, 400,
480, 512, 576]
x1 = random.randint(0, 4)
x2 = random.randint(4, 7)
x3 = random.randint(7, 11)
x4 = random.randint(11, 15)
x5 = random.randint(15, 19)
channel1 = channels[x1]
channel2 = channels[x2]
channel3 = channels[x3]
channel4 = channels[x4]
channel5 = channels[x5]
num_layer1 = random.randint(2, 4)
num_layer2 = random.randint(2, 4)
num_layer3 = random.randint(3, 6)
num_layer4 = random.randint(3, 8)
num_layer5 = random.randint(3, 8)
# def __init__(self,v1,template_id,ps_replicas,worker_replicas,training_step,batch_size,interval,task_id,rtimes,tag,repeat,channel1,channel2,channel3,channel4,channel5,channel6,channel7,channel8,dbhost='192.168.128.10', retry=0, update_min_step=400, step_update=200, update_start=0.25,
# update_end=0.75, update_delay=2.0):
job = VGGTask(template_id=template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tasks['training_step'][template_id - 1],
batch_size=batch,
interval=tasks['interval'][template_id - 1],
task_id=tasks['task_id'][template_id - 1],
rtimes=tasks['rtimes'][template_id - 1],
tag=tasks['tag'][template_id - 1], channel1=channel1, channel2=channel2,
channel3=channel3,
channel4=channel4, channel5=channel5,
num_layer1=num_layer1, num_layer2=num_layer2, num_layer3=num_layer3,
num_layer4=num_layer4,
num_layer5=num_layer5
)
job_config = {'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas,
'training_step': job.training_step,
'batch_size': job.batch_size,
'interval': job.interval, 'task_id': job.task_id,
'rtimes': job.rtimes,
'tag': job.tag, 'channel1': job.channel1, 'channel2': job.channel2,
'channel3': job.channel3,
'channel4': job.channel4, 'channel5': job.channel5,
'num_layer1': job.num_layer1, 'num_layer2': job.num_layer2,
'num_layer3': job.num_layer3,
'num_layer4': job.num_layer4,
'num_layer5': job.num_layer5,
'retry': job.retry}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
dict12 = {'batch': batch, 'channel1': channel1, 'channel2': channel2,
'channel3': channel3,
'channel4': channel4,
'channel5': channel5, 'num_layer1': num_layer1, 'num_layer2': num_layer2,
'num_layer3': num_layer3, 'num_layer4': num_layer4, 'num_layer5': num_layer5}
elif template_id == 2:
bottle = random.randint(0, 1)
channels = [24, 32, 40, 48, 64, 72, 80, 96, 120, 128, 160, 192, 240, 256, 320, 384, 400,
480, 512, 576]
x1 = random.randint(0, 3)
x2 = random.randint(1, 7)
x3 = random.randint(8, 14)
x4 = random.randint(14, 19)
channel1 = channels[x1]
channel2 = channels[x2]
channel3 = channels[x3]
channel4 = channels[x4]
layer1 = random.randint(2, 6)
layer2 = random.randint(2, 8)
layer3 = random.randint(2, 40)
layer4 = random.randint(2, 6)
job = RESTask(template_id=template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tasks['training_step'][template_id - 1],
batch_size=batch,
interval=tasks['interval'][template_id - 1],
task_id=tasks['task_id'][template_id - 1],
rtimes=tasks['rtimes'][template_id - 1],
tag=tasks['tag'][template_id - 1], bottle=bottle, layer1=layer1,
layer2=layer2,
layer3=layer3,
layer4=layer4, channel1=channel1, channel2=channel2, channel3=channel3,
channel4=channel4)
job_config = {'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas,
'training_step': job.training_step,
'batch_size': job.batch_size,
'interval': job.interval,
'task_id': job.task_id, 'rtimes': job.rtimes,
'tag': job.tag, 'bottle': job.bottle, 'layer1': job.layer1,
'layer2': job.layer2,
'layer3': job.layer3,
'layer4': job.layer4, 'channel1': job.channel1, 'channel2': job.channel2,
'channel3': job.channel3, 'channel4': job.channel4, 'retry': job.retry}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
dict12 = {'batch': batch, 'channel1': channel1, 'channel2': channel2,
'channel3': channel3,
'channel4': channel4,
'layer1': layer1, 'layer2': layer2,
'layer3': layer3, 'layer4': layer4, 'bottle': bottle}
elif template_id == 3:
stack = random.randint(3, 16)
channels = [12, 16, 24, 32, 40, 48, 64, 72, 80, 96, 120, 128, 160, 192, 240, 256, 320,
384,
400,
480,
512, 576]
x1 = random.randint(0, 3)
x2 = random.randint(2, 5)
x3 = random.randint(6, 11)
x4 = random.randint(6, 11)
channel1 = channels[x1]
channel2 = channels[x2]
channel3 = channels[x3]
channel4 = channels[x4]
job = RETask(template_id=template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tasks['training_step'][template_id - 1],
batch_size=batch,
interval=tasks['interval'][template_id - 1],
task_id=tasks['task_id'][template_id - 1],
rtimes=tasks['rtimes'][template_id - 1],
tag=tasks['tag'][template_id - 1], stack=stack, channel1=channel1,
channel2=channel2,
channel3=channel3, channel4=channel4
)
dict12 = {'batch': batch, 'channel1': channel1, 'channel2': channel2,
'channel3': channel3,
'channel4': channel4, 'stack_num': stack}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
job_config = {
'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas, 'training_step': job.training_step,
'batch_size': job.batch_size, 'interval': job.interval,
'task_id': job.task_id, 'rtimes': job.rtimes,
'tag': job.tag, 'stack': job.stack, 'channel1': job.channel1,
'channel2': job.channel2,
'channel3': job.channel3, 'channel4': job.channel4, 'retry': job.retry
}
elif template_id == 4:
repeat = random.randint(4, 12)
channels = [12, 16, 24, 32, 40, 48, 64, 72, 80, 96, 120, 128, 160, 192, 240, 256, 320,
384,
400,
480,
512, 576, 640, 728, 856, 920, 960, 1024, 1280, 1408, 1536, 1600, 1728, 2048,
2096]
x1 = random.randint(0, 5)
x2 = random.randint(3, 9)
x3 = random.randint(9, 12)
x4 = random.randint(12, 18)
x5 = random.randint(19, 24)
x6 = random.randint(26, 28)
x7 = random.randint(29, 31)
x8 = random.randint(32, 34)
channel1 = channels[x1]
channel2 = channels[x2]
channel3 = channels[x3]
channel4 = channels[x4]
channel5 = channels[x5]
channel6 = channels[x6]
channel7 = channels[x7]
channel8 = channels[x8]
job = XCETask(template_id=template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tasks['training_step'][template_id - 1],
batch_size=batch,
interval=tasks['interval'][template_id - 1],
task_id=tasks['task_id'][template_id - 1],
rtimes=tasks['rtimes'][template_id - 1],
tag=tasks['tag'][template_id - 1],
repeat=repeat,
channel1=channel1, channel2=channel2, channel3=channel3,
channel4=channel4, channel5=channel5, channel6=channel6,
channel7=channel7,
channel8=channel8)
job_config = {
'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas,
'training_step': job.training_step,
'batch_size': job.batch_size,
'interval': job.interval,
'task_id': job.task_id,
'rtimes': job.rtimes, 'tag': job.tag, 'repeat': job.repeat,
'channel1': job.channel1,
'channel2': job.channel2, 'channel3': job.channel3, 'channel4': job.channel4,
'channel5': job.channel5,
'channel6': job.channel6, 'channel7': job.channel7, 'channel8': job.channel8,
'retry': job.retry
}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
dict12 = {'batch': batch, 'channel1': channel1, 'channel2': channel2,
'channel3': channel3,
'channel4': channel4, 'channel5': channel5, 'channel6': channel6,
'channel7': channel7,
'channel8': channel8, 'repeat': repeat}
else:
Ls = [16, 32, 40, 48, 50, 60, 64, 80, 100, 120, 128, 160, 180, 200, 240, 250, 256]
ks = [8, 10, 12, 16, 24, 32, 40, 48]
x1 = random.randint(0, 16)
x2 = random.randint(0, 7)
L = Ls[x1]
k = ks[x2]
BC = random.randint(0, 1)
job = DENTask(template_id=template_id, ps_replicas=ps_r,
worker_replicas=worker_r,
training_step=tasks['training_step'][template_id - 1],
batch_size=batch,
interval=tasks['interval'][template_id - 1],
task_id=tasks['task_id'][template_id - 1],
rtimes=tasks['rtimes'][template_id - 1],
tag=tasks['tag'][template_id - 1], L=L, k=k, BC=BC)
job_config = {
'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas, 'training_step': job.training_step,
'batch_size': job.batch_size, 'interval': job.interval, 'task_id': job.task_id,
'rtimes': job.rtimes,
'tag': job.tag, 'L': job.L, 'k': job.k, 'BC': job.BC, 'retry': job.retry
}
# batch, flops, params = denfpmodel.denfp(batch=256, BC=0, k=24, L=100, num_classes=10)
dict12 = {'batch': batch, 'BC': BC, 'k': k, 'L': L, 'num_classes': 10}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
measure = job.measure
# lock.acquire()
#
# tasks['base'] = job.name
# lock.release()
else:
job_base_name = tasks['base']
job_base_name_list = job_base_name.split('-')
if job_base_name_list[0] == 'vgg':
template_id = 1
elif job_base_name_list[0] == 'res':
template_id = 2
elif job_base_name_list[0] == 're':
template_id = 3
elif job_base_name_list[0] == 'xception':
template_id = 4
else:
template_id = 5
lock.acquire()
tmp1 = tasks['task_id']
tmp1[template_id - 1] += 1
tasks['task_id'] = tmp1
tmp2 = tasks['rtimes']
tmp2[template_id - 1] += 1
tasks['rtimes'] = tmp2
lock.release()
tmp_task_id = tmp1[template_id - 1]
job = reload_jobs_aim(job_base_name, task_id=tmp_task_id)
job.retry = 0
if template_id == 1:
job_config = {'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas,
'training_step': job.training_step,
'batch_size': job.batch_size,
'interval': job.interval, 'task_id': job.task_id,
'rtimes': job.rtimes,
'tag': job.tag, 'channel1': job.channel1, 'channel2': job.channel2,
'channel3': job.channel3,
'channel4': job.channel4, 'channel5': job.channel5,
'num_layer1': job.num_layer1, 'num_layer2': job.num_layer2,
'num_layer3': job.num_layer3,
'num_layer4': job.num_layer4,
'num_layer5': job.num_layer5, 'retry': job.retry}
dict12 = {'batch': job.batch_size, 'channel1': job.channel1, 'channel2': job.channel2,
'channel3': job.channel3,
'channel4': job.channel4,
'channel5': job.channel5, 'num_layer1': job.num_layer1,
'num_layer2': job.num_layer2,
'num_layer3': job.num_layer3, 'num_layer4': job.num_layer4,
'num_layer5': job.num_layer5}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
elif template_id == 2:
job_config = {'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas,
'training_step': job.training_step,
'batch_size': job.batch_size,
'interval': job.interval,
'task_id': job.task_id, 'rtimes': job.rtimes,
'tag': job.tag, 'bottle': job.bottle, 'layer1': job.layer1,
'layer2': job.layer2,
'layer3': job.layer3,
'layer4': job.layer4, 'channel1': job.channel1, 'channel2': job.channel2,
'channel3': job.channel3, 'channel4': job.channel4, 'retry': job.retry}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
dict12 = {'batch': job.batch_size, 'channel1': job.channel1, 'channel2': job.channel2,
'channel3': job.channel3,
'channel4': job.channel4,
'layer1': job.layer1, 'layer2': job.layer2,
'layer3': job.layer3, 'layer4': job.layer4, 'bottle': job.bottle}
elif template_id == 3:
dict12 = {'batch': job.batch_size, 'channel1': job.channel1, 'channel2': job.channel2,
'channel3': job.channel3,
'channel4': job.channel4, 'stack_num': job.stack}
job_config = {
'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas, 'training_step': job.training_step,
'batch_size': job.batch_size, 'interval': job.interval,
'task_id': job.task_id, 'rtimes': job.rtimes,
'tag': job.tag, 'stack': job.stack, 'channel1': job.channel1,
'channel2': job.channel2,
'channel3': job.channel3, 'channel4': job.channel4, 'retry': job.retry
}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
elif template_id == 4:
job_config = {
'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas,
'training_step': job.training_step,
'batch_size': job.batch_size,
'interval': job.interval,
'task_id': job.task_id,
'rtimes': job.rtimes, 'tag': job.tag, 'repeat': job.repeat,
'channel1': job.channel1,
'channel2': job.channel2, 'channel3': job.channel3, 'channel4': job.channel4,
'channel5': job.channel5,
'channel6': job.channel6, 'channel7': job.channel7, 'channel8': job.channel8,
'retry': job.retry
}
dict12 = {'batch': job.batch_size, 'channel1': job.channel1, 'channel2': job.channel2,
'channel3': job.channel3,
'channel4': job.channel4, 'channel5': job.channel5, 'channel6': job.channel6,
'channel7': job.channel7,
'channel8': job.channel8, 'repeat': job.repeat}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
else:
job_config = {
'template_id': job.template_id, 'ps_replicas': job.ps_replicas,
'worker_replicas': job.worker_replicas, 'training_step': job.training_step,
'batch_size': job.batch_size, 'interval': job.interval, 'task_id': job.task_id,
'rtimes': job.rtimes,
'tag': job.tag, 'L': job.L, 'k': job.k, 'BC': job.BC, 'retry': job.retry
}
dict12 = {'batch': job.batch_size, 'BC': job.BC, 'k': job.k, 'L': job.L,
'num_classes': 10}
job_mod_config = {'mod': job.mod, '-1': [float(time.time())], '0': [], '1': [], '2': [],
'3': [], '4': [], '5': [],
'6': [], '7': [], '8': [], '9': [], '10': [], '11': []}
measure = job.measure
# lock.acquire()
if tasks['count'] < tasks['size'] or tasks['buffercount'] < max_buffer_size:
pre_list = measure.split(" ")
measure_t = pre_list[0] + 'T' + pre_list[-1]
allow_p = check_path(measure_t)
save_config_dir = task_submit_fix.check_path(job.name)
save_job_path = '/tfdata/k8snfs/setbase/%s/%s.json' % (job.name, job.name)
allow_path = '/tfdata/k8snfs/setbase/%s/%s.json' % (job.name, measure_t)
pre_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
pre_client.connect(ADDR2)
pre_client.send(bytes(measure, 'utf-8'))
connect_try = 5
try_times = 1
connected = False
msg_from_server_str = ''
while True:
if try_times > connect_try:
break
msg_from_server = pre_client.recv(4096)
if not msg_from_server:
break
msg_from_server_str = str(msg_from_server.decode('utf-8'))
msg_from_server_list = msg_from_server_str.split(" ")
if msg_from_server_list[0] == '400':
connected = True
break
pre_client.send(bytes(measure, 'utf-8'))
try_times = try_times + 1
if not connected:
print("Connected or send message error!")
pre_client.close()
# lock.acquire()
if kkppkk == 0:
tmp1 = tasks['task_id']
tmp1[job.template_id - 1] -= 1
tasks['task_id'] = tmp1
tmp2 = tasks['rtimes']
tmp2[job.template_id - 1] -= 1
tasks['rtimes'] = tmp2
# lock.release()
try:
command0 = 'rm %s' % save_job_path
aek = os.system(command0)
command0 = 'rm %s' % allow_path
ask = os.system(command0)
except Exception as eee0:
print(eee0)
# lock.release()
continue
print(msg_from_server_str)
print("connected success!")
dict_json = json.dumps(dict12)
pre_client.send(bytes(dict_json, 'utf-8'))
ress = pre_client.recv(4096)
ress_str = str(ress.decode('utf-8'))
ress_lists = ress_str.split(' ')
if ress_lists[0] == '400':
batch_res = int(ress_lists[1])
flops_res = int(ress_lists[2])
params_res = int(ress_lists[3])
cpu_predict = float(ress_lists[-2])
cpu_base = math.ceil(1.03 * cpu_predict)
mem_predict = float(ress_lists[-1])
if job.template_id != 4:
mem_base = math.ceil(1.672 * mem_predict)
else:
mem_base = math.ceil(1.872 * mem_predict)
res_to_server = '1'
pre_client.send(bytes(res_to_server, 'utf-8'))
else:
res_to_server = '0'
pre_client.send(bytes(res_to_server, 'utf-8'))
print("send response success!!")
time.sleep(5.3)
pre_client.close()
print("some time later to try again!!")
if kkppkk == 0:
tmp1 = tasks['task_id']
tmp1[job.template_id - 1] -= 1
tasks['task_id'] = tmp1
tmp2 = tasks['rtimes']
tmp2[job.template_id - 1] -= 1
tasks['rtimes'] = tmp2
try:
command0 = 'rm %s' % save_job_path
aek = os.system(command0)
command0 = 'rm %s' % allow_path
ask = os.system(command0)
except Exception as eee0:
print(eee0)
time.sleep(27)
continue
pre_client.close()
tmp_reload = tasks['reload']
if tmp_reload == 0:
alpha = random.randint(0, 7) * 0.1 + 0.5
beta = random.randint(0, 18) * 0.1 + 0.875
else:
alpha = random.randint(2, 12) * 0.1 + 0.6
beta = random.randint(0, 10) * 0.1 + 1
alpha = 1
beta = 1
job.set_resource(cpu_source=(math.ceil(cpu_base * alpha)),
mem_source=(math.ceil(mem_base * beta)))
save_config(job_config, save_job_path)
allow_read = {}
allow_read['OK'] = True
allow_read['retry'] = 0
allow_p = check_path(measure_t)
save_config(allow_read, allow_path)
mini_batch = predict_min_first(rfr=rfr, cpu_alpha=alpha, mem_alpha=beta, batch=batch_res,
flops=flops_res, params=params_res)
mini_batch = float(mini_batch)
if kkppkk == 0:
deadline = mini_batch * job.training_step * (random.randint(66, 244) * 0.01) + 750
else:
deadline = float(aim_job.deadline)
print(deadline)
print(type(deadline))
# deadline = random.randint(3600, 18000)
start_time = '%.3f' % time.time()
start_time = float(start_time)
job.set_deadline(deadline=deadline, start_time=start_time)
job.set_mod(new_mod=0)
job_mod_config['0'].append(start_time)
job.set_mod(0)
job_res_config = {'deadline': job.deadline, 'start_time': job.starttime,
'cpu_source': job.cpu_allocate,
'mem_source': job.memory_allocate, 'cpu_high': cpu_base,
'memory_base': mem_base, 'batch_res': batch_res,
'flops_res': flops_res, 'params_res': params_res, 'step_base': 0,
'reloadtime': []}
save_config_dir = task_submit_fix.check_path(job.name)
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job.name, job.name)
save_mod_path = '/tfdata/k8snfs/setbase/%s/%s_mod.json' % (job.name, job.name)
save_config(job_res_config, save_res_path)
save_config(job_mod_config, save_mod_path)
now_create = now_create + 1
np.save('nowcreate.npy', now_create)
if tasks['count'] < tasks['size'] and tasks['buffercount'] == 0:
save_mode_change(1, job.name, float(time.time()))
job.set_mod(1)
node_index, cpu_nodes, memory_nodes, total_cpu_use, total_mem_use = job_basic.schedule_base()
cpu_value, mem_value, cpu_node_value, mem_node_value = get_load_value(
node_index=node_index,
cpu_base=cpu_nodes,
memory_base=memory_nodes,
total_cpu_base=total_cpu_use,
total_memory_base=total_mem_use)
tmp_ps_replicas = job.ps_replicas
tmp_worker_replicas = job.worker_replicas
worker_need = math.ceil(
(job.training_step) * job.worker_replicas * mini_batch / ((job.deadline)))
worker_need_total = worker_need
if job.training_step <= 100:
job.worker_replicas = 1
else:
job.worker_replicas = worker_need_total
if cpu_value < 0.4:
if worker_need >= 5:
job.worker_replicas = 5
elif cpu_value < 0.7:
if worker_need >= 4:
job.worker_replicas = 4
else:
if worker_need >= 2:
job.worker_replicas = 2
catch_tmp_ps_re = random.randint(math.floor(job.worker_replicas / 4),
math.ceil(job.worker_replicas / 2))
if cpu_value < 0.4:
catch_tmp_ps_re = math.ceil(job.worker_replicas / 2)
elif cpu_value < 0.7:
catch_tmp_ps_re = math.ceil(job.worker_replicas / 3)
else:
catch_tmp_ps_re = math.ceil(job.worker_replicas / 4)
if catch_tmp_ps_re < 1:
catch_tmp_ps_re = 1
job.ps_replicas = catch_tmp_ps_re
# job.ps_replicas = 1
# job.worker_replicas = 2
job.training_step = math.ceil(
job.training_step * tmp_worker_replicas / job.worker_replicas)
save_job_change_layout(job.name, job.ps_replicas, job.worker_replicas,
job.training_step)
mem_need = job.total_mem * total_mem_use + job.worker_replicas * job.memory_allocate + 2048 * job.ps_replicas
cpu_need = job.total_cpu * total_cpu_use + job.worker_replicas * job.cpu_allocate + 750 * job.ps_replicas
catch_worker = 0
catch_ps = 0
node_keys = cpu_nodes.keys()
reach_ps = False
reach_worker = False
for key in node_keys:
catch_ps_c = 0
catch_ps_m = 0
catch_worker_c = 0
catch_worker_m = 0
can_use_cpu = job.node_cpu[key] * (1 - cpu_nodes[key])
can_use_mem = job.node_memory[key] * (1 - memory_nodes[key])
first_try = True
endcpu = False
endmem = False
while (not endcpu) or (not endmem):
if first_try:
if can_use_cpu - 720 > 0 and not reach_ps:
catch_ps_c += 1
can_use_cpu = can_use_cpu - 720
else:
if can_use_cpu - job.cpu_allocate > 0 and not reach_worker:
catch_worker_c += 1
can_use_cpu = can_use_cpu - job.cpu_allocate
if can_use_mem - 2000 > 0 and not reach_ps:
catch_ps_m += 1
can_use_mem = can_use_mem - 2000
else:
if can_use_mem - job.memory_allocate > 0 and not reach_worker:
catch_worker_m += 1
can_use_mem = can_use_mem - job.memory_allocate
first_try = False
else:
if can_use_cpu - job.cpu_allocate > 0 and not reach_worker:
catch_worker_c += 1
can_use_cpu = can_use_cpu - job.cpu_allocate
else:
if can_use_cpu - 720 > 0 and not reach_ps:
catch_ps_c += 1
can_use_cpu = can_use_cpu - 720
else:
endcpu = True
if can_use_mem - job.memory_allocate > 0 and not reach_worker:
catch_worker_m += 1
can_use_mem = can_use_mem - job.memory_allocate
else:
if can_use_mem - 2000 > 0 and not reach_ps:
catch_ps_m += 1
can_use_mem = can_use_mem - 2000
else:
endmem = True
if catch_worker_c < catch_worker_m:
catch_worker += catch_worker_c
else:
catch_worker += catch_worker_m
if catch_ps_c < catch_ps_m:
catch_ps += catch_ps_c
else:
catch_ps += catch_ps_m
if catch_ps >= job.ps_replicas:
reach_ps = True
if catch_worker >= job.worker_replicas:
reach_worker = True
if catch_ps >= job.ps_replicas and catch_worker >= job.worker_replicas:
break
print("catch_ps: %d catch_worker: %d" % (catch_ps, catch_worker))
if catch_ps < job.ps_replicas or catch_worker < job.worker_replicas:
tmp_ps = job.ps_replicas
tmp_worker = job.worker_replicas
if catch_ps > 0 and catch_worker > 0:
if catch_worker > job.worker_replicas:
catch_worker = job.worker_replicas
if catch_ps > job.ps_replicas:
catch_ps = job.ps_replicas
job.ps_replicas = catch_ps
job.worker_replicas = catch_worker
job.training_step = math.ceil(
job.training_step * tmp_worker / job.worker_replicas)
save_job_change_layout(job.name, catch_ps, catch_worker, job.training_step)
job.update_step()
write_step_meg(job.name)
connected = False
try_times = 1
while True:
if try_times > 5:
break
connected = loss_server_conn(ADDR, job.measure)
if connected:
break
else:
try_times += 1
if not connected:
print("Conncet error!!Try again Later!!")
# lock.release()
continue
while True:
lock.acquire()
if job.mod != 10:
job.set_mod(10)
save_mode_change(10, job.name, float(time.time()))
if not task2['label']:
if global_count == 2 or global_count == 3 or global_count % 45 == 1:
job.create_tf(mode=1)
else:
job.create_tf()
submit_time_now = time.time()
tongji_waiting_queue(job.name, submit_time_now)
ns_tmp = tasks['ns']
ns_tmp.append(job.name)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
is_layout[job.name] = False
tasks['nslayout'] = is_layout
jobs.append(job.name)
tasks['count'] += 1
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (
job.name, job.name)
res_config = load_config(save_res_path)
lock.release()
batch_res = res_config['batch_res']
flops_res = res_config['flops_res']
params_res = res_config['params_res']
pool.apply_async(catch_node_step_msg,
args=(
jobs, job.name, tasks, lock, batch_res, flops_res,
params_res, 1, task2))
break
else:
lock.release()
time.sleep(2.9)
else:
job.ps_replicas = 1
job.worker_replicas = 1
job.training_step = job.training_step * tmp_worker
job.set_mod(new_mod=3)
save_mode_change(3, job.name, float(time.time()))
lock.acquire()
save_job_change_layout(job.name, 1, 1, job.training_step)
tmp_next = tasks['next']
tmp_next.append(job.name)
tmp_next_time_config = tasks['nexttimes']
tmp_next_time_config[job.name] = 0
tasks['nexttimes'] = tmp_next_time_config
tasks['next'] = tmp_next
lock.release()
# tasks['next'] = job.name
else:
job.update_step()
write_step_meg(job.name)
connected = False
try_times = 1
while True:
if try_times > 5:
break
connected = loss_server_conn(ADDR, job.measure)
if connected:
break
else:
try_times += 1
if not connected:
print("Conncet error!!Try again Later!!")
# lock.release()
continue
while True:
lock.acquire()
if job.mod != 10:
job.set_mod(10)
save_mode_change(10, job.name, float(time.time()))
if not task2['label']:
if global_count == 2 or global_count == 3 or global_count % 45 == 1:
job.create_tf(mode=1)
else:
job.create_tf()
submit_time_now = time.time()
tongji_waiting_queue(job.name, submit_time_now)
ns_tmp = tasks['ns']
ns_tmp.append(job.name)
tasks['ns'] = ns_tmp
# job_tmp = tasks['job']
# job_tmp[job.name] = job
# tasks['job'] = job_tmp
is_layout = tasks['nslayout']
is_layout[job.name] = False
tasks['nslayout'] = is_layout
jobs.append(job.name)
tasks['count'] += 1
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (
job.name, job.name)
res_config = load_config(save_res_path)
lock.release()
batch_res = res_config['batch_res']
flops_res = res_config['flops_res']
params_res = res_config['params_res']
pool.apply_async(catch_node_step_msg,
args=(
jobs, job.name, tasks, lock, batch_res, flops_res,
params_res, 1, task2))
break
else:
lock.release()
time.sleep(2.9)
elif tasks['count'] >= tasks['size']:
job.set_mod(2)
save_mode_change(2, job.name, float(time.time()))
lock.acquire()
worker_buffer = tasks['buffer']
worker_buffer.append(job.name)
tasks['buffer'] = worker_buffer
tmp_buffer_count = tasks['buffercount']
tmp_buffer_count = tmp_buffer_count + 1
tasks['buffercount'] = tmp_buffer_count
lock.release()
else:
# lock.acquire()
job.set_mod(2)
save_mode_change(2, job.name, float(time.time()))
worker_buffer = tasks['buffer']
worker_buffer.append(job.name)
tmp_buffer_count = tasks['buffercount']
tmp_buffer_count = tmp_buffer_count + 1
tasks['buffercount'] = tmp_buffer_count
# lock.release()
node_index, cpu_nodes, memory_nodes, total_cpu_use, total_mem_use = job_basic.schedule_base()
cpu_value, mem_value, cpu_node_value, mem_node_value = get_load_value(
node_index=node_index,
cpu_base=cpu_nodes,
memory_base=memory_nodes,
total_cpu_base=total_cpu_use,
total_memory_base=total_mem_use)
if cpu_value < 0.4:
selected = False
selected_job_name = ''
for job_name in worker_buffer:
rea = max_free_heap.add(job_name)
if rea is not None:
selected_job_name = rea
selected = True
break
if not selected:
selected_job_name = max_free_heap.items[0]
print(selected_job_name)
worker_buffer = max_free_heap.items
print(worker_buffer)
if not selected:
ceshi_name = worker_buffer.pop(0)
# tmp_buffer = tasks['buffer']
# tmp_buffer.remove(selected_job_name)
print(ceshi_name)
# lock.acquire()
tasks['buffer'] = worker_buffer[:]
# tmp_buffer_size =
max_free_heap.clear()
if selected:
tasks['buffercount'] = max_buffer_size
else:
tmp_buffer_count = tmp_buffer_count - 1
tasks['buffercount'] = tmp_buffer_count
# lock.release()
else:
selected = False
selected_job_name = ''
for job_name in worker_buffer:
# max_wight_heap
rea = max_wight_heap.add(job_name)
if rea is not None:
selected_job_name = rea
selected = True
break
if not selected:
selected_job_name = max_wight_heap.items[0]
worker_buffer = max_wight_heap.items
print(worker_buffer)
print(selected_job_name)
if not selected:
ceshi_name = worker_buffer.pop(0)
# tmp_buffer = tasks['buffer']
# tmp_buffer.remove(selected_job_name)
print(ceshi_name)
# lock.acquire()
tasks['buffer'] = worker_buffer[:]
# tmp_buffer_size =
max_wight_heap.clear()
if selected:
tasks['buffercount'] = max_buffer_size
else:
tmp_buffer_count = tmp_buffer_count - 1
tasks['buffercount'] = tmp_buffer_count
# lock.release()
job = reload_jobs(selected_job_name, -1)
job.set_mod(1)
save_mode_change(1, selected_job_name, float(time.time()))
# selected_res_config2
tmp_ps_replicas = job.ps_replicas
tmp_worker_replicas = job.worker_replicas
selected_res_config_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (
selected_job_name, selected_job_name)
selected_res_config2 = load_config(selected_res_config_path)
using_flops = selected_res_config2['flops_res']
using_param = selected_res_config2["params_res"]
using_cpu_base = selected_res_config2['cpu_high']
using_mem_base = selected_res_config2['memory_base']
using_min_batch = predict_min_first(rfr=rfr,
cpu_alpha=job.cpu_allocate / using_cpu_base,
mem_alpha=job.memory_allocate / using_mem_base,
batch=job.batch_size, flops=using_flops,
params=using_param)
using_min_batch = float(using_min_batch)
tmp_rest = job.deadline + job.starttime - time.time()
# job.worker_replicas = 2
if tmp_rest > 0:
_, _, atmp = job.get_remain(mode=0)
worker_need = math.ceil(
(job.training_step - atmp) * job.worker_replicas * using_min_batch / (
(tmp_rest)))
worker_need_total = worker_need
if job.training_step - atmp <= 2:
job.worker_replicas = 1
else:
job.worker_replicas = worker_need_total
if cpu_value < 0.4:
if worker_need >= 6:
job.worker_replicas = 6
elif cpu_value < 0.7:
if worker_need >= 4:
job.worker_replicas = 4
else:
if worker_need >= 2:
job.worker_replicas = 2
# job.get_remain()
else:
if cpu_value < 0.4:
job.worker_replicas = random.randint(3, 5)
elif cpu_value < 0.7:
job.worker_replicas = random.randint(2, 3)
else:
job.worker_replicas = random.randint(1, 2)
catch_tmp_ps_re = random.randint(math.floor(job.worker_replicas / 4),
math.ceil(job.worker_replicas / 2))
# catch_tmp_ps_re = 1
if cpu_value < 0.4:
catch_tmp_ps_re = math.ceil(job.worker_replicas / 2)
elif cpu_value < 0.7:
catch_tmp_ps_re = math.ceil(job.worker_replicas / 3)
else:
catch_tmp_ps_re = math.ceil(job.worker_replicas / 4)
if catch_tmp_ps_re < 1:
catch_tmp_ps_re = 1
# if catch_tmp_ps_re < 1:
# catch_tmp_ps_re = 1
job.ps_replicas = catch_tmp_ps_re
job.training_step = math.ceil(
job.training_step * tmp_worker_replicas / job.worker_replicas)
save_job_change_layout(job.name, job.ps_replicas, job.worker_replicas,
job.training_step)
mem_need = job.total_mem * total_mem_use + job.worker_replicas * job.memory_allocate + 2048 * job.ps_replicas
cpu_need = job.total_cpu * total_cpu_use + job.worker_replicas * job.cpu_allocate + 750 * job.ps_replicas
catch_worker = 0
catch_ps = 0
node_keys = cpu_nodes.keys()
reach_ps = False
reach_worker = False
for key in node_keys:
catch_ps_c = 0
catch_ps_m = 0
catch_worker_c = 0
catch_worker_m = 0
can_use_cpu = job.node_cpu[key] * (1 - cpu_nodes[key])
can_use_mem = job.node_memory[key] * (1 - memory_nodes[key])
first_try = True
endcpu = False
endmem = False
while (not endcpu) or (not endmem):
if first_try:
if can_use_cpu - 720 > 0 and not reach_ps:
catch_ps_c += 1
can_use_cpu = can_use_cpu - 720
else:
if can_use_cpu - job.cpu_allocate > 0 and not reach_worker:
catch_worker_c += 1
can_use_cpu = can_use_cpu - job.cpu_allocate
if can_use_mem - 2000 > 0 and not reach_ps:
catch_ps_m += 1
can_use_mem = can_use_mem - 2000
else:
if can_use_mem - job.memory_allocate > 0 and not reach_worker:
catch_worker_m += 1
can_use_mem = can_use_mem - job.memory_allocate
first_try = False
else:
if can_use_cpu - job.cpu_allocate > 0 and not reach_worker:
catch_worker_c += 1
can_use_cpu = can_use_cpu - job.cpu_allocate
else:
if can_use_cpu - 750 > 0 and not reach_ps:
catch_ps_c += 1
can_use_cpu = can_use_cpu - 750
else:
endcpu = True
if can_use_mem - job.memory_allocate > 0 and not reach_worker:
catch_worker_m += 1
can_use_mem = can_use_mem - job.memory_allocate
else:
if can_use_mem - 2000 > 0 and not reach_ps:
catch_ps_m += 1
can_use_mem = can_use_mem - 2000
else:
endmem = True
if catch_worker_c < catch_worker_m:
catch_worker += catch_worker_c
else:
catch_worker += catch_worker_m
if catch_ps_c < catch_ps_m:
catch_ps += catch_ps_c
else:
catch_ps += catch_ps_m
if catch_ps >= job.ps_replicas:
reach_ps = True
if catch_worker >= job.worker_replicas:
reach_worker = True
if catch_ps >= job.ps_replicas and catch_worker >= job.worker_replicas:
break
print("catch_ps: %d catch_worker: %d" % (catch_ps, catch_worker))
if catch_ps < job.ps_replicas or catch_worker < job.worker_replicas:
tmp_ps = job.ps_replicas
tmp_worker = job.worker_replicas
if catch_ps > 0 and catch_worker > 0:
if catch_worker > job.worker_replicas:
catch_worker = job.worker_replicas
if catch_ps > job.ps_replicas:
catch_ps = job.ps_replicas
job.ps_replicas = catch_ps
job.worker_replicas = catch_worker
job.training_step = math.ceil(
job.training_step * tmp_worker / job.worker_replicas)
save_job_change_layout(job.name, catch_ps, catch_worker, job.training_step)
job.update_step()
write_step_meg(job.name)
connected = False
try_times = 1
while True:
if try_times > 5:
break
connected = loss_server_conn(ADDR, job.measure)
if connected:
break
else:
try_times += 1
if not connected:
print("Conncet error!!Try again Later!!")
# lock.release()
continue
while True:
lock.acquire()
if job.mod != 10:
job.set_mod(10)
save_mode_change(10, job.name, float(time.time()))
if not task2['label']:
if global_count == 2 or global_count == 3 or global_count % 45 == 1:
job.create_tf(mode=1)
else:
job.create_tf()
submit_time_now = time.time()
tongji_waiting_queue(job.name, submit_time_now)
ns_tmp = tasks['ns']
ns_tmp.append(job.name)
tasks['ns'] = ns_tmp
# job_tmp = tasks['job']
# job_tmp[job.name] = job
# tasks['job'] = job_tmp
is_layout = tasks['nslayout']
is_layout[job.name] = False
tasks['nslayout'] = is_layout
jobs.append(job.name)
tasks['count'] += 1
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (
job.name, job.name)
res_config = load_config(save_res_path)
lock.release()
batch_res = res_config['batch_res']
flops_res = res_config['flops_res']
params_res = res_config['params_res']
pool.apply_async(catch_node_step_msg,
args=(
jobs, job.name, tasks, lock, batch_res, flops_res,
params_res, 1, task2))
break
else:
lock.release()
time.sleep(2.9)
else:
job.ps_replicas = 1
job.worker_replicas = 1
job.training_step = job.training_step = math.ceil(
job.training_step * tmp_worker)
save_job_change_layout(job.name, 1, 1, training_step=job.training_step)
job.set_mod(3)
save_mode_change(3, job.name, float(time.time()))
# tasks['next'] = job.name
lock.acquire()
tmp_next = tasks['next']
tmp_next.append(job.name)
tmp_next_time_config = tasks['nexttimes']
tmp_next_time_config[job.name] = 0
tasks['nexttimes'] = tmp_next_time_config
tasks['next'] = tmp_next
lock.release()
else:
job.update_step()
write_step_meg(job.name)
connected = False
try_times = 1
while True:
if try_times > 5:
break
connected = loss_server_conn(ADDR, job.measure)
if connected:
break
else:
try_times += 1
if not connected:
print("Conncet error!!Try again Later!!")
# lock.release()
continue
while True:
lock.acquire()
if job.mod != 10:
job.set_mod(10)
save_mode_change(10, job.name, float(time.time()))
if not task2['label']:
if global_count == 2 or global_count == 3 or global_count % 45 == 1:
job.create_tf(mode=1)
else:
job.create_tf()
submit_time_now = time.time()
tongji_waiting_queue(job.name, submit_time_now)
ns_tmp = tasks['ns']
ns_tmp.append(job.name)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
is_layout[job.name] = False
tasks['nslayout'] = is_layout
jobs.append(job.name)
tasks['count'] += 1
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (
job.name, job.name)
res_config = load_config(save_res_path)
lock.release()
batch_res = res_config['batch_res']
flops_res = res_config['flops_res']
params_res = res_config['params_res']
pool.apply_async(catch_node_step_msg,
args=(
jobs, job.name, tasks, lock, batch_res, flops_res,
params_res, 1, task2))
break
else:
lock.release()
time.sleep(3)
tmp_reload = tasks['reload']
tmp_reload = 0
tasks['reload'] = tmp_reload
break
global_count += 1
# and global_count%45 > 1
# and global_count%45 > 1
# and global_count%45 > 1
# and global_count % 45 > 1
# and global_count % 45 > 1
if global_count % 11 == 0 and global_count%9!=0 and global_count % 45 > 1:
for iter0 in range(2):
aim_assign_config = {}
mode1 = 0
time10 = time.time()
try:
lock.acquire()
tasks['modulate'] = True
lock.release()
try:
aim_assign_config,mode1 = assign_jobs(tasks,rfr=rfr,lock=lock)
except Exception as e00:
print("The error exist in dynamic modulation:")
print(e00)
print(aim_assign_config)
print(mode1)
# mode_saves = {}
lock.acquire()
tasks['modulate'] = False
lock.release()
except Exception as e:
print(e)
# lock.release()
time.sleep(19.2)
continue
time20 = time.time()
print(aim_assign_config)
print("Mode is %d" % mode1)
if mode1 == 0:
if iter0 == 0:
try:
mode_saves = load_config("mode.json")
except Exception as sese:
mode_saves = {'ad': []}
save_config(mode_saves, "mode.json")
tmp_mode_save = mode_saves['ad'][:]
one_mess = {'time': float(time.time()), 'mode': mode1,'need':0}
tmp_mode_save.append(one_mess)
mode_saves['ad'] = tmp_mode_save
save_config(mode_saves, "mode.json")
continue
elif mode1 == -1:
if iter0 == 0:
try:
mode_saves = load_config("mode.json")
except Exception as sese:
mode_saves = {'ad': []}
save_config(mode_saves, "mode.json")
tmp_mode_save = mode_saves['ad'][:]
one_mess = {'time': float(time.time()), 'mode': mode1,'need':0}
tmp_mode_save.append(one_mess)
mode_saves['ad'] = tmp_mode_save
save_config(mode_saves, "mode.json")
continue
elif not aim_assign_config:
if iter0 == 0:
try:
mode_saves = load_config("mode.json")
except Exception as sese:
mode_saves = {'ad': []}
save_config(mode_saves, "mode.json")
tmp_mode_save = mode_saves['ad'][:]
one_mess = {'time': float(time.time()), 'mode': mode1, 'need': 0}
tmp_mode_save.append(one_mess)
mode_saves['ad'] = tmp_mode_save
save_config(mode_saves, "mode.json")
continue
else:
assign_key = list(aim_assign_config.keys())
assign_key2 = []
for akk in assign_key:
if aim_assign_config[akk]:
assign_key2.append(akk)
assign_key = assign_key2
print(assign_key)
if not assign_key:
continue
jinxing = False
aim_ns = []
for assign in assign_key:
lock.acquire()
tmp_ns0 = tasks['ns']
lock.release()
if (aim_assign_config[assign]) and (assign in tmp_ns0):
pod_status00 = [ps.status.phase for ps in v1.list_namespaced_pod(assign).items]
if pod_status00:
if (not ('Succeeded' in pod_status00 or 'Failed' in pod_status00)):
jinxing = True
aim_ns.append(assign)
print("At last the aim can be decided as:")
print(aim_ns)
try:
mode_saves = load_config("mode.json")
except Exception as sese:
mode_saves = {'ad': []}
save_config(mode_saves, "mode.json")
tmp_mode_save = mode_saves['ad'][:]
one_mess = {'time': float(time.time()), 'mode': mode1, 'need': len(aim_ns)}
tmp_mode_save.append(one_mess)
mode_saves['ad'] = tmp_mode_save
save_config(mode_saves, "mode.json")
# if iter0 == 0:
if jinxing:
lock.acquire()
tmp_retry_ns = tasks['retry']
tmp_retry_solution = tasks['solution']
is_layout = tasks['nslayout']
if mode1 == 2:
try:
for iaim in range(len(aim_ns)-1,-1,-1):
tmp_retry_ns.append(aim_ns[iaim])
tmp_retry_solution[aim_ns[iaim]] = aim_assign_config[aim_ns[iaim]]
is_layout[aim_ns[iaim]] = False
except Exception as ex0:
print(ex0)
for aim in aim_ns:
if aim in tmp_retry_ns:
tmp_retry_ns.remove(aim)
tmp_retry_solution.pop(aim)
is_layout[aim] = True
for aim in aim_ns:
tmp_retry_ns.append(aim)
tmp_retry_solution[aim] = aim_assign_config[aim]
is_layout[aim] = False
# lock.release()
else:
for aim in aim_ns:
tmp_retry_ns.append(aim)
tmp_retry_solution[aim] = aim_assign_config[aim]
is_layout[aim] = False
tasks['retry'] = tmp_retry_ns
tasks['solution'] = tmp_retry_solution
tasks['nslayout'] = is_layout
lock.release()
tongji_adjust_number(aim_ns)
print("Modulation once cost %f" % float(time20 - time10))
if (mode1==1 or mode1==4) and (iter0>1):
break
time.sleep(27)
global_count+=1
# if global_count == 5:
# need_s = load_config("modify.json")
# need_buffer = need_s['pool']
# for i
def jiance(tasks,lock,tasks2):
try:
task2 = load_config('through.json')
task3 = load_config('buffer.json')
task4 = load_config("noderes.json")
# aa = 0
except Exception as eee:
task2 = {}
task3 = {}
task4 = {}
task2['through'] = {}
task3['buffer'] = {}
task4['cpu'] = {}
task4['mem'] = {}
task4['rank'] = {}
task4['time'] = []
print("will create them")
print(eee)
while True:
if tasks['start']==True:
time.sleep(57)
lock.acquire()
tmp_count1 = tasks['count']
tmp_bucount = tasks['buffercount']
tmp_nextcount = len(tasks['next'])
save_config(tasks,'system_info.json')
save_config(tasks2,'node_label.json')
tmp_cpu = tasks2['cpu']
tmp_mem = tasks2['mem']
tmp_rank = tasks2['rank']
tmp_buffer = tasks["buffer"]
tmp_jobs = tasks['ns']
lock.release()
pend_num = 0
try:
tmp_time = time.time()
tmp_throughput = task2['through']
for tns in tmp_jobs:
try:
pod_status2 = [i.status.phase for i in v1.list_namespaced_pod(tns).items]
if 'Pending' in pod_status2 and 'Succeeded' not in pod_status2 and 'Failed' not in pod_status2:
pend_num += 1
except Exception as eke:
print(eke)
continue
tmp_throughput[tmp_time] = {'count': tmp_count1, 'buf': tmp_bucount, 'next': tmp_nextcount,'pend':pend_num}
task2['through'] = tmp_throughput
tmp_buffer_cond = task3['buffer']
tmp_buffer_cond[tmp_time] = tmp_buffer
task3['buffer'] = tmp_buffer_cond
tck = list(tmp_cpu.keys())
for tc in tck:
try:
task4['cpu'][tc].append(tmp_cpu[tc])
except Exception as tce:
task4['cpu'][tc] = []
task4['cpu'][tc].append(tmp_cpu[tc])
tck = list(tmp_mem.keys())
for tc in tck:
try:
task4['mem'][tc].append(tmp_mem[tc])
except Exception as tce:
task4['mem'][tc] = []
task4['mem'][tc].append(tmp_mem[tc])
tck = list(tmp_rank.keys())
for tc in tck:
try:
task4['rank'][tc].append(tmp_rank[tc])
except Exception as tce:
task4['rank'][tc] = []
task4['rank'][tc].append(tmp_rank[tc])
task4['time'].append(float(time.time()))
save_config(task2,'through.json')
save_config(task3,'buffer.json')
save_config(task4,'noderes.json')
except Exception as eeee:
print(eeee)
print('saved configs')
time.sleep(57)
else:
break
def save_job_change_layout(job_name,ps_n,worker_n,training_step,mode=0):
save_job_path = '/tfdata/k8snfs/setbase/%s/%s.json' % (job_name, job_name)
save_change_path = '/tfdata/k8snfs/setbase/%s/%s_pw.json' % (job_name, job_name)
try:
job_res_config = load_config(save_change_path)
except Exception as e:
job_res_config = {}
job_res_config['changen'] = {}
job_config = load_config(save_job_path)
job_res_config['ps'] = job_config['ps_replicas']
job_res_config['worker'] = job_config['worker_replicas']
job_res_config['training_step'] = job_config['training_step']
save_config(job_res_config,save_change_path)
job_res_config = load_config(save_change_path)
timenow = time.time()
tmp_changen = job_res_config['changen']
tmp_changen[timenow] = {'psbefore': job_res_config['ps'], 'wbefore': job_res_config['worker'],
'stepbefore': job_res_config['training_step'], 'psnow': ps_n, 'wnow': worker_n,
'stepnow': training_step}
job_res_config['ps'] = ps_n
job_res_config['worker'] = worker_n
job_res_config['training_step'] = training_step
job_config = load_config(save_job_path)
if 'retry' not in job_config:
job_config['retry'] = 0
if mode != 0:
job_config['retry'] = job_config['retry']+1
job_config['ps_replicas'] = ps_n
job_config['worker_replicas'] = worker_n
job_config['training_step'] = training_step
job_res_config['changen'] = tmp_changen
save_config(job_res_config,save_change_path)
save_config(job_config, save_job_path)
def save_job_change_resource(job_name,cpu_allocate,mem_allocate):
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job_name, job_name)
save_change_path = '/tfdata/k8snfs/setbase/%s/%s_change.json' % (job_name, job_name)
change_dir = {}
try:
change_dir = load_config(save_change_path)
except Exception as eek:
change_dir['changer'] = {}
job_res_config = load_config(save_res_path)
change_dir['cpu'] = job_res_config['cpu_source']
change_dir['mem'] = job_res_config['mem_source']
# tmp_changer = job_res_config['changer']
tmp_changer = change_dir['changer']
timenow = time.time()
tmp_changer[timenow] = {"cpubefore":change_dir['cpu'],'membefore':change_dir['mem'],'memnow': mem_allocate,'cpunow':cpu_allocate}
change_dir['cpu'] = cpu_allocate
change_dir['mem'] = mem_allocate
job_res_config = load_config(save_res_path)
job_res_config['cpu_source'] = cpu_allocate
job_res_config['mem_source'] = mem_allocate
change_dir['changer'] = tmp_changer
# job_res_config['changer'] = tmp_changer
save_config(job_res_config, save_res_path)
save_config(change_dir,save_change_path)
def read_step_base(job_name):
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job_name, job_name)
job_res_config = load_config(save_res_path)
key = job_res_config.keys()
key_list = list(key)
if 'step_base' not in key_list:
job_res_config['step_base'] = 0
step_base = job_res_config['step_base']
return int(step_base)
def write_step_base(job_name,step_base):
save_res_path = '/tfdata/k8snfs/setbase/%s/%s_res.json' % (job_name, job_name)
job_res_config = load_config(save_res_path)
job_res_config['step_base'] = step_base
save_config(job_res_config,save_res_path)
print("save step base successfully!!!")
if __name__ == '__main__':
kubernetes.config.load_kube_config()
v1 = kubernetes.client.CoreV1Api()
# v1.list_node()
mgr = multiprocessing.Manager()
tasks = mgr.dict()
tasks2 = mgr.dict()
lock = mgr.Lock()
jobs = mgr.list()
config_content = load_config('system_info.json')
config_content2 = load_config('node_label.json')
for key,value in config_content.items():
tasks[key] = value
for key,value in config_content2.items():
tasks2[key] = value
print(tasks)
print(tasks2)
for ns in tasks["ns"]:
# job_reload = reload_jobs(ns,-1)
jobs.append(ns)
# tasks['ns'] = []
# tasks['job'] = {}
q = multiprocessing.Manager().Queue(maxsize=tasks['size'])
tasks['through'] = {}
tasks['start'] = True
url = 'https://192.168.128.10:6443/apis/metrics.k8s.io/v1beta1/nodes'
args = parse()
client = influxdb.InfluxDBClient('192.168.128.10', port=8086, username='admin', password='admin',
database=args.database)
# node_p = Node_mess(url=url,derivation=10,args=args)
node_p = Node_mess(url=url, args=args,tasks=tasks,v1=v1)
base_job_name = 'vgg-732-732'
submit_p = multiprocessing.Process(target=Submit_job,args=(tasks,lock,v1,jobs,tasks2))
monitor_p = multiprocessing.Process(target=Monitor_job,args=(tasks,lock,v1,jobs))
jiance_p = multiprocessing.Process(target=jiance, args=(tasks, lock,tasks2))
label_p = multiprocessing.Process(target=make_label_to_nodes,args=(tasks2,base_job_name))
# derivation
node_p.daemon = True
# submit_p.daemon = True
# monitor_p.daemon = True
jiance_p.daemon = True
label_p.daemon = True
k1 = os.getpid()
# v1.list_namespace(timeout=)
k2 = multiprocessing.current_process().pid
# v1.delete_namespace()
print(k1, k2)
while True:
boots = input("Please Input 'start' to start:\n")
if boots == 'start':
time_open = math.ceil(time.time())
tmp_list = tasks["creation"]
tmp_list.append(time_open)
tasks["creation"] = tmp_list
node_p.start()
submit_p.start()
monitor_p.start()
jiance_p.start()
label_p.start()
if boots == 'end':
tasks['start'] = False
time.sleep(10)
submit_p.join()
monitor_p.join()
if tasks['count']>0:
for ns in tasks['ns']:
print(tasks['ns'])
print("deal ns:"+ns)
pod_status = [i.status.phase for i in v1.list_namespaced_pod(ns).items]
if 'Succeeded' in pod_status or 'Failed' in pod_status:
time.sleep(float(random.randint(3, 10)))
lock.acquire()
try:
ns_tmp = tasks['ns']
command = 'kubectl delete -f /tfdata/tfcnn/expjobbase/' + ns + '.yaml'
os.system(command)
deletehelp2(ns, v1)
ns_tmp.remove(ns)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
print("is layout: \n")
print(is_layout)
is_layout.pop(ns)
tasks['nslayout'] = is_layout
print("after deal: \n")
print(tasks['nslayout'])
# tasks['job'].pop(ns)
tasks['count'] = len(ns_tmp)
finishes = tasks['finish']
finishes.append(ns)
tasks['finish'] = finishes
print(tasks['count'])
lock.release()
except Exception as eess:
ns_tmp = tasks['ns']
if ns in ns_tmp:
ns_tmp.remove(ns)
tasks['ns'] = ns_tmp
is_layout = tasks['nslayout']
print("is layout: \n")
print(is_layout)
if ns in list(is_layout.keys()):
is_layout.pop(ns)
tasks['nslayout'] = is_layout
print("after deal: \n")
print(tasks['nslayout'])
tasks['count'] = len(ns_tmp)
finishes = tasks['finish']
if ns not in finishes:
finishes.append(ns)
tasks['finish'] = finishes
print(tasks['count'])
lock.release()
print(eess)
time.sleep(5)
time_last = math.ceil(time.time())
tmp_list = tasks['endtime']
tmp_list.append(time_last)
tasks["endtime"] = tmp_list
save_config(tasks,filename='system_info.json')
print('System end!')
break |
optimization.py | import hashlib
import json
from copy import copy
from datetime import datetime
from itertools import product
from logging import getLogger
from threading import Thread, Event
from time import time
from typing import Union, Any, Sequence, Optional, Mapping, Callable
from .job import TrainsJob
from .parameters import Parameter
from ..task import Task
logger = getLogger('trains.automation.optimization')
try:
import pandas as pd
Task.add_requirements('pandas')
except ImportError:
pd = None
logger.warning('Pandas is not installed, summary table reporting will be skipped.')
class Objective(object):
"""
Optimization ``Objective`` class to maximize / minimize over all experiments. This class will sample a specific
scalar from all experiments, and maximize / minimize over single scalar (i.e., title and series combination).
``SearchStrategy`` and ``HyperParameterOptimizer`` use ``Objective`` in the strategy search algorithm.
"""
def __init__(self, title, series, order='max', extremum=False):
# type: (str, str, str, bool) -> ()
"""
Construct ``Objective`` object that will return the scalar value for a specific task ID.
:param str title: The scalar graph title to sample from.
:param str series: The scalar series title to sample from.
:param str order: The setting for maximizing or minimizing the objective scalar value.
The values are:
- ``max``
- ``min``
:param bool extremum: Return the global minimum / maximum reported metric value?
The values are:
- ``True`` - Return the global minimum / maximum reported metric value.
- ``False`` - Return the last value reported for a specific Task. (Default)
"""
self.title = title
self.series = series
assert order in ('min', 'max',)
# normalize value so we always look for the highest objective value
self.sign = -1 if (isinstance(order, str) and order.lower().strip() == 'min') else +1
self._metric = None
self.extremum = extremum
def get_objective(self, task_id):
# type: (Union[str, Task, TrainsJob]) -> Optional[float]
"""
Return a specific task scalar value based on the objective settings (title/series).
:param str task_id: The Task id to retrieve scalar from (or ``TrainsJob`` object).
:return: The scalar value.
"""
# create self._metric
self._get_last_metrics_encode_field()
if isinstance(task_id, Task):
task_id = task_id.id
elif isinstance(task_id, TrainsJob):
task_id = task_id.task_id()
# noinspection PyBroadException, Py
try:
# noinspection PyProtectedMember
task = Task._query_tasks(
task_ids=[task_id], only_fields=['last_metrics.{}.{}'.format(self._metric[0], self._metric[1])])[0]
except Exception:
return None
metrics = task.last_metrics
# noinspection PyBroadException
try:
values = metrics[self._metric[0]][self._metric[1]]
if not self.extremum:
return values['value']
return values['min_value'] if self.sign < 0 else values['max_value']
except Exception:
return None
def get_current_raw_objective(self, task):
# type: (Union[TrainsJob, Task]) -> (int, float)
"""
Return the current raw value (without sign normalization) of the objective.
:param str task: The Task or Job to retrieve scalar from (or ``TrainsJob`` object).
:return: Tuple(iteration, value) if, and only if, the metric exists. None if the metric does not exist.
"""
if not isinstance(task, Task):
if hasattr(task, 'task'):
task = task.task
if not isinstance(task, Task):
task = Task.get_task(task_id=str(task))
if not task:
raise ValueError("Task object could not be found")
# todo: replace with more efficient code
scalars = task.get_reported_scalars()
# noinspection PyBroadException
try:
return scalars[self.title][self.series]['x'][-1], scalars[self.title][self.series]['y'][-1]
except Exception:
return None
def get_objective_sign(self):
# type: () -> float
"""
Return the sign of the objective.
- ``+1`` - If maximizing
- ``-1`` - If minimizing
:return: Objective function sign.
"""
return self.sign
def get_objective_metric(self):
# type: () -> (str, str)
"""
Return the metric title, series pair of the objective.
:return: (title, series)
"""
return self.title, self.series
def get_normalized_objective(self, task_id):
# type: (Union[str, Task, TrainsJob]) -> Optional[float]
"""
Return a normalized task scalar value based on the objective settings (title/series).
I.e. objective is always to maximize the returned value
:param str task_id: The Task id to retrieve scalar from.
:return: Normalized scalar value.
"""
objective = self.get_objective(task_id=task_id)
if objective is None:
return None
# normalize value so we always look for the highest objective value
return self.sign * objective
def _get_last_metrics_encode_field(self):
# type: () -> str
"""
Return encoded representation of the title/series metric.
:return: The objective title/series.
"""
if not self._metric:
title = hashlib.md5(str(self.title).encode('utf-8')).hexdigest()
series = hashlib.md5(str(self.series).encode('utf-8')).hexdigest()
self._metric = title, series
return '{}last_metrics.{}.{}.{}'.format(
'-' if self.sign > 0 else '', self._metric[0], self._metric[1],
('min_value' if self.sign < 0 else 'max_value') if self.extremum else 'value')
class Budget(object):
class Field(object):
def __init__(self, limit=None):
# type: (Optional[float]) -> ()
self.limit = limit
self.current = {}
def update(self, uid, value):
# type: (Union[str, int], float) -> ()
if value is not None:
try:
self.current[uid] = float(value)
except (TypeError, ValueError):
pass
@property
def used(self):
# type: () -> (Optional[float])
if self.limit is None or not self.current:
return None
return sum(self.current.values())/float(self.limit)
def __init__(self, jobs_limit, iterations_limit, compute_time_limit):
# type: (Optional[int], Optional[int], Optional[float]) -> ()
self.jobs = self.Field(jobs_limit)
self.iterations = self.Field(iterations_limit)
self.compute_time = self.Field(compute_time_limit)
def to_dict(self):
# type: () -> (Mapping[str, Mapping[str, float]])
# returned dict is Mapping[Union['jobs', 'iterations', 'compute_time'], Mapping[Union['limit', 'used'], float]]
current_budget = {}
jobs = self.jobs.used
if jobs:
current_budget['jobs'] = {'limit': self.jobs.limit, 'used': jobs}
iterations = self.iterations.used
if iterations:
current_budget['iterations'] = {'limit': self.iterations.limit, 'used': iterations}
compute_time = self.compute_time.used
if compute_time:
current_budget['compute_time'] = {'limit': self.compute_time.limit, 'used': compute_time}
return current_budget
class SearchStrategy(object):
"""
The base search strategy class. Inherit this class to implement your custom strategy.
"""
_tag = 'optimization'
_job_class = TrainsJob # type: TrainsJob
def __init__(
self,
base_task_id, # type: str
hyper_parameters, # type: Sequence[Parameter]
objective_metric, # type: Objective
execution_queue, # type: str
num_concurrent_workers, # type: int
pool_period_min=2., # type: float
time_limit_per_job=None, # type: Optional[float]
max_iteration_per_job=None, # type: Optional[int]
total_max_jobs=None, # type: Optional[int]
**_ # type: Any
):
# type: (...) -> ()
"""
Initialize a search strategy optimizer.
:param str base_task_id: The Task ID (str)
:param list hyper_parameters: The list of parameter objects to optimize over.
:param Objective objective_metric: The Objective metric to maximize / minimize.
:param str execution_queue: The execution queue to use for launching Tasks (experiments).
:param int num_concurrent_workers: The maximum number of concurrent running machines.
:param float pool_period_min: The time between two consecutive pools (minutes).
:param float time_limit_per_job: The maximum execution time per single job in minutes. When time limit is
exceeded, the job is aborted. (Optional)
:param int max_iteration_per_job: The maximum iterations (of the Objective metric) per single job. When maximum
iterations is exceeded, the job is aborted. (Optional)
:param int total_max_jobs: The total maximum jobs for the optimization process. The default value is ``None``,
for unlimited.
"""
super(SearchStrategy, self).__init__()
self._base_task_id = base_task_id
self._hyper_parameters = hyper_parameters
self._objective_metric = objective_metric
self._execution_queue = execution_queue
self._num_concurrent_workers = num_concurrent_workers
self.pool_period_minutes = pool_period_min
self.time_limit_per_job = time_limit_per_job
self.max_iteration_per_job = max_iteration_per_job
self.total_max_jobs = total_max_jobs
self._stop_event = Event()
self._current_jobs = []
self._pending_jobs = []
self._num_jobs = 0
self._job_parent_id = None
self._created_jobs_ids = {}
self._naming_function = None
self._job_project = {}
self.budget = Budget(
jobs_limit=self.total_max_jobs,
compute_time_limit=self.total_max_jobs * self.time_limit_per_job if
self.time_limit_per_job and self.total_max_jobs else None,
iterations_limit=self.total_max_jobs * self.max_iteration_per_job if
self.max_iteration_per_job and self.total_max_jobs else None
)
self._validate_base_task()
self._optimizer_task = None
def start(self):
# type: () -> ()
"""
Start the Optimizer controller function loop(). If the calling process is stopped, the controller will stop
as well.
.. important::
This function returns only after the optimization is completed or :meth:`stop` was called.
"""
counter = 0
while True:
logger.debug('optimization loop #{}'.format(counter))
if not self.process_step():
break
if self._stop_event.wait(timeout=self.pool_period_minutes * 60.):
break
counter += 1
def stop(self):
# type: () -> ()
"""
Stop the current running optimization loop. Called from a different thread than the :meth:`start`.
"""
self._stop_event.set()
def process_step(self):
# type: () -> bool
"""
Abstract helper function. Implementation is not required. Default use in start default implementation
Main optimization loop, called from the daemon thread created by :meth:`start`.
- Call monitor job on every ``TrainsJob`` in jobs:
- Check the performance or elapsed time, and then decide whether to kill the jobs.
- Call create_job:
- Check if spare job slots exist, and if they do call create a new job based on previous tested experiments.
:return: True, if continue the optimization. False, if immediately stop.
"""
updated_jobs = []
for job in self._current_jobs:
if self.monitor_job(job):
updated_jobs.append(job)
self._current_jobs = updated_jobs
pending_jobs = []
for job in self._pending_jobs:
if job.is_pending():
pending_jobs.append(job)
else:
self.budget.jobs.update(job.task_id(), 1)
self._pending_jobs = pending_jobs
free_workers = self._num_concurrent_workers - len(self._current_jobs)
# do not create more jobs if we hit the limit
if self.total_max_jobs and self._num_jobs >= self.total_max_jobs:
return bool(self._current_jobs)
# see how many free slots we have and create job
for i in range(max(0, free_workers)):
new_job = self.create_job()
if not new_job:
break
self._num_jobs += 1
new_job.launch(self._execution_queue)
self._current_jobs.append(new_job)
self._pending_jobs.append(new_job)
return bool(self._current_jobs)
def create_job(self):
# type: () -> Optional[TrainsJob]
"""
Abstract helper function. Implementation is not required. Default use in process_step default implementation
Create a new job if needed. return the newly created job. If no job needs to be created, return ``None``.
:return: A Newly created TrainsJob object, or None if no TrainsJob created.
"""
return None
def monitor_job(self, job):
# type: (TrainsJob) -> bool
"""
Helper function, Implementation is not required. Default use in process_step default implementation.
Check if the job needs to be aborted or already completed.
If returns ``False``, the job was aborted / completed, and should be taken off the current job list
If there is a budget limitation, this call should update
``self.budget.compute_time.update`` / ``self.budget.iterations.update``
:param TrainsJob job: A ``TrainsJob`` object to monitor.
:return: False, if the job is no longer relevant.
"""
abort_job = False
if self.time_limit_per_job:
elapsed = job.elapsed() / 60.
if elapsed > 0:
self.budget.compute_time.update(job.task_id(), elapsed)
if elapsed > self.time_limit_per_job:
abort_job = True
if self.max_iteration_per_job:
iterations = self._get_job_iterations(job)
if iterations > 0:
self.budget.iterations.update(job.task_id(), iterations)
if iterations > self.max_iteration_per_job:
abort_job = True
if abort_job:
job.abort()
return False
return not job.is_stopped()
def get_running_jobs(self):
# type: () -> Sequence[TrainsJob]
"""
Return the current running TrainsJobs.
:return: List of TrainsJob objects.
"""
return self._current_jobs
def get_created_jobs_ids(self):
# type: () -> Mapping[str, dict]
"""
Return a Task IDs dict created by this optimizer until now, including completed and running jobs.
The values of the returned dict are the parameters used in the specific job
:return: dict of task IDs (str) as keys, and their parameters dict as values.
"""
return self._created_jobs_ids
def get_top_experiments(self, top_k):
# type: (int) -> Sequence[Task]
"""
Return a list of Tasks of the top performing experiments, based on the controller ``Objective`` object.
:param int top_k: The number of Tasks (experiments) to return.
:return: A list of Task objects, ordered by performance, where index 0 is the best performing Task.
"""
# noinspection PyProtectedMember
top_tasks = self._get_child_tasks(
parent_task_id=self._job_parent_id or self._base_task_id,
order_by=self._objective_metric._get_last_metrics_encode_field(),
additional_filters={'page_size': int(top_k), 'page': 0})
return top_tasks
def get_objective_metric(self):
# type: () -> (str, str)
"""
Return the metric title, series pair of the objective.
:return: (title, series)
"""
return self._objective_metric.get_objective_metric()
def helper_create_job(
self,
base_task_id, # type: str
parameter_override=None, # type: Optional[Mapping[str, str]]
task_overrides=None, # type: Optional[Mapping[str, str]]
tags=None, # type: Optional[Sequence[str]]
parent=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> TrainsJob
"""
Create a Job using the specified arguments, ``TrainsJob`` for details.
:return: A newly created Job instance.
"""
if parameter_override:
param_str = ['{}={}'.format(k, parameter_override[k]) for k in sorted(parameter_override.keys())]
if self._naming_function:
name = self._naming_function(self._base_task_name, parameter_override)
elif self._naming_function is False:
name = None
else:
name = '{}: {}'.format(self._base_task_name, ' '.join(param_str))
comment = '\n'.join(param_str)
else:
name = None
comment = None
tags = (tags or []) + [self._tag, 'opt' + (': {}'.format(self._job_parent_id) if self._job_parent_id else '')]
new_job = self._job_class(
base_task_id=base_task_id, parameter_override=parameter_override,
task_overrides=task_overrides, tags=tags, parent=parent or self._job_parent_id,
name=name, comment=comment, project=self._get_task_project(parent or self._job_parent_id), **kwargs)
self._created_jobs_ids[new_job.task_id()] = parameter_override
logger.info('Creating new Task: {}'.format(parameter_override))
return new_job
def set_job_class(self, job_class):
# type: (TrainsJob) -> ()
"""
Set the class to use for the :meth:`helper_create_job` function.
:param TrainsJob job_class: The Job Class type.
"""
self._job_class = job_class
def set_job_default_parent(self, job_parent_task_id):
# type: (str) -> ()
"""
Set the default parent for all Jobs created by the :meth:`helper_create_job` method.
:param str job_parent_task_id: The parent Task ID.
"""
self._job_parent_id = job_parent_task_id
def set_job_naming_scheme(self, naming_function):
# type: (Optional[Callable[[str, dict], str]]) -> ()
"""
Set the function used to name a newly created job.
:param callable naming_function:
.. code-block:: py
naming_functor(base_task_name, argument_dict) -> str
"""
self._naming_function = naming_function
def set_optimizer_task(self, task):
# type: (Task) -> ()
"""
Set the optimizer task object to be used to store/generate reports on the optimization process.
Usually this is the current task of this process.
:param Task task: The optimizer's current Task.
"""
self._optimizer_task = task
def _validate_base_task(self):
# type: () -> ()
"""
Check the base task exists and contains the requested Objective metric and hyper parameters.
"""
# check if the task exists
try:
task = Task.get_task(task_id=self._base_task_id)
self._base_task_name = task.name
except ValueError:
raise ValueError("Could not find base task id {}".format(self._base_task_id))
# check if the hyper-parameters exist:
task_parameters = task.get_parameters_as_dict()
missing_params = [h.name for h in self._hyper_parameters if h.name not in task_parameters]
if missing_params:
logger.warning('Could not find requested hyper-parameters {} on base task {}'.format(
missing_params, self._base_task_id))
# check if the objective metric exists (i.e. no typos etc)
if self._objective_metric.get_objective(self._base_task_id) is None:
logger.warning('Could not find requested metric {} report on base task {}'.format(
self._objective_metric.get_objective_metric(), self._base_task_id))
def _get_task_project(self, parent_task_id):
# type: (str) -> (Optional[str])
if not parent_task_id:
return
if parent_task_id not in self._job_project:
task = Task.get_task(task_id=parent_task_id)
self._job_project[parent_task_id] = task.project
return self._job_project.get(parent_task_id)
def _get_job_iterations(self, job):
# type: (Union[TrainsJob, Task]) -> int
iteration_value = self._objective_metric.get_current_raw_objective(job)
return iteration_value[0] if iteration_value else -1
@classmethod
def _get_child_tasks(
cls,
parent_task_id, # type: str
status=None, # type: Optional[Task.TaskStatusEnum]
order_by=None, # type: Optional[str]
additional_filters=None # type: Optional[dict]
):
# type: (...) -> (Sequence[Task])
"""
Helper function. Return a list of tasks tagged automl, with specific ``status``, ordered by ``sort_field``.
:param str parent_task_id: The base Task ID (parent).
:param status: The current status of requested tasks (for example, ``in_progress`` and ``completed``).
:param str order_by: The field name to sort results.
Examples:
.. code-block:: py
"-last_metrics.title.series.min"
"last_metrics.title.series.max"
"last_metrics.title.series.last"
"execution.parameters.name"
"updated"
:param dict additional_filters: The additional task filters.
:return: A list of Task objects
"""
task_filter = {'parent': parent_task_id,
# 'tags': [cls._tag],
'system_tags': ['-archived']}
task_filter.update(additional_filters or {})
if status:
task_filter['status'] = status
if order_by and (order_by.startswith('last_metrics') or order_by.startswith('-last_metrics')):
parts = order_by.split('.')
if parts[-1] in ('min', 'max', 'last'):
title = hashlib.md5(str(parts[1]).encode('utf-8')).hexdigest()
series = hashlib.md5(str(parts[2]).encode('utf-8')).hexdigest()
minmax = 'min_value' if 'min' in parts[3] else ('max_value' if 'max' in parts[3] else 'value')
order_by = '{}last_metrics.'.join(
('-' if order_by and order_by[0] == '-' else '', title, series, minmax))
if order_by:
task_filter['order_by'] = [order_by]
return Task.get_tasks(task_filter=task_filter)
class GridSearch(SearchStrategy):
"""
Grid search strategy controller. Full grid sampling of every hyper-parameter combination.
"""
def __init__(
self,
base_task_id, # type: str
hyper_parameters, # type: Sequence[Parameter]
objective_metric, # type: Objective
execution_queue, # type: str
num_concurrent_workers, # type: int
pool_period_min=2., # type: float
time_limit_per_job=None, # type: Optional[float]
max_iteration_per_job=None, # type: Optional[int]
total_max_jobs=None, # type: Optional[int]
**_ # type: Any
):
# type: (...) -> ()
"""
Initialize a grid search optimizer
:param str base_task_id: The Task ID.
:param list hyper_parameters: The list of parameter objects to optimize over.
:param Objective objective_metric: The Objective metric to maximize / minimize.
:param str execution_queue: The execution queue to use for launching Tasks (experiments).
:param int num_concurrent_workers: The maximum number of concurrent running machines.
:param float pool_period_min: The time between two consecutive pools (minutes).
:param float time_limit_per_job: The maximum execution time per single job in minutes. When the time limit is
exceeded job is aborted. (Optional)
:param int max_iteration_per_job: The maximum iterations (of the Objective metric)
per single job, When exceeded, the job is aborted.
:param int total_max_jobs: The total maximum jobs for the optimization process. The default is ``None``, for
unlimited.
"""
super(GridSearch, self).__init__(
base_task_id=base_task_id, hyper_parameters=hyper_parameters, objective_metric=objective_metric,
execution_queue=execution_queue, num_concurrent_workers=num_concurrent_workers,
pool_period_min=pool_period_min, time_limit_per_job=time_limit_per_job,
max_iteration_per_job=max_iteration_per_job, total_max_jobs=total_max_jobs, **_)
self._param_iterator = None
def create_job(self):
# type: () -> Optional[TrainsJob]
"""
Create a new job if needed. Return the newly created job. If no job needs to be created, return ``None``.
:return: A newly created TrainsJob object, or None if no TrainsJob is created.
"""
try:
parameters = self._next_configuration()
except StopIteration:
return None
return self.helper_create_job(base_task_id=self._base_task_id, parameter_override=parameters)
def _next_configuration(self):
# type: () -> Mapping[str, str]
def param_iterator_fn():
hyper_params_values = [p.to_list() for p in self._hyper_parameters]
for state in product(*hyper_params_values):
yield dict(kv for d in state for kv in d.items())
if not self._param_iterator:
self._param_iterator = param_iterator_fn()
return next(self._param_iterator)
class RandomSearch(SearchStrategy):
"""
Random search strategy controller. Random uniform sampling of hyper-parameters.
"""
# Number of already chosen random samples before assuming we covered the entire hyper-parameter space
_hp_space_cover_samples = 42
def __init__(
self,
base_task_id, # type: str
hyper_parameters, # type: Sequence[Parameter]
objective_metric, # type: Objective
execution_queue, # type: str
num_concurrent_workers, # type: int
pool_period_min=2., # type: float
time_limit_per_job=None, # type: Optional[float]
max_iteration_per_job=None, # type: Optional[int]
total_max_jobs=None, # type: Optional[int]
**_ # type: Any
):
# type: (...) -> ()
"""
Initialize a random search optimizer.
:param str base_task_id: The Task ID.
:param list hyper_parameters: The list of Parameter objects to optimize over.
:param Objective objective_metric: The Objective metric to maximize / minimize.
:param str execution_queue: The execution queue to use for launching Tasks (experiments).
:param int num_concurrent_workers: The maximum umber of concurrent running machines.
:param float pool_period_min: The time between two consecutive pools (minutes).
:param float time_limit_per_job: The maximum execution time per single job in minutes,
when time limit is exceeded job is aborted. (Optional)
:param int max_iteration_per_job: The maximum iterations (of the Objective metric)
per single job. When exceeded, the job is aborted.
:param int total_max_jobs: The total maximum jobs for the optimization process. The default is ``None``, for
unlimited.
"""
super(RandomSearch, self).__init__(
base_task_id=base_task_id, hyper_parameters=hyper_parameters, objective_metric=objective_metric,
execution_queue=execution_queue, num_concurrent_workers=num_concurrent_workers,
pool_period_min=pool_period_min, time_limit_per_job=time_limit_per_job,
max_iteration_per_job=max_iteration_per_job, total_max_jobs=total_max_jobs, **_)
self._hyper_parameters_collection = set()
def create_job(self):
# type: () -> Optional[TrainsJob]
"""
Create a new job if needed. Return the newly created job. If no job needs to be created, return ``None``.
:return: A newly created TrainsJob object, or None if no TrainsJob created
"""
parameters = None
# maximum tries to ge a random set that is not already in the collection
for i in range(self._hp_space_cover_samples):
parameters = {}
for p in self._hyper_parameters:
parameters.update(p.get_value())
# hash the parameters dictionary
param_hash = hash(json.dumps(parameters, sort_keys=True))
# if this is a new set of parameters, use it.
if param_hash not in self._hyper_parameters_collection:
self._hyper_parameters_collection.add(param_hash)
break
# try again
parameters = None
# if we failed to find a random set of parameters, assume we selected all of them
if not parameters:
return None
return self.helper_create_job(base_task_id=self._base_task_id, parameter_override=parameters)
class HyperParameterOptimizer(object):
"""
Hyper-parameter search controller. Clones the base experiment, changes arguments and tries to maximize/minimize
the defined objective.
"""
_tag = 'optimization'
def __init__(
self,
base_task_id, # type: str
hyper_parameters, # type: Sequence[Parameter]
objective_metric_title, # type: str
objective_metric_series, # type: str
objective_metric_sign='min', # type: str
optimizer_class=RandomSearch, # type: type(SearchStrategy)
max_number_of_concurrent_tasks=10, # type: int
execution_queue='default', # type: str
optimization_time_limit=None, # type: Optional[float]
auto_connect_task=True, # type: bool
always_create_task=False, # type: bool
**optimizer_kwargs # type: Any
):
# type: (...) -> ()
"""
Create a new hyper-parameter controller. The newly created object will launch and monitor the new experiments.
:param str base_task_id: The Task ID to be used as template experiment to optimize.
:param list hyper_parameters: The list of Parameter objects to optimize over.
:param str objective_metric_title: The Objective metric title to maximize / minimize (for example,
``validation``).
:param str objective_metric_series: The Objective metric series to maximize / minimize (for example, ``loss``).
:param str objective_metric_sign: The objective to maximize / minimize.
The values are:
- ``min`` - Minimize the last reported value for the specified title/series scalar.
- ``max`` - Maximize the last reported value for the specified title/series scalar.
- ``min_global`` - Minimize the min value of *all* reported values for the specific title/series scalar.
- ``max_global`` - Maximize the max value of *all* reported values for the specific title/series scalar.
:param class.SearchStrategy optimizer_class: The SearchStrategy optimizer to use for the hyper-parameter search
:param int max_number_of_concurrent_tasks: The maximum number of concurrent Tasks (experiments) running at the
same time.
:param str execution_queue: The execution queue to use for launching Tasks (experiments).
:param float optimization_time_limit: The maximum time (minutes) for the entire optimization process. The
default is ``None``, indicating no time limit.
:param bool auto_connect_task: Store optimization arguments and configuration in the Task?
The values are:
- ``True`` - The optimization argument and configuration will be stored in the Task. All arguments will
be under the hyper-parameter section as ``opt/<arg>``, and the hyper_parameters will stored in the
Task ``connect_configuration`` (see artifacts/hyper-parameter).
- ``False`` - Do not store with Task.
:param bool always_create_task: Always create a new Task?
The values are:
- ``True`` - No current Task initialized. Create a new task named ``optimization`` in the ``base_task_id``
project.
- ``False`` - Use the :py:meth:`task.Task.current_task` (if exists) to report statistics.
:param ** optimizer_kwargs: Arguments passed directly to the optimizer constructor.
Example:
.. code-block:: py
:linenos:
:caption: Example
from trains import Task
from trains.automation import UniformParameterRange, DiscreteParameterRange
from trains.automation import GridSearch, RandomSearch, HyperParameterOptimizer
task = Task.init('examples', 'HyperParameterOptimizer example')
an_optimizer = HyperParameterOptimizer(
base_task_id='fa30fa45d95d4927b87c323b5b04dc44',
hyper_parameters=[
UniformParameterRange('lr', min_value=0.01, max_value=0.3, step_size=0.05),
DiscreteParameterRange('network', values=['ResNet18', 'ResNet50', 'ResNet101']),
],
objective_metric_title='title',
objective_metric_series='series',
objective_metric_sign='min',
max_number_of_concurrent_tasks=5,
optimizer_class=RandomSearch,
execution_queue='workers', time_limit_per_job=120, pool_period_min=0.2)
# This will automatically create and print the optimizer new task id
# for later use. if a Task was already created, it will use it.
an_optimizer.set_time_limit(in_minutes=10.)
an_optimizer.start()
# we can create a pooling loop if we like
while not an_optimizer.reached_time_limit():
top_exp = an_optimizer.get_top_experiments(top_k=3)
print(top_exp)
# wait until optimization completed or timed-out
an_optimizer.wait()
# make sure we stop all jobs
an_optimizer.stop()
"""
# create a new Task, if we do not have one already
self._task = Task.current_task()
if not self._task and always_create_task:
base_task = Task.get_task(task_id=self.base_task_id)
self._task = Task.init(
project_name=base_task.get_project_name(),
task_name='Optimizing: {}'.format(base_task.name),
) # TODO: add task_type=controller
opts = dict(
base_task_id=base_task_id,
objective_metric_title=objective_metric_title,
objective_metric_series=objective_metric_series,
objective_metric_sign=objective_metric_sign,
max_number_of_concurrent_tasks=max_number_of_concurrent_tasks,
execution_queue=execution_queue,
optimization_time_limit=optimization_time_limit,
optimizer_kwargs=optimizer_kwargs)
# make sure all the created tasks are our children, as we are creating them
if self._task:
self._task.add_tags([self._tag])
if auto_connect_task:
optimizer_class, hyper_parameters, opts = self._connect_args(
optimizer_class=optimizer_class, hyper_param_configuration=hyper_parameters, **opts)
self.base_task_id = opts['base_task_id']
self.hyper_parameters = hyper_parameters
self.max_number_of_concurrent_tasks = opts['max_number_of_concurrent_tasks']
self.execution_queue = opts['execution_queue']
self.objective_metric = Objective(
title=opts['objective_metric_title'], series=opts['objective_metric_series'],
order='min' if opts['objective_metric_sign'] in ('min', 'min_global') else 'max',
extremum=opts['objective_metric_sign'].endswith('_global'))
# if optimizer_class is an instance, use it as is.
if type(optimizer_class) != type:
self.optimizer = optimizer_class
else:
self.optimizer = optimizer_class(
base_task_id=opts['base_task_id'], hyper_parameters=hyper_parameters,
objective_metric=self.objective_metric, execution_queue=opts['execution_queue'],
num_concurrent_workers=opts['max_number_of_concurrent_tasks'], **opts.get('optimizer_kwargs', {}))
self.optimizer.set_optimizer_task(self._task)
self.optimization_timeout = None
self.optimization_start_time = None
self._thread = None
self._stop_event = None
self._report_period_min = 5.
self._thread_reporter = None
self._experiment_completed_cb = None
if self._task:
self.optimizer.set_job_default_parent(self._task.id)
self.set_time_limit(in_minutes=opts['optimization_time_limit'])
def get_num_active_experiments(self):
# type: () -> int
"""
Return the number of current active experiments.
:return: The number of active experiments.
"""
if not self.optimizer:
return 0
return len(self.optimizer.get_running_jobs())
def get_active_experiments(self):
# type: () -> Sequence[Task]
"""
Return a list of Tasks of the current active experiments.
:return: A list of Task objects, representing the current active experiments.
"""
if not self.optimizer:
return []
return [j.task for j in self.optimizer.get_running_jobs()]
def start(self, job_complete_callback=None):
# type: (Optional[Callable[[str, float, int, dict, str], None]]) -> bool
"""
Start the HyperParameterOptimizer controller. If the calling process is stopped, then the controller stops
as well.
:param Callable job_complete_callback: Callback function, called when a job is completed.
.. code-block:: py
def job_complete_callback(
job_id, # type: str
objective_value, # type: float
objective_iteration, # type: int
job_parameters, # type: dict
top_performance_job_id # type: str
):
pass
:return: True, if the controller started. False, if the controller did not start.
"""
if not self.optimizer:
return False
if self._thread:
return True
self.optimization_start_time = time()
self._experiment_completed_cb = job_complete_callback
self._stop_event = Event()
self._thread = Thread(target=self._daemon)
self._thread.daemon = True
self._thread.start()
self._thread_reporter = Thread(target=self._report_daemon)
self._thread_reporter.daemon = True
self._thread_reporter.start()
return True
def stop(self, timeout=None):
# type: (Optional[float]) -> ()
"""
Stop the HyperParameterOptimizer controller and the optimization thread.
:param float timeout: Wait timeout for the optimization thread to exit (minutes).
The default is ``None``, indicating do not wait terminate immediately.
"""
if not self._thread or not self._stop_event or not self.optimizer:
return
_thread = self._thread
self._stop_event.set()
self.optimizer.stop()
# wait for optimizer thread
if timeout is not None:
_thread.join(timeout=timeout * 60.)
# stop all running tasks:
for j in self.optimizer.get_running_jobs():
j.abort()
# clear thread
self._thread = None
# wait for reporter to flush
self._thread_reporter.join()
def is_active(self):
# type: () -> bool
"""
Is the optimization procedure active (still running)?
The values are:
- ``True`` - The optimization procedure is active (still running).
- ``False`` - The optimization procedure is not active (not still running).
.. note::
If the daemon thread has not yet started, ``is_active`` returns ``True``.
:return: A boolean indicating whether the optimization procedure is active (still running) or stopped.
"""
return self._stop_event is None or self._thread is not None
def is_running(self):
# type: () -> bool
"""
Is the optimization controller is running?
The values are:
- ``True`` - The optimization procedure is running.
- ``False`` - The optimization procedure is running.
:return: A boolean indicating whether the optimization procedure is active (still running) or stopped.
"""
return self._thread is not None
def wait(self, timeout=None):
# type: (Optional[float]) -> bool
"""
Wait for the optimizer to finish.
.. note::
This method does not stop the optimizer. Call :meth:`stop` to terminate the optimizer.
:param float timeout: The timeout to wait for the optimization to complete (minutes).
If ``None``, then wait until we reached the timeout, or optimization completed.
:return: True, if the optimization finished. False, if the optimization timed out.
"""
if not self.is_running():
return True
if timeout is not None:
timeout *= 60.
else:
timeout = max(0, self.optimization_timeout - self.optimization_start_time) \
if self.optimization_timeout else None
_thread = self._thread
_thread.join(timeout=timeout)
if _thread.is_alive():
return False
return True
def set_time_limit(self, in_minutes=None, specific_time=None):
# type: (Optional[float], Optional[datetime]) -> ()
"""
Set a time limit for the HyperParameterOptimizer controller. If we reached the time limit, stop the optimization
process. If ``specific_time`` is provided, use it; otherwise, use the ``in_minutes``.
:param float in_minutes: The maximum processing time from current time (minutes).
:param datetime specific_time: The specific date/time limit.
"""
if specific_time:
self.optimization_timeout = specific_time.timestamp()
else:
self.optimization_timeout = (float(in_minutes) * 60.) + time() if in_minutes else None
def get_time_limit(self):
# type: () -> datetime
"""
Return the controller optimization time limit.
:return: The absolute datetime limit of the controller optimization process.
"""
return datetime.fromtimestamp(self.optimization_timeout)
def elapsed(self):
# type: () -> float
"""
Return minutes elapsed from controller stating time stamp.
:return: The minutes from controller start time. A negative value means the process has not started yet.
"""
if self.optimization_start_time is None:
return -1.0
return (time() - self.optimization_start_time) / 60.
def reached_time_limit(self):
# type: () -> bool
"""
Did the optimizer reach the time limit?
The values are:
- ``True`` - The time limit passed.
- ``False`` - The time limit did not pass.
This method returns immediately, it does not wait for the optimizer.
:return: True, if optimizer is running and we passed the time limit, otherwise returns False.
"""
if self.optimization_start_time is None:
return False
if not self.is_running():
return False
return time() > self.optimization_timeout
def get_top_experiments(self, top_k):
# type: (int) -> Sequence[Task]
"""
Return a list of Tasks of the top performing experiments, based on the controller ``Objective`` object.
:param int top_k: The number of Tasks (experiments) to return.
:return: A list of Task objects, ordered by performance, where index 0 is the best performing Task.
"""
if not self.optimizer:
return []
return self.optimizer.get_top_experiments(top_k=top_k)
def get_optimizer(self):
# type: () -> SearchStrategy
"""
Return the currently used optimizer object.
:return: The SearchStrategy object used.
"""
return self.optimizer
def set_default_job_class(self, job_class):
# type: (TrainsJob) -> ()
"""
Set the Job class to use when the optimizer spawns new Jobs.
:param TrainsJob job_class: The Job Class type.
"""
self.optimizer.set_job_class(job_class)
def set_report_period(self, report_period_minutes):
# type: (float) -> ()
"""
Set reporting period for the accumulated objective report (minutes). This report is sent on the Optimizer Task,
and collects the Objective metric from all running jobs.
:param float report_period_minutes: The reporting period (minutes). The default is once every 10 minutes.
"""
self._report_period_min = float(report_period_minutes)
def _connect_args(self, optimizer_class=None, hyper_param_configuration=None, **kwargs):
# type: (SearchStrategy, dict, Any) -> (SearchStrategy, list, dict)
if not self._task:
logger.warning('Auto Connect turned on but no Task was found, '
'hyper-parameter optimization argument logging disabled')
return optimizer_class, hyper_param_configuration, kwargs
configuration_dict = {'parameter_optimization_space': [c.to_dict() for c in hyper_param_configuration]}
self._task.connect_configuration(configuration_dict)
# this is the conversion back magic:
configuration_dict = {'parameter_optimization_space': [
Parameter.from_dict(c) for c in configuration_dict['parameter_optimization_space']]}
arguments = {'opt': kwargs}
if type(optimizer_class) != type:
logger.warning('Auto Connect optimizer_class disabled, {} is already instantiated'.format(optimizer_class))
self._task.connect(arguments)
else:
arguments['opt']['optimizer_class'] = str(optimizer_class).split('.')[-1][:-2] \
if not isinstance(optimizer_class, str) else optimizer_class
self._task.connect(arguments)
# this is the conversion back magic:
original_class = optimizer_class
optimizer_class = arguments['opt'].pop('optimizer_class', None)
if optimizer_class == 'RandomSearch':
optimizer_class = RandomSearch
elif optimizer_class == 'GridSearch':
optimizer_class = GridSearch
elif optimizer_class == 'OptimizerBOHB':
from .hpbandster import OptimizerBOHB
optimizer_class = OptimizerBOHB
elif optimizer_class == 'OptimizerOptuna':
from .optuna import OptimizerOptuna
optimizer_class = OptimizerOptuna
else:
logger.warning("Could not resolve optimizer_class {} reverting to original class {}".format(
optimizer_class, original_class))
optimizer_class = original_class
return optimizer_class, configuration_dict['parameter_optimization_space'], arguments['opt']
def _daemon(self):
# type: () -> ()
"""
Implement the main pooling thread, calling loop every ``self.pool_period_minutes`` minutes.
"""
self.optimizer.start()
self._thread = None
def _report_daemon(self):
# type: () -> ()
worker_to_series = {}
title, series = self.objective_metric.get_objective_metric()
title = '{}/{}'.format(title, series)
series = 'machine:'
counter = 0
completed_jobs = dict()
best_experiment = float('-inf'), None
while self._thread is not None:
timeout = self.optimization_timeout - time() if self.optimization_timeout else 0.
if timeout >= 0:
timeout = min(self._report_period_min * 60., timeout if timeout else self._report_period_min * 60.)
# make sure that we have the first report fired before we actually go to sleep, wait for 15 sec.
if counter <= 0:
timeout = 15
print('Progress report #{} completed, sleeping for {} minutes'.format(counter, timeout / 60.))
if self._stop_event.wait(timeout=timeout):
# wait for one last report
timeout = -1
counter += 1
# get task to report on.
if self._task or Task.current_task():
task_logger = (self._task or Task.current_task()).get_logger()
# do some reporting
# running objective, per machine
running_job_ids = set()
for j in self.optimizer.get_running_jobs():
worker = j.worker()
running_job_ids.add(j.task_id())
if worker not in worker_to_series:
worker_to_series[worker] = len(worker_to_series) + 1
machine_id = worker_to_series[worker]
value = self.objective_metric.get_objective(j)
if value is not None:
task_logger.report_scalar(
title=title, series='{}{}'.format(series, machine_id),
iteration=counter, value=value)
# noinspection PyBroadException
try:
budget = self.optimizer.budget.to_dict()
except Exception:
budget = {}
# report remaining budget
for budget_part, value in budget.items():
task_logger.report_scalar(
title='remaining budget', series='{} %'.format(budget_part),
iteration=counter, value=round(100 - value['used'] * 100., ndigits=1))
if self.optimization_timeout and self.optimization_start_time:
task_logger.report_scalar(
title='remaining budget', series='time %',
iteration=counter,
value=round(100 - (100. * (time() - self.optimization_start_time) /
(self.optimization_timeout - self.optimization_start_time)), ndigits=1)
)
# collect a summary of all the jobs and their final objective values
cur_completed_jobs = set(self.optimizer.get_created_jobs_ids().keys()) - running_job_ids
if cur_completed_jobs != set(completed_jobs.keys()):
pairs = []
labels = []
created_jobs = copy(self.optimizer.get_created_jobs_ids())
for i, (job_id, params) in enumerate(created_jobs.items()):
if job_id in completed_jobs:
pairs.append((i, completed_jobs[job_id][0]))
labels.append(str(completed_jobs[job_id][2])[1:-1])
else:
value = self.objective_metric.get_objective(job_id)
if value is not None:
pairs.append((i, value))
labels.append(str(params)[1:-1])
iteration_value = self.objective_metric.get_current_raw_objective(job_id)
completed_jobs[job_id] = (
value, iteration_value[0] if iteration_value else -1, copy(params))
# callback new experiment completed
if self._experiment_completed_cb:
normalized_value = self.objective_metric.get_normalized_objective(job_id)
if normalized_value is not None and normalized_value > best_experiment[0]:
best_experiment = normalized_value, job_id
c = completed_jobs[job_id]
self._experiment_completed_cb(job_id, c[0], c[1], c[2], best_experiment[1])
if pairs:
print('Updating job performance summary plot/table')
# update scatter plot
task_logger.report_scatter2d(
title='optimization', series=title,
scatter=pairs, iteration=0, labels=labels,
mode='markers', xaxis='job #', yaxis='objective')
# update summary table
if pd:
index = list(completed_jobs.keys())
table = {'objective': [completed_jobs[i][0] for i in index],
'iteration': [completed_jobs[i][1] for i in index]}
columns = set([c for k, v in completed_jobs.items() for c in v[2].keys()])
for c in sorted(columns):
table.update({c: [completed_jobs[i][2].get(c, '') for i in index]})
df = pd.DataFrame(table, index=index)
df.sort_values(by='objective', ascending=bool(self.objective_metric.sign < 0), inplace=True)
df.index.name = 'task id'
task_logger.report_table(
"summary", "job", 0, table_plot=df,
extra_layout={"title": "objective: {}".format(title)})
# if we should leave, stop everything now.
if timeout < 0:
# we should leave
self.stop()
return
|
tests.py | # -*- coding: utf-8 -*-
"""
gns3-proxy
GNS3 Proxy Server in Python.
based on proxy.py - HTTP Proxy Server in Python - copyright: (c) 2013-2018 by Abhinav Singh
:copyright: (c) 2020 by Sebastian Rieger.
:license: BSD, see LICENSE for more details.
"""
import sys
import base64
import socket
import logging
import unittest
from threading import Thread
from contextlib import closing
from gns3_proxy import Proxy, ChunkParser, HttpParser, Client
from gns3_proxy import ProxyAuthenticationFailed, ProxyConnectionFailed
from gns3_proxy import CRLF, version, PROXY_TUNNEL_ESTABLISHED_RESPONSE_PKT
# logging.basicConfig(level=logging.DEBUG,
# format='%(asctime)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s')
# True if we are running on Python 3.
if sys.version_info[0] == 3:
from http.server import HTTPServer, BaseHTTPRequestHandler
else:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class TestChunkParser(unittest.TestCase):
def setUp(self):
self.parser = ChunkParser()
def test_chunk_parse_basic(self):
self.parser.parse(b''.join([
b'4\r\n',
b'Wiki\r\n',
b'5\r\n',
b'pedia\r\n',
b'E\r\n',
b' in\r\n\r\nchunks.\r\n',
b'0\r\n',
b'\r\n'
]))
self.assertEqual(self.parser.chunk, b'')
self.assertEqual(self.parser.size, None)
self.assertEqual(self.parser.body, b'Wikipedia in\r\n\r\nchunks.')
self.assertEqual(self.parser.state, ChunkParser.states.COMPLETE)
def test_chunk_parse_issue_27(self):
"""Case when data ends with the chunk size but without CRLF."""
self.parser.parse(b'3')
self.assertEqual(self.parser.chunk, b'3')
self.assertEqual(self.parser.size, None)
self.assertEqual(self.parser.body, b'')
self.assertEqual(self.parser.state, ChunkParser.states.WAITING_FOR_SIZE)
self.parser.parse(b'\r\n')
self.assertEqual(self.parser.chunk, b'')
self.assertEqual(self.parser.size, 3)
self.assertEqual(self.parser.body, b'')
self.assertEqual(self.parser.state, ChunkParser.states.WAITING_FOR_DATA)
self.parser.parse(b'abc')
self.assertEqual(self.parser.chunk, b'')
self.assertEqual(self.parser.size, None)
self.assertEqual(self.parser.body, b'abc')
self.assertEqual(self.parser.state, ChunkParser.states.WAITING_FOR_SIZE)
self.parser.parse(b'\r\n')
self.assertEqual(self.parser.chunk, b'')
self.assertEqual(self.parser.size, None)
self.assertEqual(self.parser.body, b'abc')
self.assertEqual(self.parser.state, ChunkParser.states.WAITING_FOR_SIZE)
self.parser.parse(b'4\r\n')
self.assertEqual(self.parser.chunk, b'')
self.assertEqual(self.parser.size, 4)
self.assertEqual(self.parser.body, b'abc')
self.assertEqual(self.parser.state, ChunkParser.states.WAITING_FOR_DATA)
self.parser.parse(b'defg\r\n0')
self.assertEqual(self.parser.chunk, b'0')
self.assertEqual(self.parser.size, None)
self.assertEqual(self.parser.body, b'abcdefg')
self.assertEqual(self.parser.state, ChunkParser.states.WAITING_FOR_SIZE)
self.parser.parse(b'\r\n\r\n')
self.assertEqual(self.parser.chunk, b'')
self.assertEqual(self.parser.size, None)
self.assertEqual(self.parser.body, b'abcdefg')
self.assertEqual(self.parser.state, ChunkParser.states.COMPLETE)
class TestHttpParser(unittest.TestCase):
def setUp(self):
self.parser = HttpParser(HttpParser.types.REQUEST_PARSER)
def test_build_header(self):
self.assertEqual(HttpParser.build_header(b'key', b'value'), b'key: value')
def test_split(self):
self.assertEqual(HttpParser.split(b'CONNECT python.org:443 HTTP/1.0\r\n\r\n'),
(b'CONNECT python.org:443 HTTP/1.0', b'\r\n'))
def test_split_false_line(self):
self.assertEqual(HttpParser.split(b'CONNECT python.org:443 HTTP/1.0'),
(False, b'CONNECT python.org:443 HTTP/1.0'))
def test_get_full_parse(self):
raw = CRLF.join([
b'GET %s HTTP/1.1',
b'Host: %s',
CRLF
])
self.parser.parse(raw % (b'https://example.com/path/dir/?a=b&c=d#p=q', b'example.com'))
self.assertEqual(self.parser.build_url(), b'/path/dir/?a=b&c=d#p=q')
self.assertEqual(self.parser.method, b'GET')
self.assertEqual(self.parser.url.hostname, b'example.com')
self.assertEqual(self.parser.url.port, None)
self.assertEqual(self.parser.version, b'HTTP/1.1')
self.assertEqual(self.parser.state, HttpParser.states.COMPLETE)
self.assertDictContainsSubset({b'host': (b'Host', b'example.com')}, self.parser.headers)
self.assertEqual(raw % (b'/path/dir/?a=b&c=d#p=q', b'example.com'),
self.parser.build(del_headers=[b'host'], add_headers=[(b'Host', b'example.com')]))
def test_build_url_none(self):
self.assertEqual(self.parser.build_url(), b'/None')
def test_line_rcvd_to_rcving_headers_state_change(self):
self.parser.parse(b'GET http://localhost HTTP/1.1')
self.assertEqual(self.parser.state, HttpParser.states.INITIALIZED)
self.parser.parse(CRLF)
self.assertEqual(self.parser.state, HttpParser.states.LINE_RCVD)
self.parser.parse(CRLF)
self.assertEqual(self.parser.state, HttpParser.states.RCVING_HEADERS)
def test_get_partial_parse1(self):
self.parser.parse(CRLF.join([
b'GET http://localhost:8080 HTTP/1.1'
]))
self.assertEqual(self.parser.method, None)
self.assertEqual(self.parser.url, None)
self.assertEqual(self.parser.version, None)
self.assertEqual(self.parser.state, HttpParser.states.INITIALIZED)
self.parser.parse(CRLF)
self.assertEqual(self.parser.method, b'GET')
self.assertEqual(self.parser.url.hostname, b'localhost')
self.assertEqual(self.parser.url.port, 8080)
self.assertEqual(self.parser.version, b'HTTP/1.1')
self.assertEqual(self.parser.state, HttpParser.states.LINE_RCVD)
self.parser.parse(b'Host: localhost:8080')
self.assertDictEqual(self.parser.headers, dict())
self.assertEqual(self.parser.buffer, b'Host: localhost:8080')
self.assertEqual(self.parser.state, HttpParser.states.LINE_RCVD)
self.parser.parse(CRLF * 2)
self.assertDictContainsSubset({b'host': (b'Host', b'localhost:8080')}, self.parser.headers)
self.assertEqual(self.parser.state, HttpParser.states.COMPLETE)
def test_get_partial_parse2(self):
self.parser.parse(CRLF.join([
b'GET http://localhost:8080 HTTP/1.1',
b'Host: '
]))
self.assertEqual(self.parser.method, b'GET')
self.assertEqual(self.parser.url.hostname, b'localhost')
self.assertEqual(self.parser.url.port, 8080)
self.assertEqual(self.parser.version, b'HTTP/1.1')
self.assertEqual(self.parser.buffer, b'Host: ')
self.assertEqual(self.parser.state, HttpParser.states.LINE_RCVD)
self.parser.parse(b'localhost:8080' + CRLF)
self.assertDictContainsSubset({b'host': (b'Host', b'localhost:8080')}, self.parser.headers)
self.assertEqual(self.parser.buffer, b'')
self.assertEqual(self.parser.state, HttpParser.states.RCVING_HEADERS)
self.parser.parse(b'Content-Type: text/plain' + CRLF)
self.assertEqual(self.parser.buffer, b'')
self.assertDictContainsSubset({b'content-type': (b'Content-Type', b'text/plain')}, self.parser.headers)
self.assertEqual(self.parser.state, HttpParser.states.RCVING_HEADERS)
self.parser.parse(CRLF)
self.assertEqual(self.parser.state, HttpParser.states.COMPLETE)
def test_post_full_parse(self):
raw = CRLF.join([
b'POST %s HTTP/1.1',
b'Host: localhost',
b'Content-Length: 7',
b'Content-Type: application/x-www-form-urlencoded' + CRLF,
b'a=b&c=d'
])
self.parser.parse(raw % b'http://localhost')
self.assertEqual(self.parser.method, b'POST')
self.assertEqual(self.parser.url.hostname, b'localhost')
self.assertEqual(self.parser.url.port, None)
self.assertEqual(self.parser.version, b'HTTP/1.1')
self.assertDictContainsSubset({b'content-type': (b'Content-Type', b'application/x-www-form-urlencoded')},
self.parser.headers)
self.assertDictContainsSubset({b'content-length': (b'Content-Length', b'7')}, self.parser.headers)
self.assertEqual(self.parser.body, b'a=b&c=d')
self.assertEqual(self.parser.buffer, b'')
self.assertEqual(self.parser.state, HttpParser.states.COMPLETE)
self.assertEqual(len(self.parser.build()), len(raw % b'/'))
def test_post_partial_parse(self):
self.parser.parse(CRLF.join([
b'POST http://localhost HTTP/1.1',
b'Host: localhost',
b'Content-Length: 7',
b'Content-Type: application/x-www-form-urlencoded'
]))
self.assertEqual(self.parser.method, b'POST')
self.assertEqual(self.parser.url.hostname, b'localhost')
self.assertEqual(self.parser.url.port, None)
self.assertEqual(self.parser.version, b'HTTP/1.1')
self.assertEqual(self.parser.state, HttpParser.states.RCVING_HEADERS)
self.parser.parse(CRLF)
self.assertEqual(self.parser.state, HttpParser.states.RCVING_HEADERS)
self.parser.parse(CRLF)
self.assertEqual(self.parser.state, HttpParser.states.HEADERS_COMPLETE)
self.parser.parse(b'a=b')
self.assertEqual(self.parser.state, HttpParser.states.RCVING_BODY)
self.assertEqual(self.parser.body, b'a=b')
self.assertEqual(self.parser.buffer, b'')
self.parser.parse(b'&c=d')
self.assertEqual(self.parser.state, HttpParser.states.COMPLETE)
self.assertEqual(self.parser.body, b'a=b&c=d')
self.assertEqual(self.parser.buffer, b'')
def test_connect_request_without_host_header_request_parse(self):
"""Case where clients can send CONNECT request without a Host header field.
Example:
1. pip3 --proxy http://localhost:8899 install <package name>
Uses HTTP/1.0, Host header missing with CONNECT requests
2. Android Emulator
Uses HTTP/1.1, Host header missing with CONNECT requests
See https://github.com/abhinavsingh/proxy.py/issues/5 for details.
"""
self.parser.parse(b'CONNECT pypi.org:443 HTTP/1.0\r\n\r\n')
self.assertEqual(self.parser.method, b'CONNECT')
self.assertEqual(self.parser.version, b'HTTP/1.0')
self.assertEqual(self.parser.state, HttpParser.states.COMPLETE)
def test_request_parse_without_content_length(self):
"""Case when incoming request doesn't contain a content-length header.
From http://w3-org.9356.n7.nabble.com/POST-with-empty-body-td103965.html
'A POST with no content-length and no body is equivalent to a POST with Content-Length: 0
and nothing following, as could perfectly happen when you upload an empty file for instance.'
See https://github.com/abhinavsingh/proxy.py/issues/20 for details.
"""
self.parser.parse(CRLF.join([
b'POST http://localhost HTTP/1.1',
b'Host: localhost',
b'Content-Type: application/x-www-form-urlencoded',
CRLF
]))
self.assertEqual(self.parser.method, b'POST')
self.assertEqual(self.parser.state, HttpParser.states.COMPLETE)
def test_response_parse_without_content_length(self):
"""Case when server response doesn't contain a content-length header for non-chunk response types.
HttpParser by itself has no way to know if more data should be expected.
In example below, parser reaches state HttpParser.states.HEADERS_COMPLETE
and it is responsibility of callee to change state to HttpParser.states.COMPLETE
when server stream closes.
See https://github.com/abhinavsingh/proxy.py/issues/20 for details.
"""
self.parser.type = HttpParser.types.RESPONSE_PARSER
self.parser.parse(b'HTTP/1.0 200 OK' + CRLF)
self.assertEqual(self.parser.code, b'200')
self.assertEqual(self.parser.version, b'HTTP/1.0')
self.assertEqual(self.parser.state, HttpParser.states.LINE_RCVD)
self.parser.parse(CRLF.join([
b'Server: BaseHTTP/0.3 Python/2.7.10',
b'Date: Thu, 13 Dec 2018 16:24:09 GMT',
CRLF
]))
self.assertEqual(self.parser.state, HttpParser.states.HEADERS_COMPLETE)
def test_response_parse(self):
self.parser.type = HttpParser.types.RESPONSE_PARSER
self.parser.parse(b''.join([
b'HTTP/1.1 301 Moved Permanently\r\n',
b'Location: http://www.google.com/\r\n',
b'Content-Type: text/html; charset=UTF-8\r\n',
b'Date: Wed, 22 May 2013 14:07:29 GMT\r\n',
b'Expires: Fri, 21 Jun 2013 14:07:29 GMT\r\n',
b'Cache-Control: public, max-age=2592000\r\n',
b'Server: gws\r\n',
b'Content-Length: 219\r\n',
b'X-XSS-Protection: 1; mode=block\r\n',
b'X-Frame-Options: SAMEORIGIN\r\n\r\n',
b'<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">\n' +
b'<TITLE>301 Moved</TITLE></HEAD>',
b'<BODY>\n<H1>301 Moved</H1>\nThe document has moved\n' +
b'<A HREF="http://www.google.com/">here</A>.\r\n</BODY></HTML>\r\n'
]))
self.assertEqual(self.parser.code, b'301')
self.assertEqual(self.parser.reason, b'Moved Permanently')
self.assertEqual(self.parser.version, b'HTTP/1.1')
self.assertEqual(self.parser.body,
b'<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">\n' +
b'<TITLE>301 Moved</TITLE></HEAD><BODY>\n<H1>301 Moved</H1>\nThe document has moved\n' +
b'<A HREF="http://www.google.com/">here</A>.\r\n</BODY></HTML>\r\n')
self.assertDictContainsSubset({b'content-length': (b'Content-Length', b'219')}, self.parser.headers)
self.assertEqual(self.parser.state, HttpParser.states.COMPLETE)
def test_response_partial_parse(self):
self.parser.type = HttpParser.types.RESPONSE_PARSER
self.parser.parse(b''.join([
b'HTTP/1.1 301 Moved Permanently\r\n',
b'Location: http://www.google.com/\r\n',
b'Content-Type: text/html; charset=UTF-8\r\n',
b'Date: Wed, 22 May 2013 14:07:29 GMT\r\n',
b'Expires: Fri, 21 Jun 2013 14:07:29 GMT\r\n',
b'Cache-Control: public, max-age=2592000\r\n',
b'Server: gws\r\n',
b'Content-Length: 219\r\n',
b'X-XSS-Protection: 1; mode=block\r\n',
b'X-Frame-Options: SAMEORIGIN\r\n'
]))
self.assertDictContainsSubset({b'x-frame-options': (b'X-Frame-Options', b'SAMEORIGIN')}, self.parser.headers)
self.assertEqual(self.parser.state, HttpParser.states.RCVING_HEADERS)
self.parser.parse(b'\r\n')
self.assertEqual(self.parser.state, HttpParser.states.HEADERS_COMPLETE)
self.parser.parse(
b'<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">\n' +
b'<TITLE>301 Moved</TITLE></HEAD>')
self.assertEqual(self.parser.state, HttpParser.states.RCVING_BODY)
self.parser.parse(
b'<BODY>\n<H1>301 Moved</H1>\nThe document has moved\n' +
b'<A HREF="http://www.google.com/">here</A>.\r\n</BODY></HTML>\r\n')
self.assertEqual(self.parser.state, HttpParser.states.COMPLETE)
def test_chunked_response_parse(self):
self.parser.type = HttpParser.types.RESPONSE_PARSER
self.parser.parse(b''.join([
b'HTTP/1.1 200 OK\r\n',
b'Content-Type: application/json\r\n',
b'Date: Wed, 22 May 2013 15:08:15 GMT\r\n',
b'Server: gunicorn/0.16.1\r\n',
b'transfer-encoding: chunked\r\n',
b'Connection: keep-alive\r\n\r\n',
b'4\r\n',
b'Wiki\r\n',
b'5\r\n',
b'pedia\r\n',
b'E\r\n',
b' in\r\n\r\nchunks.\r\n',
b'0\r\n',
b'\r\n'
]))
self.assertEqual(self.parser.body, b'Wikipedia in\r\n\r\nchunks.')
self.assertEqual(self.parser.state, HttpParser.states.COMPLETE)
class MockConnection(object):
def __init__(self, b=b''):
self.buffer = b
def recv(self, b=8192):
data = self.buffer[:b]
self.buffer = self.buffer[b:]
return data
def send(self, data):
return len(data)
def queue(self, data):
self.buffer += data
class HTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
# TODO(abhinavsingh): Proxy should work just fine even without content-length header
self.send_header('content-length', 2)
self.end_headers()
self.wfile.write(b'OK')
class TestProxy(unittest.TestCase):
http_server = None
http_server_port = None
http_server_thread = None
@staticmethod
def get_available_port():
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.bind(('', 0))
_, port = sock.getsockname()
return port
@classmethod
def setUpClass(cls):
cls.http_server_port = cls.get_available_port()
cls.http_server = HTTPServer(('127.0.0.1', cls.http_server_port), HTTPRequestHandler)
cls.http_server_thread = Thread(target=cls.http_server.serve_forever)
cls.http_server_thread.setDaemon(True)
cls.http_server_thread.start()
@classmethod
def tearDownClass(cls):
cls.http_server.shutdown()
cls.http_server.server_close()
cls.http_server_thread.join()
def setUp(self):
self._conn = MockConnection()
self._addr = ('127.0.0.1', 54382)
self.proxy = Proxy(Client(self._conn, self._addr))
# def test_http_get(self):
# # Send request line
# self.proxy.client.conn.queue((b'GET http://localhost:%d HTTP/1.1' % self.http_server_port) + CRLF)
# self.proxy._process_request(self.proxy.client.recv())
# self.assertNotEqual(self.proxy.request.state, HttpParser.states.COMPLETE)
# # Send headers and blank line, thus completing HTTP request
# self.proxy.client.conn.queue(CRLF.join([
# b'User-Agent: proxy.py/%s' % version,
# b'Host: localhost:%d' % self.http_server_port,
# b'Accept: */*',
# b'Proxy-Connection: Keep-Alive',
# CRLF
# ]))
# self.proxy._process_request(self.proxy.client.recv())
# self.assertEqual(self.proxy.request.state, HttpParser.states.COMPLETE)
# self.assertEqual(self.proxy.server.addr, (b'localhost', self.http_server_port))
# # Flush data queued for server
# self.proxy.server.flush()
# self.assertEqual(self.proxy.server.buffer_size(), 0)
# # Receive full response from server
# data = self.proxy.server.recv()
# while data:
# self.proxy._process_response(data)
# logging.info(self.proxy.response.state)
# if self.proxy.response.state == HttpParser.states.COMPLETE:
# break
# data = self.proxy.server.recv()
# # Verify 200 success response code
# self.assertEqual(self.proxy.response.state, HttpParser.states.COMPLETE)
# self.assertEqual(int(self.proxy.response.code), 200)
#
# def test_http_tunnel(self):
# self.proxy.client.conn.queue(CRLF.join([
# b'CONNECT localhost:%d HTTP/1.1' % self.http_server_port,
# b'Host: localhost:%d' % self.http_server_port,
# b'User-Agent: proxy.py/%s' % version,
# b'Proxy-Connection: Keep-Alive',
# CRLF
# ]))
# self.proxy._process_request(self.proxy.client.recv())
# self.assertFalse(self.proxy.server is None)
# self.assertEqual(self.proxy.client.buffer, PROXY_TUNNEL_ESTABLISHED_RESPONSE_PKT)
#
# parser = HttpParser(HttpParser.types.RESPONSE_PARSER)
# parser.parse(self.proxy.client.buffer)
# self.assertEqual(parser.state, HttpParser.states.HEADERS_COMPLETE)
# self.assertEqual(int(parser.code), 200)
#
# self.proxy.client.flush()
# self.assertEqual(self.proxy.client.buffer_size(), 0)
#
# self.proxy.client.conn.queue(CRLF.join([
# b'GET / HTTP/1.1',
# b'Host: localhost:%d' % self.http_server_port,
# b'User-Agent: proxy.py/%s' % version,
# CRLF
# ]))
# self.proxy._process_request(self.proxy.client.recv())
# self.proxy.server.flush()
# self.assertEqual(self.proxy.server.buffer_size(), 0)
#
# parser = HttpParser(HttpParser.types.RESPONSE_PARSER)
# data = self.proxy.server.recv()
# while data:
# parser.parse(data)
# if parser.state == HttpParser.states.COMPLETE:
# break
# data = self.proxy.server.recv()
#
# self.assertEqual(parser.state, HttpParser.states.COMPLETE)
# self.assertEqual(int(parser.code), 200)
#
# def test_proxy_connection_failed(self):
# with self.assertRaises(ProxyConnectionFailed):
# self.proxy._process_request(CRLF.join([
# b'GET http://unknown.domain HTTP/1.1',
# b'Host: unknown.domain',
# CRLF
# ]))
# def test_proxy_authentication_failed(self):
# self.proxy = Proxy(Client(self._conn, self._addr), b'Basic %s' % base64.b64encode(b'user:pass'))
#
# with self.assertRaises(ProxyAuthenticationFailed):
# self.proxy._process_request(CRLF.join([
# b'GET http://abhinavsingh.com HTTP/1.1',
# b'Host: abhinavsingh.com',
# CRLF
# ]))
# def test_authenticated_proxy_http_get(self):
# self.proxy = Proxy(Client(self._conn, self._addr), b'Basic %s' % base64.b64encode(b'user:pass'))
#
# self.proxy.client.conn.queue((b'GET http://localhost:%d HTTP/1.1' % self.http_server_port) + CRLF)
# self.proxy._process_request(self.proxy.client.recv())
# self.assertNotEqual(self.proxy.request.state, HttpParser.states.COMPLETE)
#
# self.proxy.client.conn.queue(CRLF.join([
# b'User-Agent: proxy.py/%s' % version,
# b'Host: localhost:%d' % self.http_server_port,
# b'Accept: */*',
# b'Proxy-Connection: Keep-Alive',
# b'Proxy-Authorization: Basic dXNlcjpwYXNz',
# CRLF
# ]))
#
# self.proxy._process_request(self.proxy.client.recv())
# self.assertEqual(self.proxy.request.state, HttpParser.states.COMPLETE)
# self.assertEqual(self.proxy.server.addr, (b'localhost', self.http_server_port))
#
# self.proxy.server.flush()
# self.assertEqual(self.proxy.server.buffer_size(), 0)
#
# data = self.proxy.server.recv()
# while data:
# self.proxy._process_response(data)
# if self.proxy.response.state == HttpParser.states.COMPLETE:
# break
# data = self.proxy.server.recv()
#
# self.assertEqual(self.proxy.response.state, HttpParser.states.COMPLETE)
# self.assertEqual(int(self.proxy.response.code), 200)
#
# def test_authenticated_proxy_http_tunnel(self):
# self.proxy = Proxy(Client(self._conn, self._addr), b'Basic %s' % base64.b64encode(b'user:pass'))
#
# self.proxy.client.conn.queue(CRLF.join([
# b'CONNECT localhost:%d HTTP/1.1' % self.http_server_port,
# b'Host: localhost:%d' % self.http_server_port,
# b'User-Agent: proxy.py/%s' % version,
# b'Proxy-Connection: Keep-Alive',
# b'Proxy-Authorization: Basic dXNlcjpwYXNz',
# CRLF
# ]))
# self.proxy._process_request(self.proxy.client.recv())
# self.assertFalse(self.proxy.server is None)
# self.assertEqual(self.proxy.client.buffer, PROXY_TUNNEL_ESTABLISHED_RESPONSE_PKT)
#
# parser = HttpParser(HttpParser.types.RESPONSE_PARSER)
# parser.parse(self.proxy.client.buffer)
# self.assertEqual(parser.state, HttpParser.states.HEADERS_COMPLETE)
# self.assertEqual(int(parser.code), 200)
#
# self.proxy.client.flush()
# self.assertEqual(self.proxy.client.buffer_size(), 0)
#
# self.proxy.client.conn.queue(CRLF.join([
# b'GET / HTTP/1.1',
# b'Host: localhost:%d' % self.http_server_port,
# b'User-Agent: proxy.py/%s' % version,
# CRLF
# ]))
# self.proxy._process_request(self.proxy.client.recv())
# self.proxy.server.flush()
# self.assertEqual(self.proxy.server.buffer_size(), 0)
#
# parser = HttpParser(HttpParser.types.RESPONSE_PARSER)
# data = self.proxy.server.recv()
# while data:
# parser.parse(data)
# if parser.state == HttpParser.states.COMPLETE:
# break
# data = self.proxy.server.recv()
#
# self.assertEqual(parser.state, HttpParser.states.COMPLETE)
# self.assertEqual(int(parser.code), 200)
if __name__ == '__main__':
unittest.main()
|
metric_store_test.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import random
import threading
import time
import unittest
import mock
from infra_libs.ts_mon.common import distribution
from infra_libs.ts_mon.common import interface
from infra_libs.ts_mon.common import errors
from infra_libs.ts_mon.common import metric_store
from infra_libs.ts_mon.common import metrics
from infra_libs.ts_mon.common import targets
class DefaultModifyFnTest(unittest.TestCase):
def test_adds(self):
fn = metric_store.default_modify_fn('foo')
self.assertEquals(5, fn(2, 3))
self.assertEquals(5, fn(3, 2))
def test_negative(self):
fn = metric_store.default_modify_fn('foo')
with self.assertRaises(errors.MonitoringDecreasingValueError) as cm:
fn(2, -1)
self.assertIn('"foo"', str(cm.exception))
class MetricStoreTestBase(object):
"""Abstract base class for testing MetricStore implementations.
This class doesn't inherit from unittest.TestCase to prevent it from being
run automatically by expect_tests.
Your subclass should inherit from this and unittest.TestCase, and set
METRIC_STORE_CLASS to the implementation you want to test. See
InProcessMetricStoreTest in this file for an example.
"""
METRIC_STORE_CLASS = None
def setUp(self):
super(MetricStoreTestBase, self).setUp()
self.mock_time = mock.create_autospec(time.time, spec_set=True)
self.mock_time.return_value = 1234
target = targets.TaskTarget(
'test_service', 'test_job', 'test_region', 'test_host')
self.state = interface.State(store_ctor=self.create_store, target=target)
mock.patch('infra_libs.ts_mon.common.interface.state',
new=self.state).start()
self.store = self.state.store
self.metric = metrics.Metric('foo', 'desc', None)
def create_store(self, *args, **kwargs):
kwargs['time_fn'] = self.mock_time
return self.METRIC_STORE_CLASS(*args, **kwargs)
def tearDown(self):
super(MetricStoreTestBase, self).tearDown()
mock.patch.stopall()
def test_sets_start_time(self):
self.metric._start_time = None
self.mock_time.return_value = 1234
self.store.set('foo', ('value',), None, 42)
self.store.set('foo', ('value2',), None, 43)
all_metrics = list(self.store.get_all())
self.assertEqual(1, len(all_metrics))
self.assertEqual('foo', all_metrics[0][1].name)
self.assertEqual(1234, all_metrics[0][2])
def test_uses_start_time_from_metric(self):
self.metric._start_time = 5678
self.store.set('foo', ('value',), None, 42)
self.store.set('foo', ('value2',), None, 43)
all_metrics = list(self.store.get_all())
self.assertEqual(1, len(all_metrics))
self.assertEqual('foo', all_metrics[0][1].name)
self.assertEqual(5678, all_metrics[0][2])
def test_get(self):
fields1 = ('value',)
fields2 = ('value2',)
fields3 = ('value3',)
target_fields1 = {'region': 'rrr'}
target_fields2 = {'region': 'rrr', 'hostname': 'hhh'}
self.store.set('foo', fields1, None, 42)
self.store.set('foo', fields2, None, 43)
self.store.set('foo', fields1, target_fields1, 24)
self.store.set('foo', fields2, target_fields2, 34)
self.assertEquals(42, self.store.get('foo', fields1, None))
self.assertEquals(43, self.store.get('foo', fields2, None))
self.assertEquals(24, self.store.get('foo', fields1, target_fields1))
self.assertEquals(34, self.store.get('foo', fields2, target_fields2))
self.assertIsNone(self.store.get('foo', fields3, None))
self.assertIsNone(self.store.get('foo', (), None))
self.assertIsNone(self.store.get('foo', fields1, target_fields2))
self.assertEquals(44, self.store.get('foo', fields3, None, default=44))
self.assertIsNone(self.store.get('bar', (), None))
def test_iter_field_values(self):
fields1 = ('value',)
fields2 = ('value2',)
target_fields1 = {'region': 'rrr'}
self.store.set('foo', fields1, None, 42)
self.store.set('foo', fields2, None, 43)
self.store.set('foo', fields2, target_fields1, 44)
field_values = list(self.store.iter_field_values('foo'))
self.assertEquals([
(('value',), 42),
(('value2',), 43),
(('value2',), 44),
], sorted(field_values))
def test_set_enforce_ge(self):
self.store.set('foo', ('value',), None, 42, enforce_ge=True)
self.store.set('foo', ('value',), None, 43, enforce_ge=True)
with self.assertRaises(errors.MonitoringDecreasingValueError):
self.store.set('foo', ('value',), None, 42, enforce_ge=True)
def test_incr(self):
self.store.set('foo', ('value',), None, 42)
self.store.incr('foo', ('value',), None, 4)
self.assertEquals(46, self.store.get('foo', ('value',), None))
with self.assertRaises(errors.MonitoringDecreasingValueError):
self.store.incr('foo', ('value',), None, -1)
def test_incr_modify_fn(self):
def spec_fn(n, i): # pragma: no cover
return n+i
modify_fn = mock.create_autospec(spec_fn, spec_set=True)
modify_fn.return_value = 7
self.store.set('foo', ('value',), None, 42)
self.store.incr('foo', ('value',), None, 3, modify_fn=modify_fn)
self.assertEquals(7, self.store.get('foo', ('value',), None))
modify_fn.assert_called_once_with(42, 3)
def test_reset_for_unittest(self):
self.store.set('foo', ('value',), None, 42)
self.store.reset_for_unittest()
self.assertIsNone(self.store.get('foo', ('value',), None))
def test_reset_for_unittest_name(self):
self.store.set('foo', ('value',), None, 42)
self.store.reset_for_unittest(name='bar')
self.assertEquals(42, self.store.get('foo', ('value',), None))
self.store.reset_for_unittest(name='foo')
self.assertIsNone(self.store.get('foo', ('value',), None))
def test_unregister_metric(self):
fields = (('field', 'value'),)
self.store.set('foo', fields, None, 42) # Registered in setUp().
self.store.set('bar', fields, None, 24) # Unregistered.
all_metrics = list(self.store.get_all())
self.assertEqual(1, len(all_metrics))
self.assertEqual('foo', all_metrics[0][1].name)
def test_copies_distributions(self):
def modify_fn(dist, delta):
# This is the same as the modify_fn in _DistributionMetricBase's add().
if dist == 0:
dist = distribution.Distribution(distribution.GeometricBucketer())
dist.add(delta)
return dist
# Increment the metric once to create it in the store.
self.store.incr('foo', (), None, 42, modify_fn)
# Get its value from get_all. We should get a copy of the distribution.
dist = list(list(self.store.get_all())[0][4].items())[0][1]
self.assertEqual(1, dist.count)
self.assertEqual(42, dist.sum)
# Increment the metric again.
self.store.incr('foo', (), None, 42, modify_fn)
# The object we got should not change.
self.assertEqual(1, dist.count)
self.assertEqual(42, dist.sum)
def test_get_all_thread_safe(self):
"""Dumb test to check that setting metrics while calling get_all is ok."""
start = threading.Event()
stop = threading.Event()
def modify_worker():
start.wait()
while not stop.is_set():
self.store.set('foo', (('field', random.random()),), None, 1)
successful_workers = []
def get_all_worker():
start.wait()
while not stop.is_set():
for _, _, _, _, fields_values in self.store.get_all():
list(fields_values.items())
successful_workers.append(True)
# Create 10 modify threads and 10 get_all threads.
threads = (
[threading.Thread(target=modify_worker) for _ in range(10)] +
[threading.Thread(target=get_all_worker) for _ in range(10)])
# Start all the threads at once.
for thread in threads:
thread.start()
start.set()
# Wait 2 seconds then stop them all.
time.sleep(2)
stop.set()
for thread in threads:
thread.join()
# All the threads should've been successful and not raised an exception in
# get_all.
self.assertEqual([True] * 10, successful_workers)
class InProcessMetricStoreTest(MetricStoreTestBase, unittest.TestCase):
METRIC_STORE_CLASS = metric_store.InProcessMetricStore
|
thread_race.py | #导入Thread类
from threading import Thread
#初始化全局变量
g_sum = 0
sum = 499995000000
def child_thread():
global g_sum
for i in range(100000):
g_sum = g_sum + i
if __name__ == "__main__":
threads = [Thread(target=child_thread)
for i in range(100)]
for t in threads:
t.start() #启动所有线程
for t in threads:
t.join() #等待线程结束
print("g_sum should be:%s;g_sum:%s"%(sum,g_sum))
|
utils.py | # -*- coding: utf-8 -*-
import contextlib
import errno
import hashlib
import importlib
import json
import os
import sys
from atomicwrites import atomic_write
import click
import click_threading
from . import cli_logger
from .. import DOCS_HOME, exceptions
from ..sync import IdentConflict, StorageEmpty, SyncConflict
from ..utils import expand_path, get_class_init_args
from ..utils.compat import to_native
try:
import Queue as queue
except ImportError:
import queue
STATUS_PERMISSIONS = 0o600
STATUS_DIR_PERMISSIONS = 0o700
# Increase whenever upgrade potentially breaks discovery cache and collections
# should be re-discovered
DISCOVERY_CACHE_VERSION = 1
class _StorageIndex(object):
def __init__(self):
self._storages = dict(
caldav='vdirsyncer.storage.dav.CaldavStorage',
carddav='vdirsyncer.storage.dav.CarddavStorage',
filesystem='vdirsyncer.storage.filesystem.FilesystemStorage',
http='vdirsyncer.storage.http.HttpStorage',
singlefile='vdirsyncer.storage.singlefile.SingleFileStorage',
remotestorage_contacts=(
'vdirsyncer.storage.remotestorage.RemoteStorageContacts'),
remotestorage_calendars=(
'vdirsyncer.storage.remotestorage.RemoteStorageCalendars'),
)
def __getitem__(self, name):
item = self._storages[name]
if not isinstance(item, str):
return item
modname, clsname = item.rsplit('.', 1)
mod = importlib.import_module(modname)
self._storages[name] = rv = getattr(mod, clsname)
assert rv.storage_name == name
return rv
storage_names = _StorageIndex()
del _StorageIndex
class JobFailed(RuntimeError):
pass
# TODO: Making this a decorator would be nice
def handle_cli_error(status_name=None):
'''
Print a useful error message for the current exception.
This is supposed to catch all exceptions, and should never raise any
exceptions itself.
'''
try:
raise
except exceptions.UserError as e:
cli_logger.critical(e)
except StorageEmpty as e:
cli_logger.error(
'{status_name}: Storage "{name}" was completely emptied. If you '
'want to delete ALL entries on BOTH sides, then use '
'`vdirsyncer sync --force-delete {status_name}`. '
'Otherwise delete the files for {status_name} in your status '
'directory.'.format(
name=e.empty_storage.instance_name,
status_name=status_name
)
)
except SyncConflict as e:
cli_logger.error(
'{status_name}: One item changed on both sides. Resolve this '
'conflict manually, or by setting the `conflict_resolution` '
'parameter in your config file.\n'
'See also {docs}/config.html#pair-section\n'
'Item ID: {e.ident}\n'
'Item href on side A: {e.href_a}\n'
'Item href on side B: {e.href_b}\n'
.format(status_name=status_name, e=e, docs=DOCS_HOME)
)
except IdentConflict as e:
cli_logger.error(
'{status_name}: Storage "{storage.instance_name}" contains '
'multiple items with the same UID or even content. Vdirsyncer '
'will now abort the synchronization of this collection, because '
'the fix for this is not clear; It could be the result of a badly '
'behaving server. You can try running:\n\n'
' vdirsyncer repair {storage.instance_name}\n\n'
'But make sure to have a backup of your data in some form. The '
'offending hrefs are:\n\n{href_list}\n'
.format(status_name=status_name,
storage=e.storage,
href_list='\n'.join(map(repr, e.hrefs)))
)
except (click.Abort, KeyboardInterrupt, JobFailed):
pass
except exceptions.PairNotFound as e:
cli_logger.error(
'Pair {pair_name} does not exist. Please check your '
'configuration file and make sure you\'ve typed the pair name '
'correctly'.format(pair_name=e.pair_name)
)
except Exception as e:
if status_name:
msg = 'Unhandled exception occured for {}.'.format(
coerce_native(status_name))
else:
msg = 'Unhandled exception occured.'
cli_logger.exception(msg)
def get_status_name(pair, collection):
if collection is None:
return pair
return pair + '/' + collection
def _get_collections_cache_key(pair):
m = hashlib.sha256()
j = json.dumps([
DISCOVERY_CACHE_VERSION,
pair.options.get('collections', None),
pair.config_a,
pair.config_b,
], sort_keys=True)
m.update(j.encode('utf-8'))
return m.hexdigest()
def collections_for_pair(status_path, pair, skip_cache=False):
'''Determine all configured collections for a given pair. Takes care of
shortcut expansion and result caching.
:param status_path: The path to the status directory.
:param skip_cache: Whether to skip the cached data and always do discovery.
Even with this option enabled, the new cache is written.
:returns: iterable of (collection, (a_args, b_args))
'''
rv = load_status(status_path, pair.name, data_type='collections')
cache_key = _get_collections_cache_key(pair)
if rv and not skip_cache:
if rv.get('cache_key', None) == cache_key:
return list(_expand_collections_cache(
rv['collections'], pair.config_a, pair.config_b
))
elif rv:
cli_logger.info('Detected change in config file, discovering '
'collections for {}'.format(pair.name))
cli_logger.info('Discovering collections for pair {}'
.format(pair.name))
# We have to use a list here because the special None/null value would get
# mangled to string (because JSON objects always have string keys).
rv = list(_collections_for_pair_impl(status_path, pair))
save_status(status_path, pair.name, data_type='collections',
data={
'collections': list(
_compress_collections_cache(rv, pair.config_a,
pair.config_b)
),
'cache_key': cache_key
})
return rv
def _compress_collections_cache(collections, config_a, config_b):
def deduplicate(x, y):
rv = {}
for key, value in x.items():
if key not in y or y[key] != value:
rv[key] = value
return rv
for name, (a, b) in collections:
yield name, (deduplicate(a, config_a), deduplicate(b, config_b))
def _expand_collections_cache(collections, config_a, config_b):
for name, (a_delta, b_delta) in collections:
a = dict(config_a)
a.update(a_delta)
b = dict(config_b)
b.update(b_delta)
yield name, (a, b)
def _discover_from_config(config):
storage_type = config['type']
cls, config = storage_class_from_config(config)
try:
discovered = list(cls.discover(**config))
except Exception:
return handle_storage_init_error(cls, config)
else:
rv = {}
for args in discovered:
args['type'] = storage_type
rv[args['collection']] = args
return rv
def _handle_collection_not_found(config, collection, e=None):
storage_name = config.get('instance_name', None)
cli_logger.error('{}No collection {} found for storage {}.'
.format('{}\n'.format(e) if e else '',
coerce_native(collection), storage_name))
if click.confirm('Should vdirsyncer attempt to create it?'):
storage_type = config['type']
cls, config = storage_class_from_config(config)
config['collection'] = collection
try:
args = cls.create_collection(**config)
args['type'] = storage_type
return args
except NotImplementedError as e:
cli_logger.error(e)
raise exceptions.UserError(
'Unable to find or create collection "{collection}" for '
'storage "{storage}". Please create the collection '
'yourself.'.format(collection=collection,
storage=storage_name))
def _collections_for_pair_impl(status_path, pair):
shortcuts = pair.options['collections']
if shortcuts is None:
yield None, (pair.config_a, pair.config_b)
else:
a_discovered = _discover_from_config(pair.config_a)
b_discovered = _discover_from_config(pair.config_b)
for shortcut in set(shortcuts):
if shortcut == 'from a':
collections = a_discovered
elif shortcut == 'from b':
collections = b_discovered
else:
collections = [shortcut]
for collection in collections:
try:
a_args = a_discovered[collection]
except KeyError:
a_args = _handle_collection_not_found(pair.config_a,
collection)
try:
b_args = b_discovered[collection]
except KeyError:
b_args = _handle_collection_not_found(pair.config_b,
collection)
yield collection, (a_args, b_args)
def load_status(base_path, pair, collection=None, data_type=None):
assert data_type is not None
status_name = get_status_name(pair, collection)
path = expand_path(os.path.join(base_path, status_name))
if os.path.isfile(path) and data_type == 'items':
new_path = path + '.items'
cli_logger.warning('Migrating statuses: Renaming {} to {}'
.format(path, new_path))
os.rename(path, new_path)
path += '.' + data_type
if not os.path.exists(path):
return None
assert_permissions(path, STATUS_PERMISSIONS)
with open(path) as f:
try:
return dict(json.load(f))
except ValueError:
pass
# XXX: Deprecate
# Old status format, deprecated as of 0.4.0
# See commit 06a701bc10dac16ff0ff304eb7cb9f502b71cf95
f.seek(0)
try:
return dict(json.loads(line) for line in f)
except ValueError:
pass
return {}
def save_status(base_path, pair, collection=None, data_type=None, data=None):
assert data_type is not None
assert data is not None
status_name = get_status_name(pair, collection)
path = expand_path(os.path.join(base_path, status_name)) + '.' + data_type
dirname = os.path.dirname(path)
try:
os.makedirs(dirname, STATUS_DIR_PERMISSIONS)
except OSError as e:
if e.errno != errno.EEXIST:
raise
with atomic_write(path, mode='w', overwrite=True) as f:
json.dump(data, f)
os.chmod(path, STATUS_PERMISSIONS)
def storage_class_from_config(config):
config = dict(config)
storage_name = config.pop('type')
try:
cls = storage_names[storage_name]
except KeyError:
raise exceptions.UserError(
'Unknown storage type: {}'.format(storage_name))
return cls, config
def storage_instance_from_config(config, create=True):
'''
:param config: A configuration dictionary to pass as kwargs to the class
corresponding to config['type']
'''
cls, new_config = storage_class_from_config(config)
try:
return cls(**new_config)
except exceptions.CollectionNotFound as e:
if create:
config = _handle_collection_not_found(
config, config.get('collection', None), e=str(e))
return storage_instance_from_config(config, create=False)
else:
raise
except Exception:
return handle_storage_init_error(cls, new_config)
def handle_storage_init_error(cls, config):
e = sys.exc_info()[1]
if isinstance(e, (click.Abort, exceptions.UserError, KeyboardInterrupt)):
raise
all, required = get_class_init_args(cls)
given = set(config)
missing = required - given
invalid = given - all
problems = []
if missing:
cli_logger.critical(
u'{} storage requires the parameters: {}'
.format(cls.storage_name, u', '.join(missing)))
if invalid:
cli_logger.critical(
u'{} storage doesn\'t take the parameters: {}'
.format(cls.storage_name, u', '.join(invalid)))
if not problems:
if not isinstance(e, exceptions.UserError):
cli_logger.exception('')
problems.append(str(e))
raise exceptions.UserError(
u'Failed to initialize {}'.format(config['instance_name']),
problems=problems
)
class WorkerQueue(object):
'''
A simple worker-queue setup.
Note that workers quit if queue is empty. That means you have to first put
things into the queue before spawning the worker!
'''
def __init__(self, max_workers):
self._queue = queue.Queue()
self._workers = []
self._exceptions = []
self._max_workers = max_workers
self._shutdown_handlers = []
def shutdown(self):
while self._shutdown_handlers:
try:
self._shutdown_handlers.pop()()
except Exception:
pass
def _worker(self):
while True:
try:
func = self._queue.get(False)
except queue.Empty:
break
try:
func(wq=self)
except Exception as e:
handle_cli_error()
self._exceptions.append(e)
finally:
self._queue.task_done()
if not self._queue.unfinished_tasks:
self.shutdown()
def spawn_worker(self):
if self._max_workers and len(self._workers) >= self._max_workers:
return
t = click_threading.Thread(target=self._worker)
t.start()
self._workers.append(t)
@contextlib.contextmanager
def join(self):
assert self._workers or not self._queue.unfinished_tasks
ui_worker = click_threading.UiWorker()
self._shutdown_handlers.append(ui_worker.shutdown)
with ui_worker.patch_click():
yield
ui_worker.run()
self._queue.join()
for worker in self._workers:
worker.join()
if self._exceptions:
sys.exit(1)
def put(self, f):
return self._queue.put(f)
def format_storage_config(cls, header=True):
if header is True:
yield '[storage example_for_{}]'.format(cls.storage_name)
yield 'type = {}'.format(cls.storage_name)
from ..storage.base import Storage
from ..utils import get_class_init_specs
handled = set()
for spec in get_class_init_specs(cls, stop_at=Storage):
defaults = spec.defaults or ()
defaults = dict(zip(spec.args[-len(defaults):], defaults))
for key in spec.args[1:]:
if key in handled:
continue
handled.add(key)
comment = '' if key not in defaults else '#'
value = defaults.get(key, '...')
yield '{}{} = {}'.format(comment, key, json.dumps(value))
def assert_permissions(path, wanted):
permissions = os.stat(path).st_mode & 0o777
if permissions > wanted:
cli_logger.warning('Correcting permissions of {} from {:o} to {:o}'
.format(path, permissions, wanted))
os.chmod(path, wanted)
def coerce_native(x, encoding='utf-8'):
# XXX: Remove with Python 3 only
try:
return str(x)
except UnicodeError:
pass
try:
return to_native(x, encoding=encoding)
except UnicodeError:
pass
return repr(x)
|
client.py | from bottle import route, run, request, static_file, Bottle, response
import hash_ring
import sys, getopt
import yaml
import os
import requests
import json
from argparse import ArgumentParser
from optparse import OptionParser
import time
import socket
import random
from multiprocessing import Process, Queue
from dxf import *
import rejson, redis, json
app = Bottle()
dbNoBlob = 0
dbNoFile = 1
dbNoBFRecipe = 2
####
# NANNAN: tar the blobs and send back to master.
# maybe ignore.
####
##
# NANNAN: fetch the serverips from redis by using layer digest
##
def pull_from_registry(wait, dgst, registry_q, startTime, onTime_q):
while True:
registry_tmp = registry_q.get()
results = []
size = 0
t = 0
t = time.time()
if ":5000" not in registry_tmp:
registry_tmp = registry_tmp+":5000"
print "layer/manifest: "+dgst+"goest to registry: "+registry_tmp
onTime = 'yes'
dxf = DXF(registry_tmp, 'test_repo', insecure=True)
try:
for chunk in dxf.pull_blob(dgst, chunk_size=1024*1024):
size += len(chunk)
except Exception as e:
if "expected digest sha256:" in str(e):
onTime = 'yes: wrong digest'
else:
onTime = 'failed: '+str(e)
t = time.time() - t
results.append({'size': size, 'onTime': onTime, 'duration': t})
onTime_q.put(results)
def redis_stat_bfrecipe_serverips(dgst):
global rj_dbNoBFRecipe
if not rj_dbNoBFRecipe.exists(dgst):
return None
bfrecipe = json.loads(rj_dbNoBFRecipe.execute_command('JSON.GET', dgst))
serverIps = []
for serverip in bfrecipe.ServerIps:
serverIps.append(serverip)
return serverIps
def get_request_registries(r):
global ring
dgst = r['blob']
if r['method'] == 'PUT':
registry_tmp = ring.get_node(dgst) # which registry should store this layer/manifest?
print "layer: "+req['blob']+"goest to registry: "+registry_tmp
return registry_tmp
else:
serverIps = redis_stat_bfrecipe_serverips(dgst)
if not serverIps:
registry_tmp = ring.get_node(dgst)
return registry_tmp
return serverIps
def send_requests(wait, requests, startTime, q):
results = []
for r in requests:
size = 0
t = 0
registries = []
start = startTime + r['delay']
onTime = 'no'
if r['method'] == 'GET':
registries.extend(get_request_registries(r))
threads = len(registries)
if not threads:
print 'destination registries for this blob is zero! ERROR!'
onTime_q = Queue()
now = time.time()
if start > now and wait is True:
onTime = 'yes'
time.sleep(start - now)
t = time.time()
for i in range(threads):
p = Process(target=pull_from_registry, args=(wait, dgst, registry_q, startTime, onTime_q))
p.start()
processes.append(p)
for p in processes:
p.join()
t = time.time() - t
onTime_l = list(onTime_q.queue)
results.append({'time': now, 'duration': t, 'onTime': onTime_l}) #, 'size': size
pull_rsp_q.put(results)
print 'processes joined, send requests continuing'
else:
size = r['size']
if size > 0:
now = time.time()
if start > now and wait is True:
time.sleep(start - now)
now = time.time()
registries.extend(get_request_registries(r))
registry_tmp = registries[0]
dxf = DXF(registry_tmp, 'test_repo', insecure=True)
try:
dgst = dxf.push_blob(r['data'])#fname
except Exception as e:
if "expected digest sha256:" in str(e):
onTime = 'yes: wrong digest'
else:
onTime = 'failed: '+str(e)
t = time.time() - now
results.append({'time': now, 'duration': t, 'onTime': onTime, 'size': size})
q.put(results)
################################
# NANNAN: forward to registries according to cht
################################
def get_messages(q):
while True:
msg = q.get()
masterip = msg[0]
requests = json.loads(msg[1])
# put_rand = requests[0]['random']
threads = requests[0]['threads']
ID = requests[0]['id']
master = (masterip, requests[0]['port'])
# registry = requests[0]['registry']
wait = requests[0]['wait']
print master, ID, threads
processes = []
process_requests = []
delayed = []
for i in range(threads):
process_requests.append([])
delayed.append(0)
for r in requests[1:]:
i = 0
for j in range(len(delayed)):
if delayed[j] < delayed[i]:
i = j
if delayed[i] < r['delay']:
delayed[i] = r['delay'] + r['duration']
else:
delayed[i] += r['duration']
process_requests[i].append(r)
requests = [{'id': ID}]
startTime = time.time()
rq = Queue()
for i in range(threads):
# first = registry.pop(0)
# registry.append(first)
p = Process(target=send_requests, args=(wait, process_requests[i], startTime, rq))
p.start()
processes.append(p)
for i in range(threads):
requests.extend(rq.get())
for p in processes:
p.join()
print 'processes joined, sending response'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
err = False
try:
sock.connect(master)
sock.sendall(json.dumps(requests))
except Exception as inst:
print inst
print "Error sending info, writing to file"
err = True
if err is True:
with open('error_output', 'w') as f:
f.write(json.dumps(requests))
sock.close()
print 'finished'
@app.route('/up', method="POST")
def sen():
if 'application/json' in request.headers['Content-Type']:
app.queue.put((request.environ.get('REMOTE_ADDR'), request.body.read()))
return 'gotcha :D'
def main():
ip = "0.0.0.0"
registries = []
parser = ArgumentParser(description='registry-helper, helping registry to do a global dedup or slimmer ops.')
parser.add_argument('-i', '--input', dest='input', type=str, required=True, help = 'Input YAML configuration file, should contain all the inputs requried for processing')
parser.add_argument('-c', '--command', dest='command', type=str, required=False, help= 'registry-testing command. Possible commands: TestGloablDedup, etc,.')
args = parser.parse_args()
config = file(args.input, 'r')
try:
inputs = yaml.load(config)
except Exception as inst:
print 'error reading config file'
print inst
exit(-1)
verbose = False
if 'verbose' in inputs:
if inputs['verbose'] is True:
verbose = True
print 'Verbose Mode'
if 'registry' in inputs:
registries.extend(inputs['registry'])
if 'port' not in inputs['client_info']:
if verbose:
print 'client port not specified, assuming 8082'
port = 8082
else:
port = inputs['client_info']['port']
if verbose:
print 'helper port: ' + str(port)
global app
global ring
global rj_dbNoBFRecipe
global rjpool_dbNoBFRecipe
#### connect to redis!
if 'redis' not in inputs:
print 'please config redis for helper!'
else:
redis_host = inputs['redis']['host']
redis_port = inputs['redis']['port']
if verbose:
print 'redis: host:'+str(redis_host)+',port:'+str(redis_port)
# rj = rejson.Client(host=redis_host, port=redis_port)
rjpool_dbNoBFRecipe = redis.ConnectionPool(host = redis_host, port = redis_port, db = dbNoBFRecipe)
rj_dbNoBFRecipe = redis.Redis(connection_pool=rjpool_dbNoBFRecipe)
ring = hash_ring.HashRing(registries)
if args.command == 'TestGlobalDedup':
if verbose:
print 'test global dedup mode'
app.queue = Queue()
backend = Process(target=get_messages, args=[app.queue])
backend.start()
run(app, host=ip, port=port, quiet=True, numthreads=1)
if __name__ == "__main__":
main()
|
system_test.py | '''
Copyright (c) 2019, Arm Limited and Contributors
SPDX-License-Identifier: Apache-2.0
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 sys, os, math, platform, threading, datetime, subprocess, zipfile, argparse, shutil, struct, imghdr
from time import sleep
from threading import Thread
# Settings (changing these may cause instabilities)
dependencies = ("magick", "cmake", "git", "adb")
multithread = False
sub_tests = []
test_desktop = True
test_android = True
comparison_metric = "MAE"
current_dir = os.getcwd()
script_path = os.path.dirname(os.path.realpath(__file__))
root_path = os.path.join(script_path, "../../")
build_path = ""
build_config = ""
outputs_path = os.path.join(root_path, "output/images/")
tmp_path = os.path.join(script_path, "tmp/")
archive_path = os.path.join(script_path, "artifacts/")
image_ext = ".png"
android_timeout = 60 # How long in seconds should we wait before timing out on Android
check_step = 5
threshold = 0.999 # How similar the images are allowed to be before they pass
class Subtest:
result = False
test_name = ""
platform = ""
def __init__(self, test_name, platform):
self.test_name = test_name
self.platform = platform
def run(self, application_path):
result = True
path = root_path + application_path
arguments = ["--hide", "--test", "{}".format(self.test_name)]
try:
subprocess.run([path] + arguments, cwd=root_path)
except FileNotFoundError:
print("\t\t\t(Error) Couldn't find application ({})".format(path))
result = False
except:
print("\t\t\t(Error) Application error ({})".format(path))
result = False
return result
def test(self):
print("\t\t=== Test started: {} ===".format(self.test_name))
self.result = True
screenshot_path = tmp_path + self.platform + "/"
try:
shutil.move(outputs_path + self.test_name + image_ext, screenshot_path + self.test_name + image_ext)
except FileNotFoundError:
print("\t\t\t(Error) Couldn't find screenshot ({}), perhaps test crashed".format(outputs_path + self.test_name + image_ext))
self.result = False
return
if not test(self.test_name, screenshot_path):
self.result = False
if self.result:
print("\t\t=== Passed! ===")
else:
print("\t\t=== Failed. ===")
def passed(self):
return self.result
class WindowsSubtest(Subtest):
def __init__(self, test_name):
super().__init__(test_name, "Windows")
def run(self):
app_path = "{}vulkan_samples/bin/{}/{}/vulkan_samples.exe".format(build_path, build_config, platform.machine())
return super().run(app_path)
class UnixSubtest(Subtest):
def __init__(self, test_name, platform_type):
super().__init__(test_name, platform_type)
def run(self):
app_path = "{}vulkan_samples/bin/{}/{}/vulkan_samples".format(build_path, build_config, platform.machine())
return super().run(app_path)
class AndroidSubtest(Subtest):
def __init__(self, test_name):
super().__init__(test_name, "Android")
def run(self):
subprocess.run("adb shell am force-stop com.khronos.vulkan_samples")
subprocess.run(["adb", "shell", "am", "start", "-W", "-n", "com.khronos.vulkan_samples/com.khronos.vulkan_samples.BPSampleActivity", "-e", "test", "{0}".format(self.test_name)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
output = subprocess.check_output("adb shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp' | cut -d . -f 5 | cut -d ' ' -f 1")
activity = "".join(output.decode("utf-8").split())
timeout_counter = 0
while activity == "vulkan_samples" and timeout_counter <= android_timeout:
sleep(check_step)
timeout_counter += check_step
output = subprocess.check_output("adb shell \"dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp' | cut -d . -f 5 | cut -d ' ' -f 1\"")
activity = "".join(output.decode("utf-8").split())
if timeout_counter <= android_timeout:
subprocess.run(["adb", "pull", "/sdcard/Android/data/com.khronos.vulkan_samples/files/" + outputs_path + self.test_name + image_ext, root_path + outputs_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return True
else:
print("\t\t\t(Error) Timed out")
return False
def create_app(platform, test_name):
"""
@brief Creates a buildable and runnable test, returning it
@param platform An integer representing what platform the app should be built for
@param test_name The name of the test, used to create the app
@return A runnable application
"""
if platform == "Windows":
return WindowsSubtest(test_name)
elif platform in ["Linux", "Darwin"]:
return UnixSubtest(test_name, platform)
elif platform == "Android":
return AndroidSubtest(test_name)
else:
print("Error: cannot create subtest, cant find associated platform.")
exit(1)
def get_command(command):
"""
@brief Ensures command can be executed on each platform
@param command The commands name
@return A platform appropriate command
"""
if platform.system() == "Windows":
command += ".exe"
return command
def get_resolution(image):
"""
@brief Gets the width and height of a given image
@param image The path to the image relative to this script
@return A string denoting the resolution in the format (WxH)
"""
return subprocess.check_output([get_command("magick"), "identify", "-format", "\"%[fx:w]x%[fx:h]\"", image]).decode("utf-8")[1:-1]
def compare(metric, base_image, test_image, diff_image = "null:"):
"""
@brief Compares two images by their mean absolute error (changing the order of these parameters will change the contents of diff_image)
@param metric The type of image comparison you want to invoke
@param base_image The relative path to the image to base the test on
@param test_image The relative path to compare the base_image with
@param diff_image The relative path to the output image of the difference between the two images, default "null:"
@return A float clamped between 0 and 1 denoting how similar the images are (1 being identical, 0 being opposite)
"""
output = ""
try:
output = subprocess.check_output([get_command("magick"), "compare", "-metric", metric, base_image, test_image, diff_image], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
output = e.output
pass
output = output.decode("utf-8")
return max(0.0, min(1.0 - float(output[output.find("(")+1:output.find(")")]), 1.0))
def test(test_name, screenshot_path):
"""
@brief Tests each screenshot within the tmp/ folder against the goldtest, saving the results if it fails
@param test_name The name of the test, used to retrieve the respective goldtest image
@param screenshot_path The directory where to store screenshots
@return True if the image tests pass
"""
# Run test
result = False
image = test_name + image_ext
base_image = screenshot_path + image
test_image = root_path + "assets/gold/{0}/{1}.png".format(test_name, get_resolution(base_image))
if not os.path.isfile(test_image):
print("\t\t\t(Error) Resolution not supported, gold image not found ({})".format(test_image))
return False
diff_image = "{0}{1}-diff.png".format(screenshot_path, image[0:image.find(".")])
print("\t\t\t(Comparing images...) '{0}' with '{1}':".format(base_image, test_image), end = " ", flush = True)
similarity = compare(comparison_metric, base_image, test_image, diff_image)
print("{}%".format(100*math.floor(similarity*10000)/10000))
# Remove images if it is identical
if similarity >= threshold:
os.remove(base_image)
os.remove(diff_image)
result = True
return result
def execute(app):
print("\t=== Running {} on {} ===".format(app.test_name, app.platform))
if app.run():
app.test()
def main():
"""
@brief Runs the system test
"""
if test_android and not os.path.exists(tmp_path + "Android/"):
os.makedirs(tmp_path + "Android/")
if test_desktop and not os.path.exists(tmp_path + platform.system()):
os.makedirs(tmp_path + platform.system())
print("=== System Test started! ===")
results = []
# Create tests
apps = []
for test_name in sub_tests:
if test_android:
apps.append(create_app("Android", test_name))
if test_desktop:
apps.append(create_app(platform.system(), test_name))
# Run tests
if not multithread:
for app in apps:
if app:
execute(app)
else:
threads = []
for app in apps:
process = Thread(target=execute, args=[app])
process.start()
threads.append(process)
for thread in threads:
thread.join()
# Evaluate system test
passed = 0
failed = 0
for app in apps:
results.append(app.passed())
for result in results:
if result:
passed += 1
else:
failed += 1
if failed == 0:
print("=== Success: All tests passed! ===")
shutil.rmtree(tmp_path)
exit(0)
else:
print("=== Failed: {} passed - {} failed ===".format(passed, failed))
# If the screenshot directory is not empty, create an archive of the results
if os.listdir(tmp_path) is not None:
print("=== Archiving results into '{}' ===".format(shutil.make_archive(archive_path + "system_test" + "-" + datetime.datetime.now().strftime("%Y.%m.%d-%H.%M.%S"), 'zip', tmp_path)))
shutil.rmtree(tmp_path)
exit(1)
if __name__ == "__main__":
argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="A simple script that runs, screenshots, and tests your apps against a pre-existing gold")
argparser.add_argument("-B", "--build", required=True, help="relative path to the cmake build directory")
argparser.add_argument("-C", "--config", required=True, help="build configuration to use")
argparser.add_argument("-S", "--subtests", default=os.listdir(os.path.join(script_path, "sub_tests")), nargs="+", help="if set the specified sub tests will be run instead")
argparser.add_argument("-P", "--parallel", action='store_true', help="flag to deploy tests in parallel")
build_group = argparser.add_mutually_exclusive_group()
build_group.add_argument("-D", "--desktop", action='store_false', help="flag to only deploy tests on desktop")
build_group.add_argument("-A", "--android", action='store_false', help="flag to only deploy tests on android")
args = vars(argparser.parse_args())
build_path = args["build"]
build_config = args["config"]
sub_tests = args["subtests"]
test_desktop = args["android"]
test_android = args["desktop"]
multithread = args["parallel"]
if build_path[-1] != "/":
build_path += "/"
# Ensure right dependencies are installed before continuing
runnable = True
for dependency in dependencies:
if shutil.which(dependency) is None:
print("Error: Couldn't find {}, perhaps it is not installed".format(dependency))
runnable = False
if not runnable:
if platform.system() not in ["Linux", "Darwin"]:
exit(1)
else:
print("Unix based system detected. Allowing script to continue to account for aliasing. Please ensure you have the dependencies installed or aliased otherwise the script will fail.")
# If building for android check that a valid device is plugged in
if test_android:
try:
subprocess.check_output("adb get-state")
except:
print("Device not found, disabling Android testing")
test_android = False
else:
print("Device found!")
if multithread:
print("Android doesn't support multithreading, disabling!")
multithread = False
# Run script and handle keyboard interruption
try:
main()
except KeyboardInterrupt:
print("System Test Aborted")
try:
sys.exit(0)
except SystemExit:
os._exit(0)
|
upnp.py | import logging
import threading
from queue import Queue
from typing import Optional
try:
import miniupnpc
except ImportError:
pass
log = logging.getLogger(__name__)
class UPnP:
thread: Optional[threading.Thread] = None
queue: Queue = Queue()
def __init__(self):
def run():
try:
self.upnp = miniupnpc.UPnP()
self.upnp.discoverdelay = 30
self.upnp.discover()
self.upnp.selectigd()
keep_going = True
while keep_going:
msg = self.queue.get()
if msg[0] == "remap":
port = msg[1]
log.info(f"Attempting to enable UPnP (open up port {port})")
try:
self.upnp.deleteportmapping(port, "TCP")
except Exception as e:
log.info(f"Removal of previous portmapping failed. This does not indicate an error: {e}")
self.upnp.addportmapping(port, "TCP", self.upnp.lanaddr, port, "pipscoin", "")
log.info(
f"Port {port} opened with UPnP. lanaddr {self.upnp.lanaddr} "
f"external: {self.upnp.externalipaddress()}"
)
elif msg[0] == "release":
port = msg[1]
log.info(f"UPnP, releasing port {port}")
self.upnp.deleteportmapping(port, "TCP")
log.info(f"UPnP, Port {port} closed")
elif msg[0] == "shutdown":
keep_going = False
except Exception as e:
log.info(
"UPnP failed. This is not required to run pipscoin, it allows incoming connections from other peers."
)
log.info(e)
self.thread = threading.Thread(target=run)
self.thread.start()
def remap(self, port):
self.queue.put(("remap", port))
def release(self, port):
self.queue.put(("release", port))
def shutdown(self):
if not self.thread:
return
self.queue.put(("shutdown",))
log.info("UPnP, shutting down thread")
self.thread.join(5)
self.thread = None
# this is here just in case the UPnP object is destroyed non-gracefully,
# e.g. via an exception before the main thread can call shutdown()
def __del__(self):
self.shutdown()
|
test_logging.py | #!/usr/bin/env python
#
# Copyright 2001-2010 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""Test harness for the logging module. Run all tests.
Copyright (C) 2001-2010 Vinay Sajip. All Rights Reserved.
"""
import logging
import logging.handlers
import logging.config
import codecs
import cPickle
import cStringIO
import gc
import json
import os
import re
import select
import socket
from SocketServer import ThreadingTCPServer, StreamRequestHandler
import struct
import sys
import tempfile
from test.test_support import captured_stdout, run_with_locale, run_unittest
import textwrap
import unittest
import warnings
import weakref
try:
import threading
except ImportError:
threading = None
class BaseTest(unittest.TestCase):
"""Base class for logging tests."""
log_format = "%(name)s -> %(levelname)s: %(message)s"
expected_log_pat = r"^([\w.]+) -> ([\w]+): ([\d]+)$"
message_num = 0
def setUp(self):
"""Setup the default logging stream to an internal StringIO instance,
so that we can examine log output as we want."""
logger_dict = logging.getLogger().manager.loggerDict
logging._acquireLock()
try:
self.saved_handlers = logging._handlers.copy()
self.saved_handler_list = logging._handlerList[:]
self.saved_loggers = logger_dict.copy()
self.saved_level_names = logging._levelNames.copy()
finally:
logging._releaseLock()
# Set two unused loggers: one non-ASCII and one Unicode.
# This is to test correct operation when sorting existing
# loggers in the configuration code. See issue 8201.
logging.getLogger("\xab\xd7\xbb")
logging.getLogger(u"\u013f\u00d6\u0047")
self.root_logger = logging.getLogger("")
self.original_logging_level = self.root_logger.getEffectiveLevel()
self.stream = cStringIO.StringIO()
self.root_logger.setLevel(logging.DEBUG)
self.root_hdlr = logging.StreamHandler(self.stream)
self.root_formatter = logging.Formatter(self.log_format)
self.root_hdlr.setFormatter(self.root_formatter)
self.root_logger.addHandler(self.root_hdlr)
def tearDown(self):
"""Remove our logging stream, and restore the original logging
level."""
self.stream.close()
self.root_logger.removeHandler(self.root_hdlr)
while self.root_logger.handlers:
h = self.root_logger.handlers[0]
self.root_logger.removeHandler(h)
h.close()
self.root_logger.setLevel(self.original_logging_level)
logging._acquireLock()
try:
logging._levelNames.clear()
logging._levelNames.update(self.saved_level_names)
logging._handlers.clear()
logging._handlers.update(self.saved_handlers)
logging._handlerList[:] = self.saved_handler_list
loggerDict = logging.getLogger().manager.loggerDict
loggerDict.clear()
loggerDict.update(self.saved_loggers)
finally:
logging._releaseLock()
def assert_log_lines(self, expected_values, stream=None):
"""Match the collected log lines against the regular expression
self.expected_log_pat, and compare the extracted group values to
the expected_values list of tuples."""
stream = stream or self.stream
pat = re.compile(self.expected_log_pat)
try:
stream.reset()
actual_lines = stream.readlines()
except AttributeError:
# StringIO.StringIO lacks a reset() method.
actual_lines = stream.getvalue().splitlines()
self.assertEqual(len(actual_lines), len(expected_values))
for actual, expected in zip(actual_lines, expected_values):
match = pat.search(actual)
if not match:
self.fail("Log line does not match expected pattern:\n" +
actual)
self.assertEqual(tuple(match.groups()), expected)
s = stream.read()
if s:
self.fail("Remaining output at end of log stream:\n" + s)
def next_message(self):
"""Generate a message consisting solely of an auto-incrementing
integer."""
self.message_num += 1
return "%d" % self.message_num
class BuiltinLevelsTest(BaseTest):
"""Test builtin levels and their inheritance."""
def test_flat(self):
#Logging levels in a flat logger namespace.
m = self.next_message
ERR = logging.getLogger("ERR")
ERR.setLevel(logging.ERROR)
INF = logging.getLogger("INF")
INF.setLevel(logging.INFO)
DEB = logging.getLogger("DEB")
DEB.setLevel(logging.DEBUG)
# These should log.
ERR.log(logging.CRITICAL, m())
ERR.error(m())
INF.log(logging.CRITICAL, m())
INF.error(m())
INF.warn(m())
INF.info(m())
DEB.log(logging.CRITICAL, m())
DEB.error(m())
DEB.warn (m())
DEB.info (m())
DEB.debug(m())
# These should not log.
ERR.warn(m())
ERR.info(m())
ERR.debug(m())
INF.debug(m())
self.assert_log_lines([
('ERR', 'CRITICAL', '1'),
('ERR', 'ERROR', '2'),
('INF', 'CRITICAL', '3'),
('INF', 'ERROR', '4'),
('INF', 'WARNING', '5'),
('INF', 'INFO', '6'),
('DEB', 'CRITICAL', '7'),
('DEB', 'ERROR', '8'),
('DEB', 'WARNING', '9'),
('DEB', 'INFO', '10'),
('DEB', 'DEBUG', '11'),
])
def test_nested_explicit(self):
# Logging levels in a nested namespace, all explicitly set.
m = self.next_message
INF = logging.getLogger("INF")
INF.setLevel(logging.INFO)
INF_ERR = logging.getLogger("INF.ERR")
INF_ERR.setLevel(logging.ERROR)
# These should log.
INF_ERR.log(logging.CRITICAL, m())
INF_ERR.error(m())
# These should not log.
INF_ERR.warn(m())
INF_ERR.info(m())
INF_ERR.debug(m())
self.assert_log_lines([
('INF.ERR', 'CRITICAL', '1'),
('INF.ERR', 'ERROR', '2'),
])
def test_nested_inherited(self):
#Logging levels in a nested namespace, inherited from parent loggers.
m = self.next_message
INF = logging.getLogger("INF")
INF.setLevel(logging.INFO)
INF_ERR = logging.getLogger("INF.ERR")
INF_ERR.setLevel(logging.ERROR)
INF_UNDEF = logging.getLogger("INF.UNDEF")
INF_ERR_UNDEF = logging.getLogger("INF.ERR.UNDEF")
UNDEF = logging.getLogger("UNDEF")
# These should log.
INF_UNDEF.log(logging.CRITICAL, m())
INF_UNDEF.error(m())
INF_UNDEF.warn(m())
INF_UNDEF.info(m())
INF_ERR_UNDEF.log(logging.CRITICAL, m())
INF_ERR_UNDEF.error(m())
# These should not log.
INF_UNDEF.debug(m())
INF_ERR_UNDEF.warn(m())
INF_ERR_UNDEF.info(m())
INF_ERR_UNDEF.debug(m())
self.assert_log_lines([
('INF.UNDEF', 'CRITICAL', '1'),
('INF.UNDEF', 'ERROR', '2'),
('INF.UNDEF', 'WARNING', '3'),
('INF.UNDEF', 'INFO', '4'),
('INF.ERR.UNDEF', 'CRITICAL', '5'),
('INF.ERR.UNDEF', 'ERROR', '6'),
])
def test_nested_with_virtual_parent(self):
# Logging levels when some parent does not exist yet.
m = self.next_message
INF = logging.getLogger("INF")
GRANDCHILD = logging.getLogger("INF.BADPARENT.UNDEF")
CHILD = logging.getLogger("INF.BADPARENT")
INF.setLevel(logging.INFO)
# These should log.
GRANDCHILD.log(logging.FATAL, m())
GRANDCHILD.info(m())
CHILD.log(logging.FATAL, m())
CHILD.info(m())
# These should not log.
GRANDCHILD.debug(m())
CHILD.debug(m())
self.assert_log_lines([
('INF.BADPARENT.UNDEF', 'CRITICAL', '1'),
('INF.BADPARENT.UNDEF', 'INFO', '2'),
('INF.BADPARENT', 'CRITICAL', '3'),
('INF.BADPARENT', 'INFO', '4'),
])
class BasicFilterTest(BaseTest):
"""Test the bundled Filter class."""
def test_filter(self):
# Only messages satisfying the specified criteria pass through the
# filter.
filter_ = logging.Filter("spam.eggs")
handler = self.root_logger.handlers[0]
try:
handler.addFilter(filter_)
spam = logging.getLogger("spam")
spam_eggs = logging.getLogger("spam.eggs")
spam_eggs_fish = logging.getLogger("spam.eggs.fish")
spam_bakedbeans = logging.getLogger("spam.bakedbeans")
spam.info(self.next_message())
spam_eggs.info(self.next_message()) # Good.
spam_eggs_fish.info(self.next_message()) # Good.
spam_bakedbeans.info(self.next_message())
self.assert_log_lines([
('spam.eggs', 'INFO', '2'),
('spam.eggs.fish', 'INFO', '3'),
])
finally:
handler.removeFilter(filter_)
#
# First, we define our levels. There can be as many as you want - the only
# limitations are that they should be integers, the lowest should be > 0 and
# larger values mean less information being logged. If you need specific
# level values which do not fit into these limitations, you can use a
# mapping dictionary to convert between your application levels and the
# logging system.
#
SILENT = 120
TACITURN = 119
TERSE = 118
EFFUSIVE = 117
SOCIABLE = 116
VERBOSE = 115
TALKATIVE = 114
GARRULOUS = 113
CHATTERBOX = 112
BORING = 111
LEVEL_RANGE = range(BORING, SILENT + 1)
#
# Next, we define names for our levels. You don't need to do this - in which
# case the system will use "Level n" to denote the text for the level.
#
my_logging_levels = {
SILENT : 'Silent',
TACITURN : 'Taciturn',
TERSE : 'Terse',
EFFUSIVE : 'Effusive',
SOCIABLE : 'Sociable',
VERBOSE : 'Verbose',
TALKATIVE : 'Talkative',
GARRULOUS : 'Garrulous',
CHATTERBOX : 'Chatterbox',
BORING : 'Boring',
}
class GarrulousFilter(logging.Filter):
"""A filter which blocks garrulous messages."""
def filter(self, record):
return record.levelno != GARRULOUS
class VerySpecificFilter(logging.Filter):
"""A filter which blocks sociable and taciturn messages."""
def filter(self, record):
return record.levelno not in [SOCIABLE, TACITURN]
class CustomLevelsAndFiltersTest(BaseTest):
"""Test various filtering possibilities with custom logging levels."""
# Skip the logger name group.
expected_log_pat = r"^[\w.]+ -> ([\w]+): ([\d]+)$"
def setUp(self):
BaseTest.setUp(self)
for k, v in my_logging_levels.items():
logging.addLevelName(k, v)
def log_at_all_levels(self, logger):
for lvl in LEVEL_RANGE:
logger.log(lvl, self.next_message())
def test_logger_filter(self):
# Filter at logger level.
self.root_logger.setLevel(VERBOSE)
# Levels >= 'Verbose' are good.
self.log_at_all_levels(self.root_logger)
self.assert_log_lines([
('Verbose', '5'),
('Sociable', '6'),
('Effusive', '7'),
('Terse', '8'),
('Taciturn', '9'),
('Silent', '10'),
])
def test_handler_filter(self):
# Filter at handler level.
self.root_logger.handlers[0].setLevel(SOCIABLE)
try:
# Levels >= 'Sociable' are good.
self.log_at_all_levels(self.root_logger)
self.assert_log_lines([
('Sociable', '6'),
('Effusive', '7'),
('Terse', '8'),
('Taciturn', '9'),
('Silent', '10'),
])
finally:
self.root_logger.handlers[0].setLevel(logging.NOTSET)
def test_specific_filters(self):
# Set a specific filter object on the handler, and then add another
# filter object on the logger itself.
handler = self.root_logger.handlers[0]
specific_filter = None
garr = GarrulousFilter()
handler.addFilter(garr)
try:
self.log_at_all_levels(self.root_logger)
first_lines = [
# Notice how 'Garrulous' is missing
('Boring', '1'),
('Chatterbox', '2'),
('Talkative', '4'),
('Verbose', '5'),
('Sociable', '6'),
('Effusive', '7'),
('Terse', '8'),
('Taciturn', '9'),
('Silent', '10'),
]
self.assert_log_lines(first_lines)
specific_filter = VerySpecificFilter()
self.root_logger.addFilter(specific_filter)
self.log_at_all_levels(self.root_logger)
self.assert_log_lines(first_lines + [
# Not only 'Garrulous' is still missing, but also 'Sociable'
# and 'Taciturn'
('Boring', '11'),
('Chatterbox', '12'),
('Talkative', '14'),
('Verbose', '15'),
('Effusive', '17'),
('Terse', '18'),
('Silent', '20'),
])
finally:
if specific_filter:
self.root_logger.removeFilter(specific_filter)
handler.removeFilter(garr)
class MemoryHandlerTest(BaseTest):
"""Tests for the MemoryHandler."""
# Do not bother with a logger name group.
expected_log_pat = r"^[\w.]+ -> ([\w]+): ([\d]+)$"
def setUp(self):
BaseTest.setUp(self)
self.mem_hdlr = logging.handlers.MemoryHandler(10, logging.WARNING,
self.root_hdlr)
self.mem_logger = logging.getLogger('mem')
self.mem_logger.propagate = 0
self.mem_logger.addHandler(self.mem_hdlr)
def tearDown(self):
self.mem_hdlr.close()
BaseTest.tearDown(self)
def test_flush(self):
# The memory handler flushes to its target handler based on specific
# criteria (message count and message level).
self.mem_logger.debug(self.next_message())
self.assert_log_lines([])
self.mem_logger.info(self.next_message())
self.assert_log_lines([])
# This will flush because the level is >= logging.WARNING
self.mem_logger.warn(self.next_message())
lines = [
('DEBUG', '1'),
('INFO', '2'),
('WARNING', '3'),
]
self.assert_log_lines(lines)
for n in (4, 14):
for i in range(9):
self.mem_logger.debug(self.next_message())
self.assert_log_lines(lines)
# This will flush because it's the 10th message since the last
# flush.
self.mem_logger.debug(self.next_message())
lines = lines + [('DEBUG', str(i)) for i in range(n, n + 10)]
self.assert_log_lines(lines)
self.mem_logger.debug(self.next_message())
self.assert_log_lines(lines)
class ExceptionFormatter(logging.Formatter):
"""A special exception formatter."""
def formatException(self, ei):
return "Got a [%s]" % ei[0].__name__
class ConfigFileTest(BaseTest):
"""Reading logging config from a .ini-style config file."""
expected_log_pat = r"^([\w]+) \+\+ ([\w]+)$"
# config0 is a standard configuration.
config0 = """
[loggers]
keys=root
[handlers]
keys=hand1
[formatters]
keys=form1
[logger_root]
level=WARNING
handlers=hand1
[handler_hand1]
class=StreamHandler
level=NOTSET
formatter=form1
args=(sys.stdout,)
[formatter_form1]
format=%(levelname)s ++ %(message)s
datefmt=
"""
# config1 adds a little to the standard configuration.
config1 = """
[loggers]
keys=root,parser
[handlers]
keys=hand1
[formatters]
keys=form1
[logger_root]
level=WARNING
handlers=
[logger_parser]
level=DEBUG
handlers=hand1
propagate=1
qualname=compiler.parser
[handler_hand1]
class=StreamHandler
level=NOTSET
formatter=form1
args=(sys.stdout,)
[formatter_form1]
format=%(levelname)s ++ %(message)s
datefmt=
"""
# config2 has a subtle configuration error that should be reported
config2 = config1.replace("sys.stdout", "sys.stbout")
# config3 has a less subtle configuration error
config3 = config1.replace("formatter=form1", "formatter=misspelled_name")
# config4 specifies a custom formatter class to be loaded
config4 = """
[loggers]
keys=root
[handlers]
keys=hand1
[formatters]
keys=form1
[logger_root]
level=NOTSET
handlers=hand1
[handler_hand1]
class=StreamHandler
level=NOTSET
formatter=form1
args=(sys.stdout,)
[formatter_form1]
class=""" + __name__ + """.ExceptionFormatter
format=%(levelname)s:%(name)s:%(message)s
datefmt=
"""
# config5 specifies a custom handler class to be loaded
config5 = config1.replace('class=StreamHandler', 'class=logging.StreamHandler')
# config6 uses ', ' delimiters in the handlers and formatters sections
config6 = """
[loggers]
keys=root,parser
[handlers]
keys=hand1, hand2
[formatters]
keys=form1, form2
[logger_root]
level=WARNING
handlers=
[logger_parser]
level=DEBUG
handlers=hand1
propagate=1
qualname=compiler.parser
[handler_hand1]
class=StreamHandler
level=NOTSET
formatter=form1
args=(sys.stdout,)
[handler_hand2]
class=StreamHandler
level=NOTSET
formatter=form1
args=(sys.stderr,)
[formatter_form1]
format=%(levelname)s ++ %(message)s
datefmt=
[formatter_form2]
format=%(message)s
datefmt=
"""
def apply_config(self, conf):
file = cStringIO.StringIO(textwrap.dedent(conf))
logging.config.fileConfig(file)
def test_config0_ok(self):
# A simple config file which overrides the default settings.
with captured_stdout() as output:
self.apply_config(self.config0)
logger = logging.getLogger()
# Won't output anything
logger.info(self.next_message())
# Outputs a message
logger.error(self.next_message())
self.assert_log_lines([
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config1_ok(self, config=config1):
# A config file defining a sub-parser as well.
with captured_stdout() as output:
self.apply_config(config)
logger = logging.getLogger("compiler.parser")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config2_failure(self):
# A simple config file which overrides the default settings.
self.assertRaises(StandardError, self.apply_config, self.config2)
def test_config3_failure(self):
# A simple config file which overrides the default settings.
self.assertRaises(StandardError, self.apply_config, self.config3)
def test_config4_ok(self):
# A config file specifying a custom formatter class.
with captured_stdout() as output:
self.apply_config(self.config4)
logger = logging.getLogger()
try:
raise RuntimeError()
except RuntimeError:
logging.exception("just testing")
sys.stdout.seek(0)
self.assertEqual(output.getvalue(),
"ERROR:root:just testing\nGot a [RuntimeError]\n")
# Original logger output is empty
self.assert_log_lines([])
def test_config5_ok(self):
self.test_config1_ok(config=self.config5)
def test_config6_ok(self):
self.test_config1_ok(config=self.config6)
class LogRecordStreamHandler(StreamRequestHandler):
"""Handler for a streaming logging request. It saves the log message in the
TCP server's 'log_output' attribute."""
TCP_LOG_END = "!!!END!!!"
def handle(self):
"""Handle multiple requests - each expected to be of 4-byte length,
followed by the LogRecord in pickle format. Logs the record
according to whatever policy is configured locally."""
while True:
chunk = self.connection.recv(4)
if len(chunk) < 4:
break
slen = struct.unpack(">L", chunk)[0]
chunk = self.connection.recv(slen)
while len(chunk) < slen:
chunk = chunk + self.connection.recv(slen - len(chunk))
obj = self.unpickle(chunk)
record = logging.makeLogRecord(obj)
self.handle_log_record(record)
def unpickle(self, data):
return cPickle.loads(data)
def handle_log_record(self, record):
# If the end-of-messages sentinel is seen, tell the server to
# terminate.
if self.TCP_LOG_END in record.msg:
self.server.abort = 1
return
self.server.log_output += record.msg + "\n"
class LogRecordSocketReceiver(ThreadingTCPServer):
"""A simple-minded TCP socket-based logging receiver suitable for test
purposes."""
allow_reuse_address = 1
log_output = ""
def __init__(self, host='localhost',
port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
handler=LogRecordStreamHandler):
ThreadingTCPServer.__init__(self, (host, port), handler)
self.abort = False
self.timeout = 0.1
self.finished = threading.Event()
def serve_until_stopped(self):
while not self.abort:
rd, wr, ex = select.select([self.socket.fileno()], [], [],
self.timeout)
if rd:
self.handle_request()
# Notify the main thread that we're about to exit
self.finished.set()
# close the listen socket
self.server_close()
@unittest.skipUnless(threading, 'Threading required for this test.')
class SocketHandlerTest(BaseTest):
"""Test for SocketHandler objects."""
def setUp(self):
"""Set up a TCP server to receive log messages, and a SocketHandler
pointing to that server's address and port."""
BaseTest.setUp(self)
self.tcpserver = LogRecordSocketReceiver(port=0)
self.port = self.tcpserver.socket.getsockname()[1]
self.threads = [
threading.Thread(target=self.tcpserver.serve_until_stopped)]
for thread in self.threads:
thread.start()
self.sock_hdlr = logging.handlers.SocketHandler('localhost', self.port)
self.sock_hdlr.setFormatter(self.root_formatter)
self.root_logger.removeHandler(self.root_logger.handlers[0])
self.root_logger.addHandler(self.sock_hdlr)
def tearDown(self):
"""Shutdown the TCP server."""
try:
self.tcpserver.abort = True
del self.tcpserver
self.root_logger.removeHandler(self.sock_hdlr)
self.sock_hdlr.close()
for thread in self.threads:
thread.join(2.0)
finally:
BaseTest.tearDown(self)
def get_output(self):
"""Get the log output as received by the TCP server."""
# Signal the TCP receiver and wait for it to terminate.
self.root_logger.critical(LogRecordStreamHandler.TCP_LOG_END)
self.tcpserver.finished.wait(2.0)
return self.tcpserver.log_output
def test_output(self):
# The log message sent to the SocketHandler is properly received.
logger = logging.getLogger("tcp")
logger.error("spam")
logger.debug("eggs")
self.assertEqual(self.get_output(), "spam\neggs\n")
class MemoryTest(BaseTest):
"""Test memory persistence of logger objects."""
def setUp(self):
"""Create a dict to remember potentially destroyed objects."""
BaseTest.setUp(self)
self._survivors = {}
def _watch_for_survival(self, *args):
"""Watch the given objects for survival, by creating weakrefs to
them."""
for obj in args:
key = id(obj), repr(obj)
self._survivors[key] = weakref.ref(obj)
def _assertTruesurvival(self):
"""Assert that all objects watched for survival have survived."""
# Trigger cycle breaking.
gc.collect()
dead = []
for (id_, repr_), ref in self._survivors.items():
if ref() is None:
dead.append(repr_)
if dead:
self.fail("%d objects should have survived "
"but have been destroyed: %s" % (len(dead), ", ".join(dead)))
def test_persistent_loggers(self):
# Logger objects are persistent and retain their configuration, even
# if visible references are destroyed.
self.root_logger.setLevel(logging.INFO)
foo = logging.getLogger("foo")
self._watch_for_survival(foo)
foo.setLevel(logging.DEBUG)
self.root_logger.debug(self.next_message())
foo.debug(self.next_message())
self.assert_log_lines([
('foo', 'DEBUG', '2'),
])
del foo
# foo has survived.
self._assertTruesurvival()
# foo has retained its settings.
bar = logging.getLogger("foo")
bar.debug(self.next_message())
self.assert_log_lines([
('foo', 'DEBUG', '2'),
('foo', 'DEBUG', '3'),
])
class EncodingTest(BaseTest):
def test_encoding_plain_file(self):
# In Python 2.x, a plain file object is treated as having no encoding.
log = logging.getLogger("test")
fn = tempfile.mktemp(".log")
# the non-ascii data we write to the log.
data = "foo\x80"
try:
handler = logging.FileHandler(fn)
log.addHandler(handler)
try:
# write non-ascii data to the log.
log.warning(data)
finally:
log.removeHandler(handler)
handler.close()
# check we wrote exactly those bytes, ignoring trailing \n etc
f = open(fn)
try:
self.assertEqual(f.read().rstrip(), data)
finally:
f.close()
finally:
if os.path.isfile(fn):
os.remove(fn)
def test_encoding_cyrillic_unicode(self):
log = logging.getLogger("test")
#Get a message in Unicode: Do svidanya in Cyrillic (meaning goodbye)
message = u'\u0434\u043e \u0441\u0432\u0438\u0434\u0430\u043d\u0438\u044f'
#Ensure it's written in a Cyrillic encoding
writer_class = codecs.getwriter('cp1251')
writer_class.encoding = 'cp1251'
stream = cStringIO.StringIO()
writer = writer_class(stream, 'strict')
handler = logging.StreamHandler(writer)
log.addHandler(handler)
try:
log.warning(message)
finally:
log.removeHandler(handler)
handler.close()
# check we wrote exactly those bytes, ignoring trailing \n etc
s = stream.getvalue()
#Compare against what the data should be when encoded in CP-1251
self.assertEqual(s, '\xe4\xee \xf1\xe2\xe8\xe4\xe0\xed\xe8\xff\n')
class WarningsTest(BaseTest):
def test_warnings(self):
with warnings.catch_warnings():
logging.captureWarnings(True)
try:
warnings.filterwarnings("always", category=UserWarning)
file = cStringIO.StringIO()
h = logging.StreamHandler(file)
logger = logging.getLogger("py.warnings")
logger.addHandler(h)
warnings.warn("I'm warning you...")
logger.removeHandler(h)
s = file.getvalue()
h.close()
self.assertTrue(s.find("UserWarning: I'm warning you...\n") > 0)
#See if an explicit file uses the original implementation
file = cStringIO.StringIO()
warnings.showwarning("Explicit", UserWarning, "dummy.py", 42,
file, "Dummy line")
s = file.getvalue()
file.close()
self.assertEqual(s,
"dummy.py:42: UserWarning: Explicit\n Dummy line\n")
finally:
logging.captureWarnings(False)
def formatFunc(format, datefmt=None):
return logging.Formatter(format, datefmt)
def handlerFunc():
return logging.StreamHandler()
class CustomHandler(logging.StreamHandler):
pass
class ConfigDictTest(BaseTest):
"""Reading logging config from a dictionary."""
expected_log_pat = r"^([\w]+) \+\+ ([\w]+)$"
# config0 is a standard configuration.
config0 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'root' : {
'level' : 'WARNING',
'handlers' : ['hand1'],
},
}
# config1 adds a little to the standard configuration.
config1 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# config2 has a subtle configuration error that should be reported
config2 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdbout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
#As config1 but with a misspelt level on a handler
config2a = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NTOSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
#As config1 but with a misspelt level on a logger
config2b = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WRANING',
},
}
# config3 has a less subtle configuration error
config3 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'misspelled_name',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# config4 specifies a custom formatter class to be loaded
config4 = {
'version': 1,
'formatters': {
'form1' : {
'()' : __name__ + '.ExceptionFormatter',
'format' : '%(levelname)s:%(name)s:%(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'root' : {
'level' : 'NOTSET',
'handlers' : ['hand1'],
},
}
# As config4 but using an actual callable rather than a string
config4a = {
'version': 1,
'formatters': {
'form1' : {
'()' : ExceptionFormatter,
'format' : '%(levelname)s:%(name)s:%(message)s',
},
'form2' : {
'()' : __name__ + '.formatFunc',
'format' : '%(levelname)s:%(name)s:%(message)s',
},
'form3' : {
'()' : formatFunc,
'format' : '%(levelname)s:%(name)s:%(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
'hand2' : {
'()' : handlerFunc,
},
},
'root' : {
'level' : 'NOTSET',
'handlers' : ['hand1'],
},
}
# config5 specifies a custom handler class to be loaded
config5 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : __name__ + '.CustomHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
# config6 specifies a custom handler class to be loaded
# but has bad arguments
config6 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : __name__ + '.CustomHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
'9' : 'invalid parameter name',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
#config 7 does not define compiler.parser but defines compiler.lexer
#so compiler.parser should be disabled after applying it
config7 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.lexer' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
config8 = {
'version': 1,
'disable_existing_loggers' : False,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
'compiler.lexer' : {
},
},
'root' : {
'level' : 'WARNING',
},
}
config9 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'WARNING',
'stream' : 'ext://sys.stdout',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'WARNING',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'NOTSET',
},
}
config9a = {
'version': 1,
'incremental' : True,
'handlers' : {
'hand1' : {
'level' : 'WARNING',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'INFO',
},
},
}
config9b = {
'version': 1,
'incremental' : True,
'handlers' : {
'hand1' : {
'level' : 'INFO',
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'INFO',
},
},
}
#As config1 but with a filter added
config10 = {
'version': 1,
'formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'filters' : {
'filt1' : {
'name' : 'compiler.parser',
},
},
'handlers' : {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
'filters' : ['filt1'],
},
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'filters' : ['filt1'],
},
},
'root' : {
'level' : 'WARNING',
'handlers' : ['hand1'],
},
}
#As config1 but using cfg:// references
config11 = {
'version': 1,
'true_formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handler_configs': {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'formatters' : 'cfg://true_formatters',
'handlers' : {
'hand1' : 'cfg://handler_configs[hand1]',
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
#As config11 but missing the version key
config12 = {
'true_formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handler_configs': {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'formatters' : 'cfg://true_formatters',
'handlers' : {
'hand1' : 'cfg://handler_configs[hand1]',
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
#As config11 but using an unsupported version
config13 = {
'version': 2,
'true_formatters': {
'form1' : {
'format' : '%(levelname)s ++ %(message)s',
},
},
'handler_configs': {
'hand1' : {
'class' : 'logging.StreamHandler',
'formatter' : 'form1',
'level' : 'NOTSET',
'stream' : 'ext://sys.stdout',
},
},
'formatters' : 'cfg://true_formatters',
'handlers' : {
'hand1' : 'cfg://handler_configs[hand1]',
},
'loggers' : {
'compiler.parser' : {
'level' : 'DEBUG',
'handlers' : ['hand1'],
},
},
'root' : {
'level' : 'WARNING',
},
}
def apply_config(self, conf):
logging.config.dictConfig(conf)
def test_config0_ok(self):
# A simple config which overrides the default settings.
with captured_stdout() as output:
self.apply_config(self.config0)
logger = logging.getLogger()
# Won't output anything
logger.info(self.next_message())
# Outputs a message
logger.error(self.next_message())
self.assert_log_lines([
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config1_ok(self, config=config1):
# A config defining a sub-parser as well.
with captured_stdout() as output:
self.apply_config(config)
logger = logging.getLogger("compiler.parser")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config2_failure(self):
# A simple config which overrides the default settings.
self.assertRaises(StandardError, self.apply_config, self.config2)
def test_config2a_failure(self):
# A simple config which overrides the default settings.
self.assertRaises(StandardError, self.apply_config, self.config2a)
def test_config2b_failure(self):
# A simple config which overrides the default settings.
self.assertRaises(StandardError, self.apply_config, self.config2b)
def test_config3_failure(self):
# A simple config which overrides the default settings.
self.assertRaises(StandardError, self.apply_config, self.config3)
def test_config4_ok(self):
# A config specifying a custom formatter class.
with captured_stdout() as output:
self.apply_config(self.config4)
#logger = logging.getLogger()
try:
raise RuntimeError()
except RuntimeError:
logging.exception("just testing")
sys.stdout.seek(0)
self.assertEqual(output.getvalue(),
"ERROR:root:just testing\nGot a [RuntimeError]\n")
# Original logger output is empty
self.assert_log_lines([])
def test_config4a_ok(self):
# A config specifying a custom formatter class.
with captured_stdout() as output:
self.apply_config(self.config4a)
#logger = logging.getLogger()
try:
raise RuntimeError()
except RuntimeError:
logging.exception("just testing")
sys.stdout.seek(0)
self.assertEqual(output.getvalue(),
"ERROR:root:just testing\nGot a [RuntimeError]\n")
# Original logger output is empty
self.assert_log_lines([])
def test_config5_ok(self):
self.test_config1_ok(config=self.config5)
def test_config6_failure(self):
self.assertRaises(StandardError, self.apply_config, self.config6)
def test_config7_ok(self):
with captured_stdout() as output:
self.apply_config(self.config1)
logger = logging.getLogger("compiler.parser")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
with captured_stdout() as output:
self.apply_config(self.config7)
logger = logging.getLogger("compiler.parser")
self.assertTrue(logger.disabled)
logger = logging.getLogger("compiler.lexer")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '3'),
('ERROR', '4'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
#Same as test_config_7_ok but don't disable old loggers.
def test_config_8_ok(self):
with captured_stdout() as output:
self.apply_config(self.config1)
logger = logging.getLogger("compiler.parser")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
with captured_stdout() as output:
self.apply_config(self.config8)
logger = logging.getLogger("compiler.parser")
self.assertFalse(logger.disabled)
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
logger = logging.getLogger("compiler.lexer")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '3'),
('ERROR', '4'),
('INFO', '5'),
('ERROR', '6'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
def test_config_9_ok(self):
with captured_stdout() as output:
self.apply_config(self.config9)
logger = logging.getLogger("compiler.parser")
#Nothing will be output since both handler and logger are set to WARNING
logger.info(self.next_message())
self.assert_log_lines([], stream=output)
self.apply_config(self.config9a)
#Nothing will be output since both handler is still set to WARNING
logger.info(self.next_message())
self.assert_log_lines([], stream=output)
self.apply_config(self.config9b)
#Message should now be output
logger.info(self.next_message())
self.assert_log_lines([
('INFO', '3'),
], stream=output)
def test_config_10_ok(self):
with captured_stdout() as output:
self.apply_config(self.config10)
logger = logging.getLogger("compiler.parser")
logger.warning(self.next_message())
logger = logging.getLogger('compiler')
#Not output, because filtered
logger.warning(self.next_message())
logger = logging.getLogger('compiler.lexer')
#Not output, because filtered
logger.warning(self.next_message())
logger = logging.getLogger("compiler.parser.codegen")
#Output, as not filtered
logger.error(self.next_message())
self.assert_log_lines([
('WARNING', '1'),
('ERROR', '4'),
], stream=output)
def test_config11_ok(self):
self.test_config1_ok(self.config11)
def test_config12_failure(self):
self.assertRaises(StandardError, self.apply_config, self.config12)
def test_config13_failure(self):
self.assertRaises(StandardError, self.apply_config, self.config13)
@unittest.skipUnless(threading, 'listen() needs threading to work')
def setup_via_listener(self, text):
# Ask for a randomly assigned port (by using port 0)
t = logging.config.listen(0)
t.start()
t.ready.wait()
# Now get the port allocated
port = t.port
t.ready.clear()
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2.0)
sock.connect(('localhost', port))
slen = struct.pack('>L', len(text))
s = slen + text
sentsofar = 0
left = len(s)
while left > 0:
sent = sock.send(s[sentsofar:])
sentsofar += sent
left -= sent
sock.close()
finally:
t.ready.wait(2.0)
logging.config.stopListening()
t.join(2.0)
def test_listen_config_10_ok(self):
with captured_stdout() as output:
self.setup_via_listener(json.dumps(self.config10))
logger = logging.getLogger("compiler.parser")
logger.warning(self.next_message())
logger = logging.getLogger('compiler')
#Not output, because filtered
logger.warning(self.next_message())
logger = logging.getLogger('compiler.lexer')
#Not output, because filtered
logger.warning(self.next_message())
logger = logging.getLogger("compiler.parser.codegen")
#Output, as not filtered
logger.error(self.next_message())
self.assert_log_lines([
('WARNING', '1'),
('ERROR', '4'),
], stream=output)
def test_listen_config_1_ok(self):
with captured_stdout() as output:
self.setup_via_listener(textwrap.dedent(ConfigFileTest.config1))
logger = logging.getLogger("compiler.parser")
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
self.assert_log_lines([
('INFO', '1'),
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
self.assert_log_lines([])
class ManagerTest(BaseTest):
def test_manager_loggerclass(self):
logged = []
class MyLogger(logging.Logger):
def _log(self, level, msg, args, exc_info=None, extra=None):
logged.append(msg)
man = logging.Manager(None)
self.assertRaises(TypeError, man.setLoggerClass, int)
man.setLoggerClass(MyLogger)
logger = man.getLogger('test')
logger.warning('should appear in logged')
logging.warning('should not appear in logged')
self.assertEqual(logged, ['should appear in logged'])
class ChildLoggerTest(BaseTest):
def test_child_loggers(self):
r = logging.getLogger()
l1 = logging.getLogger('abc')
l2 = logging.getLogger('def.ghi')
c1 = r.getChild('xyz')
c2 = r.getChild('uvw.xyz')
self.assertTrue(c1 is logging.getLogger('xyz'))
self.assertTrue(c2 is logging.getLogger('uvw.xyz'))
c1 = l1.getChild('def')
c2 = c1.getChild('ghi')
c3 = l1.getChild('def.ghi')
self.assertTrue(c1 is logging.getLogger('abc.def'))
self.assertTrue(c2 is logging.getLogger('abc.def.ghi'))
self.assertTrue(c2 is c3)
# Set the locale to the platform-dependent default. I have no idea
# why the test does this, but in any case we save the current locale
# first and restore it at the end.
@run_with_locale('LC_ALL', '')
def test_main():
run_unittest(BuiltinLevelsTest, BasicFilterTest,
CustomLevelsAndFiltersTest, MemoryHandlerTest,
ConfigFileTest, SocketHandlerTest, MemoryTest,
EncodingTest, WarningsTest, ConfigDictTest, ManagerTest,
ChildLoggerTest)
if __name__ == "__main__":
test_main()
|
callbacks_test.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Keras callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import csv
import json
import os
import re
import shutil
import sys
import threading
import time
import unittest
from absl.testing import parameterized
import numpy as np
from tensorflow.core.framework import summary_pb2
from tensorflow.python import keras
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.framework import random_seed
from tensorflow.python.keras import keras_parameterized
from tensorflow.python.keras import testing_utils
from tensorflow.python.keras.engine import base_layer
from tensorflow.python.keras.engine import sequential
from tensorflow.python.keras.optimizer_v2 import gradient_descent
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import summary_ops_v2
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.summary import summary_iterator
from tensorflow.python.training import adam
from tensorflow.python.training import checkpoint_management
from tensorflow.python.keras.optimizer_v2 import learning_rate_schedule
try:
import h5py # pylint:disable=g-import-not-at-top
except ImportError:
h5py = None
try:
import requests # pylint:disable=g-import-not-at-top
except ImportError:
requests = None
TRAIN_SAMPLES = 10
TEST_SAMPLES = 10
NUM_CLASSES = 2
INPUT_DIM = 3
NUM_HIDDEN = 5
BATCH_SIZE = 5
class Counter(keras.callbacks.Callback):
"""Counts the number of times each callback method was run.
Attributes:
method_counts: dict. Contains the counts of time each callback method was
run.
"""
def __init__(self):
self.method_counts = collections.defaultdict(int)
methods_to_count = [
'on_batch_begin', 'on_batch_end', 'on_epoch_begin', 'on_epoch_end',
'on_predict_batch_begin', 'on_predict_batch_end', 'on_predict_begin',
'on_predict_end', 'on_test_batch_begin', 'on_test_batch_end',
'on_test_begin', 'on_test_end', 'on_train_batch_begin',
'on_train_batch_end', 'on_train_begin', 'on_train_end'
]
for method_name in methods_to_count:
setattr(self, method_name,
self.wrap_with_counts(method_name, getattr(self, method_name)))
def wrap_with_counts(self, method_name, method):
def _call_and_count(*args, **kwargs):
self.method_counts[method_name] += 1
return method(*args, **kwargs)
return _call_and_count
def _get_numpy():
return np.ones((10, 10)), np.ones((10, 1))
def _get_sequence():
class MySequence(keras.utils.data_utils.Sequence):
def __getitem__(self, _):
return np.ones((2, 10)), np.ones((2, 1))
def __len__(self):
return 5
return MySequence(), None
@keras_parameterized.run_with_all_model_types
@keras_parameterized.run_all_keras_modes
class CallbackCountsTest(keras_parameterized.TestCase):
def _check_counts(self, counter, expected_counts):
"""Checks that the counts registered by `counter` are those expected."""
for method_name, expected_count in expected_counts.items():
self.assertEqual(
counter.method_counts[method_name],
expected_count,
msg='For method {}: expected {}, got: {}'.format(
method_name, expected_count, counter.method_counts[method_name]))
def _get_model(self):
layers = [
keras.layers.Dense(10, activation='relu'),
keras.layers.Dense(1, activation='sigmoid')
]
model = testing_utils.get_model_from_layers(layers, input_shape=(10,))
model.compile(
adam.AdamOptimizer(0.001),
'binary_crossentropy',
run_eagerly=testing_utils.should_run_eagerly(),
experimental_run_tf_function=testing_utils.should_run_tf_function())
return model
@parameterized.named_parameters(('with_numpy', _get_numpy()),
('with_sequence', _get_sequence()))
def test_callback_hooks_are_called_in_fit(self, data):
x, y = data
val_x, val_y = np.ones((4, 10)), np.ones((4, 1))
is_sequence = isinstance(x, keras.utils.data_utils.Sequence)
model = self._get_model()
counter = Counter()
model.fit(
x,
y,
validation_data=(val_x, val_y),
batch_size=2 if not is_sequence else None,
steps_per_epoch=5 if is_sequence else None,
epochs=5,
callbacks=[counter])
self._check_counts(
counter, {
'on_batch_begin': 25,
'on_batch_end': 25,
'on_epoch_begin': 5,
'on_epoch_end': 5,
'on_predict_batch_begin': 0,
'on_predict_batch_end': 0,
'on_predict_begin': 0,
'on_predict_end': 0,
'on_test_batch_begin': 10,
'on_test_batch_end': 10,
'on_test_begin': 5,
'on_test_end': 5,
'on_train_batch_begin': 25,
'on_train_batch_end': 25,
'on_train_begin': 1,
'on_train_end': 1
})
@parameterized.named_parameters(('with_numpy', _get_numpy()),
('with_sequence', _get_sequence()))
def test_callback_hooks_are_called_in_evaluate(self, data):
x, y = data
is_sequence = isinstance(x, keras.utils.data_utils.Sequence)
model = self._get_model()
counter = Counter()
model.evaluate(
x,
y,
batch_size=2 if not is_sequence else None,
steps=5 if is_sequence else None,
callbacks=[counter])
self._check_counts(
counter, {
'on_test_batch_begin': 5,
'on_test_batch_end': 5,
'on_test_begin': 1,
'on_test_end': 1
})
@parameterized.named_parameters(('with_numpy', _get_numpy()),
('with_sequence', _get_sequence()))
def test_callback_hooks_are_called_in_predict(self, data):
x = data[0]
is_sequence = isinstance(x, keras.utils.data_utils.Sequence)
model = self._get_model()
counter = Counter()
model.predict(
x,
batch_size=2 if not is_sequence else None,
steps=5 if is_sequence else None,
callbacks=[counter])
self._check_counts(
counter, {
'on_predict_batch_begin': 5,
'on_predict_batch_end': 5,
'on_predict_begin': 1,
'on_predict_end': 1
})
def test_callback_list_methods(self):
counter = Counter()
callback_list = keras.callbacks.CallbackList([counter])
batch = 0
callback_list.on_test_batch_begin(batch)
callback_list.on_test_batch_end(batch)
callback_list.on_predict_batch_begin(batch)
callback_list.on_predict_batch_end(batch)
self._check_counts(
counter, {
'on_test_batch_begin': 1,
'on_test_batch_end': 1,
'on_predict_batch_begin': 1,
'on_predict_batch_end': 1
})
class KerasCallbacksTest(keras_parameterized.TestCase):
def _get_model(self, input_shape=None):
layers = [
keras.layers.Dense(3, activation='relu'),
keras.layers.Dense(2, activation='softmax')
]
model = testing_utils.get_model_from_layers(layers, input_shape=input_shape)
model.compile(
loss='mse',
optimizer='rmsprop',
metrics=[keras.metrics.CategoricalAccuracy(name='my_acc')],
run_eagerly=testing_utils.should_run_eagerly(),
experimental_run_tf_function=testing_utils.should_run_tf_function())
return model
@keras_parameterized.run_with_all_model_types
@keras_parameterized.run_all_keras_modes
def test_progbar_logging(self):
model = self._get_model(input_shape=(3,))
x = array_ops.ones((50, 3))
y = array_ops.zeros((50, 2))
dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).batch(10)
expected_log = r'(.*- loss:.*- my_acc:.*)+'
with self.captureWritesToStream(sys.stdout) as printed:
model.fit(dataset, epochs=2, steps_per_epoch=10)
self.assertRegexpMatches(printed.contents(), expected_log)
@keras_parameterized.run_with_all_model_types(exclude_models='functional')
@keras_parameterized.run_all_keras_modes
def test_progbar_logging_deferred_model_build(self):
model = self._get_model()
self.assertFalse(model.built)
x = array_ops.ones((50, 3))
y = array_ops.zeros((50, 2))
dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).batch(10)
expected_log = r'(.*- loss:.*- my_acc:.*)+'
with self.captureWritesToStream(sys.stdout) as printed:
model.fit(dataset, epochs=2, steps_per_epoch=10)
self.assertRegexpMatches(printed.contents(), expected_log)
@keras_parameterized.run_with_all_model_types
@keras_parameterized.run_all_keras_modes
def test_progbar_logging_validation_data(self):
model = self._get_model(input_shape=(3,))
x = array_ops.ones((50, 3))
y = array_ops.zeros((50, 2))
training_dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).batch(10)
val_dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).batch(10)
expected_log = r'(.*5/5.*- loss:.*- my_acc:.*- val_loss:.*- val_my_acc:.*)+'
with self.captureWritesToStream(sys.stdout) as printed:
model.fit(training_dataset, epochs=2, validation_data=val_dataset)
self.assertRegexpMatches(printed.contents(), expected_log)
@keras_parameterized.run_with_all_model_types
@keras_parameterized.run_all_keras_modes
def test_progbar_logging_validation_split(self):
model = self._get_model(input_shape=(3,))
x = np.ones((100, 3))
y = np.zeros((100, 2))
expected_log = (
r'(?s).*1/2.*80/80.*- loss:.*- my_acc:.*- val_loss:.*- val_my_acc:'
r'.*2/2.*80/80.*- loss:.*- my_acc:.*- val_loss:.*- val_my_acc:.*')
with self.captureWritesToStream(sys.stdout) as printed:
model.fit(x, y, batch_size=10, epochs=2, validation_split=0.2)
self.assertRegexpMatches(printed.contents(), expected_log)
@keras_parameterized.run_with_all_model_types
def test_ModelCheckpoint(self):
if h5py is None:
return # Skip test if models cannot be saved.
layers = [
keras.layers.Dense(NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'),
keras.layers.Dense(NUM_CLASSES, activation='softmax')
]
model = testing_utils.get_model_from_layers(layers, input_shape=(10,))
model.compile(
loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc'])
temp_dir = self.get_temp_dir()
self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True)
filepath = os.path.join(temp_dir, 'checkpoint.h5')
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
# case 1
monitor = 'val_loss'
save_best_only = False
mode = 'auto'
model = keras.models.Sequential()
model.add(
keras.layers.Dense(
NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'))
model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax'))
model.compile(
loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc'])
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
assert os.path.exists(filepath)
os.remove(filepath)
# case 2
mode = 'min'
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
assert os.path.exists(filepath)
os.remove(filepath)
# case 3
mode = 'max'
monitor = 'val_acc'
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
assert os.path.exists(filepath)
os.remove(filepath)
# case 4
save_best_only = True
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
assert os.path.exists(filepath)
os.remove(filepath)
# Case: metric not available.
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor='unknown',
save_best_only=True)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
# File won't be written.
assert not os.path.exists(filepath)
# case 5
save_best_only = False
period = 2
mode = 'auto'
filepath = os.path.join(temp_dir, 'checkpoint.{epoch:02d}.h5')
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode,
period=period)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=4,
verbose=1)
assert os.path.exists(filepath.format(epoch=2))
assert os.path.exists(filepath.format(epoch=4))
os.remove(filepath.format(epoch=2))
os.remove(filepath.format(epoch=4))
assert not os.path.exists(filepath.format(epoch=1))
assert not os.path.exists(filepath.format(epoch=3))
# Invalid use: this will raise a warning but not an Exception.
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode='unknown')
# Case 6: `ModelCheckpoint` with a combination of `save_freq` and `period`.
# Though `period` is deprecated, we're testing it for
# backward-compatibility.
filepath = os.path.join(temp_dir, 'checkpoint.epoch{epoch:02d}.h5')
cbks = [
keras.callbacks.ModelCheckpoint(
filepath, monitor=monitor, mode=mode, save_freq='epoch', period=5)
]
assert not os.path.exists(filepath.format(epoch=0))
assert not os.path.exists(filepath.format(epoch=5))
model.fit(
x_train,
y_train,
batch_size=2,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=10,
verbose=1)
assert not os.path.exists(filepath.format(epoch=1))
assert not os.path.exists(filepath.format(epoch=2))
assert not os.path.exists(filepath.format(epoch=3))
assert not os.path.exists(filepath.format(epoch=4))
assert os.path.exists(filepath.format(epoch=5))
assert not os.path.exists(filepath.format(epoch=6))
assert os.path.exists(filepath.format(epoch=10))
os.remove(filepath.format(epoch=5))
os.remove(filepath.format(epoch=10))
# Case 7: `ModelCheckpoint` with an integer `save_freq`
filepath = os.path.join(temp_dir, 'checkpoint.epoch{epoch:02d}.h5')
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode,
save_freq=30,
period=100) # The period should be ignored (this test tests this).
]
assert not os.path.exists(filepath.format(epoch=3))
model.fit(
x_train,
y_train,
batch_size=2,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=10,
verbose=1)
assert not os.path.exists(filepath.format(epoch=1))
assert not os.path.exists(filepath.format(epoch=2))
assert os.path.exists(filepath.format(epoch=3))
assert not os.path.exists(filepath.format(epoch=4))
assert not os.path.exists(filepath.format(epoch=5))
assert os.path.exists(filepath.format(epoch=6))
assert not os.path.exists(filepath.format(epoch=7))
assert not os.path.exists(filepath.format(epoch=8))
assert os.path.exists(filepath.format(epoch=9))
os.remove(filepath.format(epoch=3))
os.remove(filepath.format(epoch=6))
os.remove(filepath.format(epoch=9))
# Case 8: `ModelCheckpoint` with valid and invalid save_freq argument.
with self.assertRaisesRegexp(ValueError, 'Unrecognized save_freq'):
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode,
save_freq='invalid_save_freq')
# The following should not raise ValueError.
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode,
save_freq='epoch')
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode,
save_freq=3)
def _get_dummy_resource_for_model_checkpoint_testing(self):
def get_input_datasets():
# Simple training input.
train_input = [[1]] * 16
train_label = [[0]] * 16
ds = dataset_ops.Dataset.from_tensor_slices((train_input, train_label))
return ds.batch(8, drop_remainder=True)
class Bias(base_layer.Layer):
def build(self, input_shape):
self.bias = self.add_variable('bias', (1,), initializer='zeros')
def call(self, inputs):
return inputs + self.bias
# Very simple bias model to eliminate randomness.
optimizer = gradient_descent.SGD(0.1)
model = sequential.Sequential()
model.add(Bias(input_shape=(1,)))
model.compile(loss='mae', optimizer=optimizer, metrics=['mae'])
train_ds = get_input_datasets()
temp_dir = self.get_temp_dir()
filepath = os.path.join(temp_dir, 'checkpoint.epoch{epoch:02d}.h5')
# The filepath shouldn't exist at the beginning.
self.assertFalse(os.path.exists(filepath))
callback = keras.callbacks.ModelCheckpoint(
filepath=filepath, save_weights_only=True)
return model, train_ds, callback, filepath
def _run_load_weights_on_restart_test_common_iterations(self):
(model, train_ds, callback,
filepath) = self._get_dummy_resource_for_model_checkpoint_testing()
initial_epochs = 3
model.fit(train_ds, epochs=initial_epochs, callbacks=[callback])
# The files should exist after fitting with callback.
for epoch in range(initial_epochs):
self.assertTrue(os.path.exists(filepath.format(epoch=epoch + 1)))
self.assertFalse(os.path.exists(filepath.format(epoch=initial_epochs + 1)))
self.assertEqual(
callback._get_most_recently_modified_file_matching_pattern(filepath),
filepath.format(epoch=initial_epochs))
model.fit(train_ds, epochs=1)
weights_after_one_more_epoch = model.get_weights()
# The filepath should continue to exist after fitting without callback.
for epoch in range(initial_epochs):
self.assertTrue(os.path.exists(filepath.format(epoch=epoch + 1)))
return model, train_ds, filepath, weights_after_one_more_epoch
@staticmethod
def get_ModelCheckpoint_load_weights_on_restart_true_test(save_weights_only):
def func(self):
(model, train_ds, filepath, weights_after_one_more_epoch
) = self._run_load_weights_on_restart_test_common_iterations()
# Sleep for some short time period ensuring the files are created with
# a different time (in MacOS OSS the granularity is only 1 second).
time.sleep(2)
callback = keras.callbacks.ModelCheckpoint(
filepath=filepath,
save_weights_only=save_weights_only,
load_weights_on_restart=True)
model.fit(train_ds, epochs=1, callbacks=[callback])
weights_after_model_restoring_and_one_more_epoch = model.get_weights()
self.assertEqual(
callback._get_most_recently_modified_file_matching_pattern(filepath),
filepath.format(epoch=1))
model.fit(
train_ds,
epochs=1,
callbacks=[
keras.callbacks.ModelCheckpoint(
filepath=filepath,
save_weights_only=save_weights_only,
load_weights_on_restart=True)
])
weights_with_one_final_extra_epoch = model.get_weights()
# Asserting the weights one epoch after initial fitting and another epoch
# after that are closed, if a ModelCheckpoint with
# load_weights_on_restart=True is given (so the model is restored at the
# beginning of training).
self.assertAllClose(weights_after_one_more_epoch,
weights_after_model_restoring_and_one_more_epoch)
self.assertNotAllClose(weights_after_one_more_epoch,
weights_with_one_final_extra_epoch)
return func
@staticmethod
def get_ModelCheckpoint_load_weights_on_restart_false_test(save_weights_only):
def func(self):
(model, train_ds, filepath, weights_after_one_more_epoch
) = self._run_load_weights_on_restart_test_common_iterations()
model.fit(
train_ds,
epochs=1,
callbacks=[
keras.callbacks.ModelCheckpoint(
filepath=filepath, save_weights_only=save_weights_only)
])
weights_after_model_restoring_and_one_more_epoch = model.get_weights()
# Asserting the weights one epoch after initial fitting and another epoch
# after that are different, if a ModelCheckpoint with
# load_weights_on_restart=False is given (so the model is not restored at
# the beginning of training).
self.assertNotAllClose(weights_after_one_more_epoch,
weights_after_model_restoring_and_one_more_epoch)
return func
test_model_checkpoint_load_weights_on_restart_true_save_weights_only_true = \
get_ModelCheckpoint_load_weights_on_restart_true_test.__func__(True)
test_model_checkpoint_load_weights_on_restart_true_save_weights_only_false = \
get_ModelCheckpoint_load_weights_on_restart_true_test.__func__(False)
test_model_checkpoint_load_weights_on_restart_false_save_weights_only_true = \
get_ModelCheckpoint_load_weights_on_restart_false_test.__func__(True)
test_model_checkpoint_load_weights_on_restart_false_save_weights_only_false \
= get_ModelCheckpoint_load_weights_on_restart_false_test.__func__(False)
def test_ModelCheckpoint_override_if_file_exist(self):
(model, train_ds, filepath,
_) = self._run_load_weights_on_restart_test_common_iterations()
# Sleep for some short time period to ensure the files are created with
# a different time (in MacOS OSS the granularity is only 1 second).
time.sleep(2)
callback = keras.callbacks.ModelCheckpoint(
filepath=filepath, save_weights_only=True)
model.load_weights(
callback._get_most_recently_modified_file_matching_pattern(filepath))
weights_before_additional_fit = model.get_weights()
model.fit(train_ds, epochs=1, callbacks=[callback])
model.load_weights(
callback._get_most_recently_modified_file_matching_pattern(filepath))
weights_after_additional_fit = model.get_weights()
self.assertNotAllClose(weights_before_additional_fit,
weights_after_additional_fit)
def test_fit_with_ModelCheckpoint_with_tf_config(self):
(model, train_ds, callback,
_) = self._get_dummy_resource_for_model_checkpoint_testing()
os.environ['TF_CONFIG'] = json.dumps({
'cluster': {
'worker': ['localhost:23333']
},
'task': {
'type': 'worker',
'index': 0
}
})
# `model.fit()` should work regardless of the presence of `TF_CONFIG`.
model.fit(train_ds, epochs=1, callbacks=[callback])
def test_EarlyStopping(self):
with self.cached_session():
np.random.seed(123)
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
model = testing_utils.get_small_sequential_mlp(
num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM)
model.compile(
loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc'])
cases = [
('max', 'val_acc'),
('min', 'val_loss'),
('auto', 'val_acc'),
('auto', 'loss'),
('unknown', 'unknown')
]
for mode, monitor in cases:
patience = 0
cbks = [
keras.callbacks.EarlyStopping(
patience=patience, monitor=monitor, mode=mode)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=5,
verbose=0)
def test_EarlyStopping_reuse(self):
with self.cached_session():
np.random.seed(1337)
patience = 3
data = np.random.random((100, 1))
labels = np.where(data > 0.5, 1, 0)
model = keras.models.Sequential((keras.layers.Dense(
1, input_dim=1, activation='relu'), keras.layers.Dense(
1, activation='sigmoid'),))
model.compile(
optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])
weights = model.get_weights()
stopper = keras.callbacks.EarlyStopping(monitor='acc', patience=patience)
hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20)
assert len(hist.epoch) >= patience
# This should allow training to go for at least `patience` epochs
model.set_weights(weights)
hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20)
assert len(hist.epoch) >= patience
def test_EarlyStopping_with_baseline(self):
with self.cached_session():
np.random.seed(1337)
baseline = 0.5
(data, labels), _ = testing_utils.get_test_data(
train_samples=100,
test_samples=50,
input_shape=(1,),
num_classes=NUM_CLASSES)
model = testing_utils.get_small_sequential_mlp(
num_hidden=1, num_classes=1, input_dim=1)
model.compile(
optimizer='sgd', loss='binary_crossentropy', metrics=['acc'])
stopper = keras.callbacks.EarlyStopping(monitor='acc',
baseline=baseline)
hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20)
assert len(hist.epoch) == 1
patience = 3
stopper = keras.callbacks.EarlyStopping(monitor='acc',
patience=patience,
baseline=baseline)
hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20)
assert len(hist.epoch) >= patience
def test_EarlyStopping_final_weights_when_restoring_model_weights(self):
class DummyModel(object):
def __init__(self):
self.stop_training = False
self.weights = -1
def get_weights(self):
return self.weights
def set_weights(self, weights):
self.weights = weights
def set_weight_to_epoch(self, epoch):
self.weights = epoch
early_stop = keras.callbacks.EarlyStopping(monitor='val_loss',
patience=2,
restore_best_weights=True)
early_stop.model = DummyModel()
losses = [0.2, 0.15, 0.1, 0.11, 0.12]
# The best configuration is in the epoch 2 (loss = 0.1000).
epochs_trained = 0
early_stop.on_train_begin()
for epoch in range(len(losses)):
epochs_trained += 1
early_stop.model.set_weight_to_epoch(epoch=epoch)
early_stop.on_epoch_end(epoch, logs={'val_loss': losses[epoch]})
if early_stop.model.stop_training:
break
# The best configuration is in epoch 2 (loss = 0.1000),
# and while patience = 2, we're restoring the best weights,
# so we end up at the epoch with the best weights, i.e. epoch 2
self.assertEqual(early_stop.model.get_weights(), 2)
def test_RemoteMonitor(self):
if requests is None:
return
monitor = keras.callbacks.RemoteMonitor()
# This will raise a warning since the default address in unreachable:
monitor.on_epoch_end(0, logs={'loss': 0.})
def test_LearningRateScheduler(self):
with self.cached_session():
np.random.seed(1337)
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
model = testing_utils.get_small_sequential_mlp(
num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM)
model.compile(
loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
cbks = [keras.callbacks.LearningRateScheduler(lambda x: 1. / (1. + x))]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=5,
verbose=0)
assert (
float(keras.backend.get_value(
model.optimizer.lr)) - 0.2) < keras.backend.epsilon()
cbks = [keras.callbacks.LearningRateScheduler(lambda x, lr: lr / 2)]
model.compile(
loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=2,
verbose=0)
assert (
float(keras.backend.get_value(
model.optimizer.lr)) - 0.01 / 4) < keras.backend.epsilon()
cbks = [
keras.callbacks.LearningRateScheduler(
lambda epoch, _: learning_rate_schedule.CosineDecay(0.01, 2)
(epoch))
]
model.compile(
loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=2,
verbose=0)
cosine_decay_np = 0.5 * (1 + np.cos(np.pi * (1 / 2)))
decayed_learning_rate = 0.01 * cosine_decay_np
assert (float(keras.backend.get_value(model.optimizer.lr)) -
decayed_learning_rate) < keras.backend.epsilon()
def test_ReduceLROnPlateau(self):
with self.cached_session():
np.random.seed(1337)
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
def make_model():
random_seed.set_random_seed(1234)
np.random.seed(1337)
model = testing_utils.get_small_sequential_mlp(
num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM)
model.compile(
loss='categorical_crossentropy',
optimizer=gradient_descent.SGD(lr=0.1))
return model
# TODO(psv): Make sure the callback works correctly when min_delta is
# set as 0. Test fails when the order of this callback and assertion is
# interchanged.
model = make_model()
cbks = [
keras.callbacks.ReduceLROnPlateau(
monitor='val_loss',
factor=0.1,
min_delta=0,
patience=1,
cooldown=5)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=2,
verbose=0)
self.assertAllClose(
float(keras.backend.get_value(model.optimizer.lr)), 0.1, atol=1e-4)
model = make_model()
# This should reduce the LR after the first epoch (due to high epsilon).
cbks = [
keras.callbacks.ReduceLROnPlateau(
monitor='val_loss',
factor=0.1,
min_delta=10,
patience=1,
cooldown=5)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=2,
verbose=2)
self.assertAllClose(
float(keras.backend.get_value(model.optimizer.lr)), 0.01, atol=1e-4)
def test_ReduceLROnPlateau_patience(self):
class DummyOptimizer(object):
def __init__(self):
self.lr = keras.backend.variable(1.0)
class DummyModel(object):
def __init__(self):
self.optimizer = DummyOptimizer()
reduce_on_plateau = keras.callbacks.ReduceLROnPlateau(
monitor='val_loss', patience=2)
reduce_on_plateau.model = DummyModel()
losses = [0.0860, 0.1096, 0.1040]
lrs = []
for epoch in range(len(losses)):
reduce_on_plateau.on_epoch_end(epoch, logs={'val_loss': losses[epoch]})
lrs.append(keras.backend.get_value(reduce_on_plateau.model.optimizer.lr))
# The learning rates should be 1.0 except the last one
for lr in lrs[:-1]:
self.assertEqual(lr, 1.0)
self.assertLess(lrs[-1], 1.0)
def test_ReduceLROnPlateau_backwards_compatibility(self):
with test.mock.patch.object(logging, 'warning') as mock_log:
reduce_on_plateau = keras.callbacks.ReduceLROnPlateau(epsilon=1e-13)
self.assertRegexpMatches(
str(mock_log.call_args), '`epsilon` argument is deprecated')
self.assertFalse(hasattr(reduce_on_plateau, 'epsilon'))
self.assertTrue(hasattr(reduce_on_plateau, 'min_delta'))
self.assertEqual(reduce_on_plateau.min_delta, 1e-13)
def test_CSVLogger(self):
with self.cached_session():
np.random.seed(1337)
temp_dir = self.get_temp_dir()
self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True)
filepath = os.path.join(temp_dir, 'log.tsv')
sep = '\t'
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
def make_model():
np.random.seed(1337)
model = testing_utils.get_small_sequential_mlp(
num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM)
model.compile(
loss='categorical_crossentropy',
optimizer=gradient_descent.SGD(lr=0.1),
metrics=['accuracy'])
return model
# case 1, create new file with defined separator
model = make_model()
cbks = [keras.callbacks.CSVLogger(filepath, separator=sep)]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
assert os.path.exists(filepath)
with open(filepath) as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read())
assert dialect.delimiter == sep
del model
del cbks
# case 2, append data to existing file, skip header
model = make_model()
cbks = [keras.callbacks.CSVLogger(filepath, separator=sep, append=True)]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
# case 3, reuse of CSVLogger object
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=2,
verbose=0)
with open(filepath) as csvfile:
list_lines = csvfile.readlines()
for line in list_lines:
assert line.count(sep) == 4
assert len(list_lines) == 5
output = ' '.join(list_lines)
assert len(re.findall('epoch', output)) == 1
os.remove(filepath)
def test_stop_training_csv(self):
# Test that using the CSVLogger callback with the TerminateOnNaN callback
# does not result in invalid CSVs.
np.random.seed(1337)
tmpdir = self.get_temp_dir()
self.addCleanup(shutil.rmtree, tmpdir, ignore_errors=True)
with self.cached_session():
fp = os.path.join(tmpdir, 'test.csv')
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
cbks = [keras.callbacks.TerminateOnNaN(), keras.callbacks.CSVLogger(fp)]
model = keras.models.Sequential()
for _ in range(5):
model.add(keras.layers.Dense(2, input_dim=INPUT_DIM, activation='relu'))
model.add(keras.layers.Dense(NUM_CLASSES, activation='linear'))
model.compile(loss='mean_squared_error',
optimizer='rmsprop')
def data_generator():
i = 0
max_batch_index = len(x_train) // BATCH_SIZE
tot = 0
while 1:
if tot > 3 * len(x_train):
yield (np.ones([BATCH_SIZE, INPUT_DIM]) * np.nan,
np.ones([BATCH_SIZE, NUM_CLASSES]) * np.nan)
else:
yield (x_train[i * BATCH_SIZE: (i + 1) * BATCH_SIZE],
y_train[i * BATCH_SIZE: (i + 1) * BATCH_SIZE])
i += 1
tot += 1
i %= max_batch_index
history = model.fit_generator(data_generator(),
len(x_train) // BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=20)
loss = history.history['loss']
assert len(loss) > 1
assert loss[-1] == np.inf or np.isnan(loss[-1])
values = []
with open(fp) as f:
for x in csv.reader(f):
# In windows, due to \r\n line ends we may end up reading empty lines
# after each line. Skip empty lines.
if x:
values.append(x)
assert 'nan' in values[-1], 'The last epoch was not logged.'
def test_TerminateOnNaN(self):
with self.cached_session():
np.random.seed(1337)
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
cbks = [keras.callbacks.TerminateOnNaN()]
model = keras.models.Sequential()
initializer = keras.initializers.Constant(value=1e5)
for _ in range(5):
model.add(
keras.layers.Dense(
2,
input_dim=INPUT_DIM,
activation='relu',
kernel_initializer=initializer))
model.add(keras.layers.Dense(NUM_CLASSES))
model.compile(loss='mean_squared_error', optimizer='rmsprop')
history = model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=20)
loss = history.history['loss']
self.assertEqual(len(loss), 1)
self.assertEqual(loss[0], np.inf)
@unittest.skipIf(
os.name == 'nt',
'use_multiprocessing=True does not work on windows properly.')
def test_LambdaCallback(self):
with self.cached_session():
np.random.seed(1337)
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
model = keras.models.Sequential()
model.add(
keras.layers.Dense(
NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'))
model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax'))
model.compile(
loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
# Start an arbitrary process that should run during model
# training and be terminated after training has completed.
e = threading.Event()
def target():
e.wait()
t = threading.Thread(target=target)
t.start()
cleanup_callback = keras.callbacks.LambdaCallback(
on_train_end=lambda logs: e.set())
cbks = [cleanup_callback]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=5,
verbose=0)
t.join()
assert not t.is_alive()
def test_RemoteMonitorWithJsonPayload(self):
if requests is None:
self.skipTest('`requests` required to run this test')
with self.cached_session():
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.np_utils.to_categorical(y_test)
y_train = keras.utils.np_utils.to_categorical(y_train)
model = keras.models.Sequential()
model.add(
keras.layers.Dense(
NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'))
model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax'))
model.compile(
loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
cbks = [keras.callbacks.RemoteMonitor(send_as_json=True)]
with test.mock.patch.object(requests, 'post'):
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1)
# A summary that was emitted during a test. Fields:
# logdir: str. The logdir of the FileWriter to which the summary was
# written.
# tag: str. The name of the summary.
_ObservedSummary = collections.namedtuple('_ObservedSummary', ('logdir', 'tag'))
class _SummaryFile(object):
"""A record of summary tags and the files to which they were written.
Fields `scalars`, `images`, `histograms`, and `tensors` are sets
containing `_ObservedSummary` values.
"""
def __init__(self):
self.scalars = set()
self.images = set()
self.histograms = set()
self.tensors = set()
def list_summaries(logdir):
"""Read all summaries under the logdir into a `_SummaryFile`.
Args:
logdir: A path to a directory that contains zero or more event
files, either as direct children or in transitive subdirectories.
Summaries in these events must only contain old-style scalars,
images, and histograms. Non-summary events, like `graph_def`s, are
ignored.
Returns:
A `_SummaryFile` object reflecting all summaries written to any
event files in the logdir or any of its descendant directories.
Raises:
ValueError: If an event file contains an summary of unexpected kind.
"""
result = _SummaryFile()
for (dirpath, dirnames, filenames) in os.walk(logdir):
del dirnames # unused
for filename in filenames:
if not filename.startswith('events.out.'):
continue
path = os.path.join(dirpath, filename)
for event in summary_iterator.summary_iterator(path):
if not event.summary: # (e.g., it's a `graph_def` event)
continue
for value in event.summary.value:
tag = value.tag
# Case on the `value` rather than the summary metadata because
# the Keras callback uses `summary_ops_v2` to emit old-style
# summaries. See b/124535134.
kind = value.WhichOneof('value')
container = {
'simple_value': result.scalars,
'image': result.images,
'histo': result.histograms,
'tensor': result.tensors,
}.get(kind)
if container is None:
raise ValueError(
'Unexpected summary kind %r in event file %s:\n%r'
% (kind, path, event))
elif kind == 'tensor' and tag != 'keras':
# Check for V2 scalar summaries, which have a different PB
# structure.
if event.summary.value[
0].metadata.plugin_data.plugin_name == 'scalars':
container = result.scalars
container.add(_ObservedSummary(logdir=dirpath, tag=tag))
return result
@keras_parameterized.run_with_all_model_types
@keras_parameterized.run_all_keras_modes(always_skip_v1=True)
class TestTensorBoardV2(keras_parameterized.TestCase):
def setUp(self):
super(TestTensorBoardV2, self).setUp()
self.logdir = os.path.join(self.get_temp_dir(), 'tb')
self.train_dir = os.path.join(self.logdir, 'train')
self.validation_dir = os.path.join(self.logdir, 'validation')
def _get_model(self):
layers = [
keras.layers.Conv2D(8, (3, 3)),
keras.layers.Flatten(),
keras.layers.Dense(1)
]
model = testing_utils.get_model_from_layers(layers, input_shape=(10, 10, 1))
opt = gradient_descent.SGD(learning_rate=0.001)
model.compile(
opt,
'mse',
run_eagerly=testing_utils.should_run_eagerly(),
experimental_run_tf_function=testing_utils.should_run_tf_function())
return model
def test_TensorBoard_default_logdir(self):
"""Regression test for cross-platform pathsep in default logdir."""
os.chdir(self.get_temp_dir())
model = self._get_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard() # no logdir specified
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
summary_file = list_summaries(logdir='.')
train_dir = os.path.join('.', 'logs', 'train')
validation_dir = os.path.join('.', 'logs', 'validation')
self.assertEqual(
summary_file.scalars, {
_ObservedSummary(logdir=train_dir, tag='epoch_loss'),
_ObservedSummary(logdir=validation_dir, tag='epoch_loss'),
})
def test_TensorBoard_basic(self):
model = self._get_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(self.logdir)
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
summary_file = list_summaries(self.logdir)
self.assertEqual(
summary_file.scalars, {
_ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),
_ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),
})
def test_TensorBoard_across_invocations(self):
"""Regression test for summary writer resource use-after-free.
See: <https://github.com/tensorflow/tensorflow/issues/25707>
"""
model = self._get_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(self.logdir)
for _ in (1, 2):
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
summary_file = list_summaries(self.logdir)
self.assertEqual(
summary_file.scalars, {
_ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),
_ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),
})
def test_TensorBoard_no_spurious_event_files(self):
model = self._get_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(self.logdir)
model.fit(
x,
y,
batch_size=2,
epochs=2,
callbacks=[tb_cbk])
events_file_run_basenames = set()
for (dirpath, dirnames, filenames) in os.walk(self.logdir):
del dirnames # unused
if any(fn.startswith('events.out.') for fn in filenames):
events_file_run_basenames.add(os.path.basename(dirpath))
self.assertEqual(events_file_run_basenames, {'train'})
def test_TensorBoard_batch_metrics(self):
model = self._get_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(self.logdir, update_freq=1)
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
summary_file = list_summaries(self.logdir)
self.assertEqual(
summary_file.scalars,
{
_ObservedSummary(logdir=self.train_dir, tag='batch_loss'),
_ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),
_ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),
},
)
def test_TensorBoard_weight_histograms(self):
model = self._get_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(self.logdir, histogram_freq=1)
model_type = testing_utils.get_model_type()
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
summary_file = list_summaries(self.logdir)
self.assertEqual(
summary_file.scalars,
{
_ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),
_ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),
},
)
self.assertEqual(
self._strip_layer_names(summary_file.histograms, model_type),
{
_ObservedSummary(logdir=self.train_dir, tag='bias_0'),
_ObservedSummary(logdir=self.train_dir, tag='kernel_0'),
},
)
def test_TensorBoard_weight_images(self):
model = self._get_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(
self.logdir, histogram_freq=1, write_images=True)
model_type = testing_utils.get_model_type()
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
summary_file = list_summaries(self.logdir)
self.assertEqual(
summary_file.scalars,
{
_ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),
_ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),
},
)
self.assertEqual(
self._strip_layer_names(summary_file.histograms, model_type),
{
_ObservedSummary(logdir=self.train_dir, tag='bias_0'),
_ObservedSummary(logdir=self.train_dir, tag='kernel_0'),
},
)
self.assertEqual(
self._strip_layer_names(summary_file.images, model_type),
{
_ObservedSummary(logdir=self.train_dir, tag='bias_0/image/0'),
_ObservedSummary(logdir=self.train_dir, tag='kernel_0/image/0'),
_ObservedSummary(logdir=self.train_dir, tag='kernel_0/image/1'),
_ObservedSummary(logdir=self.train_dir, tag='kernel_0/image/2'),
},
)
def test_custom_summary(self):
if not testing_utils.should_run_tf_function():
self.skipTest('Custom summaries only supported in V2 code path.')
def scalar_v2_mock(name, data, step=None):
"""A reimplementation of the scalar plugin to avoid circular deps."""
metadata = summary_pb2.SummaryMetadata()
# Should match value in tensorboard/plugins/scalar/metadata.py.
metadata.plugin_data.plugin_name = 'scalars'
with summary_ops_v2.summary_scope(
name, 'scalar_summary', values=[data, step]) as (tag, _):
return summary_ops_v2.write(
tag=tag,
tensor=math_ops.cast(data, 'float32'),
step=step,
metadata=metadata)
class LayerWithSummary(keras.layers.Layer):
def call(self, x):
scalar_v2_mock('custom_summary', math_ops.reduce_sum(x))
return x
model = testing_utils.get_model_from_layers([LayerWithSummary()],
input_shape=(5,),
name='model')
model.compile(
'sgd',
'mse',
run_eagerly=testing_utils.should_run_eagerly(),
experimental_run_tf_function=testing_utils.should_run_tf_function())
tb_cbk = keras.callbacks.TensorBoard(self.logdir, update_freq=1)
x, y = np.ones((10, 5)), np.ones((10, 5))
model.fit(x, y, batch_size=2, validation_data=(x, y), callbacks=[tb_cbk])
summary_file = list_summaries(self.logdir)
self.assertEqual(
summary_file.scalars,
{
_ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),
_ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),
_ObservedSummary(logdir=self.train_dir, tag='batch_loss'),
_ObservedSummary(
logdir=self.train_dir,
tag='model/layer_with_summary/custom_summary'),
_ObservedSummary(
logdir=self.validation_dir,
tag='model/layer_with_summary/custom_summary')
},
)
def _strip_layer_names(self, summaries, model_type):
"""Deduplicate summary names modulo layer prefix.
This removes the first slash-component of each tag name: for
instance, "foo/bar/baz" becomes "bar/baz".
Args:
summaries: A `set` of `_ObservedSummary` values.
model_type: The model type currently being tested.
Returns:
A new `set` of `_ObservedSummary` values with layer prefixes
removed.
"""
result = set()
for summary in summaries:
if '/' not in summary.tag:
raise ValueError('tag has no layer name: %r' % summary.tag)
start_from = 2 if 'subclass' in model_type else 1
new_tag = '/'.join(summary.tag.split('/')[start_from:])
result.add(summary._replace(tag=new_tag))
return result
def test_TensorBoard_invalid_argument(self):
with self.assertRaisesRegexp(ValueError, 'Unrecognized arguments'):
keras.callbacks.TensorBoard(wwrite_images=True)
# Note that this test specifies model_type explicitly.
@keras_parameterized.run_all_keras_modes(always_skip_v1=True)
class TestTensorBoardV2NonParameterizedTest(keras_parameterized.TestCase):
def setUp(self):
super(TestTensorBoardV2NonParameterizedTest, self).setUp()
self.logdir = os.path.join(self.get_temp_dir(), 'tb')
self.train_dir = os.path.join(self.logdir, 'train')
self.validation_dir = os.path.join(self.logdir, 'validation')
def _get_seq_model(self):
model = keras.models.Sequential([
keras.layers.Conv2D(8, (3, 3), input_shape=(10, 10, 1)),
keras.layers.Flatten(),
keras.layers.Dense(1),
])
opt = gradient_descent.SGD(learning_rate=0.001)
model.compile(
opt,
'mse',
run_eagerly=testing_utils.should_run_eagerly(),
experimental_run_tf_function=testing_utils.should_run_tf_function())
return model
def fitModelAndAssertKerasModelWritten(self, model):
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(self.logdir,
write_graph=True,
profile_batch=0)
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
summary_file = list_summaries(self.logdir)
self.assertEqual(
summary_file.tensors,
{
_ObservedSummary(logdir=self.train_dir, tag='keras'),
},
)
def test_TensorBoard_writeSequentialModel_noInputShape(self):
model = keras.models.Sequential([
keras.layers.Conv2D(8, (3, 3)),
keras.layers.Flatten(),
keras.layers.Dense(1),
])
model.compile('sgd', 'mse', run_eagerly=False)
self.fitModelAndAssertKerasModelWritten(model)
def test_TensorBoard_writeSequentialModel_withInputShape(self):
model = keras.models.Sequential([
keras.layers.Conv2D(8, (3, 3), input_shape=(10, 10, 1)),
keras.layers.Flatten(),
keras.layers.Dense(1),
])
model.compile('sgd', 'mse', run_eagerly=False)
self.fitModelAndAssertKerasModelWritten(model)
def test_TensoriBoard_writeModel(self):
inputs = keras.layers.Input([10, 10, 1])
x = keras.layers.Conv2D(8, (3, 3), activation='relu')(inputs)
x = keras.layers.Flatten()(x)
x = keras.layers.Dense(1)(x)
model = keras.models.Model(inputs=inputs, outputs=[x])
model.compile('sgd', 'mse', run_eagerly=False)
self.fitModelAndAssertKerasModelWritten(model)
def test_TensorBoard_autoTrace(self):
model = self._get_seq_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(
self.logdir, histogram_freq=1, profile_batch=1, write_graph=False)
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
summary_file = list_summaries(self.logdir)
self.assertEqual(
summary_file.tensors,
{
_ObservedSummary(logdir=self.train_dir, tag=u'batch_1'),
},
)
def test_TensorBoard_autoTrace_tagNameWithBatchNum(self):
model = self._get_seq_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(
self.logdir, histogram_freq=1, profile_batch=2, write_graph=False)
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
summary_file = list_summaries(self.logdir)
self.assertEqual(
summary_file.tensors,
{
_ObservedSummary(logdir=self.train_dir, tag=u'batch_2'),
},
)
def test_TensorBoard_autoTrace_profile_batch_largerThanBatchCount(self):
model = self._get_seq_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(
self.logdir, histogram_freq=1, profile_batch=10000, write_graph=False)
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
summary_file = list_summaries(self.logdir)
# Enabled trace only on the 10000th batch, thus it should be empty.
self.assertEmpty(summary_file.tensors)
class MostRecentlyModifiedFileMatchingPatternTest(test.TestCase):
def test_get_most_recently_modified_file_matching_pattern(self):
file_pattern = 'f.batch{batch:02d}epoch{epoch:02d}.h5'
test_dir = self.get_temp_dir()
path_pattern = os.path.join(test_dir, file_pattern)
file_paths = [
os.path.join(test_dir, file_name) for file_name in
['f.batch03epoch02.h5', 'f.batch02epoch02.h5', 'f.batch01epoch01.h5']
]
for file_path in file_paths:
with open(file_path, 'w') as f:
# Ensure there are some intervals between file creation.
time.sleep(2)
f.write('foo bar')
# Ensure the files have been actually written.
self.assertEqual(
set([
os.path.join(test_dir, file_name)
for file_name in os.listdir(test_dir)
]), set(file_paths))
self.assertEqual(
keras.callbacks.ModelCheckpoint(None)
._get_most_recently_modified_file_matching_pattern(path_pattern),
file_paths[-1])
def test_some_file_not_matching_pattern(self):
file_pattern = 'f.batch{batch:02d}epoch{epoch:02d}.h5'
test_dir = self.get_temp_dir()
path_pattern = os.path.join(test_dir, file_pattern)
file_paths = [
os.path.join(test_dir, file_name) for file_name in
['f.batch03epoch02.h5', 'f.batch02epoch02.h5', 'f.baatch01epoch01.h5']
]
for file_path in file_paths:
with open(file_path, 'w') as f:
# Ensure there are some intervals between file creation.
time.sleep(2)
f.write('foo bar')
self.assertEqual(
keras.callbacks.ModelCheckpoint(None)
._get_most_recently_modified_file_matching_pattern(path_pattern),
file_paths[-2])
def test_get_same_file_if_file_name_equals_pattern(self):
file_name = 'f.batch02.h5'
test_dir = self.get_temp_dir()
file_path = os.path.join(test_dir, file_name)
with open(file_path, 'w') as f:
f.write('foo bar')
self.assertEqual(os.path.join(test_dir, os.listdir(test_dir)[0]), file_path)
self.assertEqual(
keras.callbacks.ModelCheckpoint(
None)._get_most_recently_modified_file_matching_pattern(file_path),
file_path)
def test_get_none_if_file_does_not_exist(self):
file_name = 'f.batch02.h5'
test_dir = self.get_temp_dir()
file_path = os.path.join(test_dir, file_name)
self.assertLen(os.listdir(test_dir), 0)
self.assertEqual(
keras.callbacks.ModelCheckpoint(
None)._get_most_recently_modified_file_matching_pattern(file_path),
None)
def test_using_checkpoint_management_latest_checkpoint(self):
file_pattern = 'f.batch{batch:02d}epoch{epoch:02d}'
ckpt_file_name = 'f.batchXepochY'
test_dir = self.get_temp_dir()
path_pattern = os.path.join(test_dir, file_pattern)
ckpt_file_path = os.path.join(test_dir, ckpt_file_name)
with open(ckpt_file_path, 'w') as f:
f.write('dummy ckpt')
checkpoint_management.update_checkpoint_state_internal(
test_dir, ckpt_file_path)
file_paths = [
os.path.join(test_dir, file_name)
for file_name in ['f.batch03epoch02', 'f.batch02epoch02']
]
for file_path in file_paths:
with open(file_path, 'w') as f:
f.write('foo bar')
# The result returned from checkpoint_management.latest_checkpoint takes
# priority, so even if it was written earlier, we should still return that.
self.assertEqual(
keras.callbacks.ModelCheckpoint(None)
._get_most_recently_modified_file_matching_pattern(path_pattern),
ckpt_file_path)
if __name__ == '__main__':
test.main()
|
pjit_test.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from functools import partial
import logging
import threading
from unittest import SkipTest
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
import jax
import jax.numpy as jnp
from jax._src import test_util as jtu
from jax.errors import JAXTypeError
from jax import lax
# TODO(skye): do we still wanna call this PartitionSpec?
from jax.experimental import PartitionSpec as P
from jax.experimental.maps import xmap, mesh
from jax.experimental.pjit import pjit, pjit_p, with_sharding_constraint, SpecSync
from jax.interpreters import pxla
from jax.interpreters import xla
from jax._src.lib import xla_client
from jax._src.util import prod, curry
from jax.config import config
config.parse_flags_with_absl()
def setUpModule():
jtu.set_spmd_lowering_flag(True)
def tearDownModule():
jtu.restore_spmd_lowering_flag()
# TODO(skye): make the buffer donation utils part of JaxTestCase
class PJitTest(jtu.BufferDonationTestCase):
@jtu.with_mesh([('x', 1)])
def testDeviceBufferAval(self):
@partial(pjit, in_axis_resources=None, out_axis_resources=P('x'))
def f(x):
return x
shape = (2, 2)
x = np.arange(prod(shape), dtype=np.float32).reshape(shape)
actual = f(x)
expected = x
self.assertAllClose(actual, expected, check_dtypes=False)
self.assertIsInstance(actual, pxla.ShardedDeviceArray)
self.assertLen(actual.device_buffers, 1)
self.assertAllClose(
actual.device_buffers[0].to_py(), expected, check_dtypes=False)
# Repro for a bug on device_buffer aval
_ = repr(actual.device_buffers)
@jtu.with_mesh([('x', 2)])
def testBasic1D(self):
@partial(pjit,
in_axis_resources=(P('x'), P('x')),
out_axis_resources=None)
def f(x, y):
return x + y
shape = (8, 8)
x = np.arange(prod(shape), dtype=np.float32).reshape(shape)
actual = f(x, x + 1)
expected = x + (x + 1)
self.assertAllClose(actual, expected, check_dtypes=False)
self.assertIsInstance(actual, pxla.ShardedDeviceArray)
self.assertLen(actual.device_buffers, 2)
self.assertAllClose(actual.device_buffers[0].to_py(), expected,
check_dtypes=False)
@jtu.with_mesh([('x', 2), ('y', 2)])
def testBasic2D(self):
@partial(pjit,
in_axis_resources=(P(None, 'x', 'y'), P('y')),
out_axis_resources=P('x'))
def f(x, y):
return x @ y
x_shape = (8, 6, 4)
y_shape = (4, 2)
x = jnp.arange(np.prod(x_shape)).reshape(x_shape)
y = jnp.arange(np.prod(y_shape)).reshape(y_shape)
actual = f(x, y)
expected = x @ y
self.assertAllClose(actual, expected, check_dtypes=False)
self.assertIsInstance(actual, pxla.ShardedDeviceArray)
self.assertLen(actual.device_buffers, 4)
split0, split1 = np.split(expected, 2)
self.assertAllClose(actual.device_buffers[0].to_py(), split0,
check_dtypes=False)
self.assertAllClose(actual.device_buffers[1].to_py(), split0,
check_dtypes=False)
self.assertAllClose(actual.device_buffers[2].to_py(), split1,
check_dtypes=False)
self.assertAllClose(actual.device_buffers[3].to_py(), split1,
check_dtypes=False)
@jtu.with_mesh([('x', 2), ('y', 2)])
def testTwoMeshAxisSharding(self):
@partial(pjit,
in_axis_resources=P(('x', 'y'),),
out_axis_resources=P(('x', 'y'),))
def f(x, y):
return x @ y
shape = (8, 8)
x = jnp.arange(np.prod(shape)).reshape(shape)
actual = f(x, x + 1)
expected = x @ (x + 1)
self.assertAllClose(actual, expected, check_dtypes=False)
self.assertIsInstance(actual, pxla.ShardedDeviceArray)
self.assertLen(actual.device_buffers, 4)
splits = np.split(expected, 4)
self.assertAllClose(actual.device_buffers[0].to_py(), splits[0],
check_dtypes=False)
self.assertAllClose(actual.device_buffers[1].to_py(), splits[1],
check_dtypes=False)
self.assertAllClose(actual.device_buffers[2].to_py(), splits[2],
check_dtypes=False)
self.assertAllClose(actual.device_buffers[3].to_py(), splits[3],
check_dtypes=False)
@jtu.with_mesh([('x', 2)])
def testBufferDonation(self):
@partial(pjit,
in_axis_resources=P('x'),
out_axis_resources=P('x'),
donate_argnums=0)
def f(x, y):
return x + y
shard = pjit(lambda x: x, in_axis_resources=P('x'),
out_axis_resources=P('x'))
x = shard(jnp.ones((2, 5)) * 4)
y = shard(jnp.ones((2, 5)) * 2)
expected = x + y
self.assertAllClose(f(x, y), expected)
self.assertNotDeleted(y)
self.assertDeleted(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testShardingConstraint(self):
@partial(pjit, in_axis_resources=None, out_axis_resources=None)
def f(x):
y = x + 1
y = with_sharding_constraint(y, P('x', 'y'))
return y * 2
shape = (8, 8)
x = np.arange(prod(shape)).reshape(shape)
expected = (x + 1) * 2
actual = f(x)
self.assertAllClose(actual, expected, check_dtypes=False)
self.assertIsInstance(actual, pxla.ShardedDeviceArray)
self.assertLen(actual.device_buffers, 2)
self.assertAllClose(actual.device_buffers[0].to_py(), expected,
check_dtypes=False)
hlo = jax.xla_computation(f)(np.ones(shape))
# Annotation from with_sharding_constraint
self.assertIn("sharding={devices=[2,1]0,1}", hlo.as_hlo_text())
# Annotation from pjit
self.assertIn("sharding={replicated}", hlo.as_hlo_text())
@jtu.with_mesh([('x', 2), ('y', 1)])
def testShardingConstraintPyTree(self):
@partial(pjit, in_axis_resources=None, out_axis_resources=None)
def f(x):
x = with_sharding_constraint(x, [P('x', 'y'), P('y', 'x')])
x = x.copy()
x[0]["a"] *= 2
return x
shape = (8, 8)
v = np.arange(prod(shape)).reshape(shape)
x = [{"a": v, "b": v * 2}, v * 3]
actual = f(x)
expected = x.copy()
expected[0]["a"] *= 2
self.assertAllClose(actual, expected, check_dtypes=False)
self.assertLen(actual[0]["a"].device_buffers, 2)
hlo = jax.xla_computation(f)(x)
# Annotations from with_sharding_constraint
self.assertIn("sharding={devices=[2,1]0,1}", hlo.as_hlo_text())
self.assertIn("sharding={devices=[1,2]0,1}", hlo.as_hlo_text())
# Annotation from pjit
self.assertIn("sharding={replicated}", hlo.as_hlo_text())
def testCaching(self):
def f(x):
assert should_be_tracing
return jnp.sin(x) * 2
x = np.arange(16).reshape(4, 4)
devices = np.array(list(jax.local_devices())[:4])
if devices.size < 4:
raise SkipTest("Test requires 4 devices")
devices = devices.reshape((2, 2))
with mesh(devices, ('x', 'y')):
should_be_tracing = True
pjit(f, in_axis_resources=P(('x', 'y')), out_axis_resources=None)(x)
should_be_tracing = False
pjit(f, in_axis_resources=P(('x', 'y')), out_axis_resources=None)(x)
# Re-create the mesh to make sure that has no influence on caching
with mesh(devices, ('x', 'y')):
should_be_tracing = False
pjit(f, in_axis_resources=P(('x', 'y')), out_axis_resources=None)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testNested(self):
# Add a constant captured by the nested pjit to make things more complicated
h = jnp.arange(4)
f = pjit(lambda x: x.sum() + h.sum(), in_axis_resources=P('x', 'y'), out_axis_resources=None)
g = pjit(lambda x: f(jnp.sin(x)), in_axis_resources=P('x', None), out_axis_resources=None)
x = jnp.arange(16).reshape((4, 4))
y = g(x)
self.assertAllClose(y, jnp.sin(x).sum() + h.sum())
self.assertTrue(hasattr(y, "sharding_spec"))
@jtu.with_mesh([('x', 2), ('y', 1)])
def testJVP(self):
# Add a constant captured by the nested pjit to make things more complicated
h = jnp.arange(4)
f = pjit(lambda x: x.sum() + h.sum(), in_axis_resources=P('x', 'y'), out_axis_resources=None)
g = pjit(lambda x: f(x + 2), in_axis_resources=P('x', None), out_axis_resources=None)
jtu.check_grads(g, (jnp.arange(16, dtype=jnp.float32).reshape((4, 4)),),
order=2, modes=["fwd"], eps=1)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testEvalJaxpr(self):
x, y = jnp.arange(4), jnp.arange(5)
f = pjit(lambda x, y: x.sum() + jnp.sin(y),
in_axis_resources=(P('x'), P('y')),
out_axis_resources=P('y'))
f_jaxpr = jax.make_jaxpr(f)(x, y)
f_eval = jax.core.jaxpr_as_fun(f_jaxpr)
r, = f_eval(x, y)
self.assertAllClose(r, x.sum() + jnp.sin(y))
@jtu.with_mesh([('x', 2)])
def testNonArrayArg(self):
self.assertEqual(pjit(lambda x: x + 2,
in_axis_resources=None,
out_axis_resources=None)(1), 3)
@jtu.with_mesh([('x', 2)])
def testNonHashableAxisResources(self):
x = jnp.arange(4)
y = pjit(lambda x: {'b': x['a'] + 2},
in_axis_resources=({'a': P('x')},),
out_axis_resources={'b': P('x')})({'a': x})
self.assertAllClose(y, {'b': x + 2})
@jtu.with_mesh([('x', 2)])
def testGradOfConstraint(self):
# Make sure that we can compute grads through sharding constraints
h = lambda x: jnp.sin(with_sharding_constraint(x, P('x'))).sum()
f = pjit(lambda x: jax.grad(h)(x),
in_axis_resources=None, out_axis_resources=None)
x = jnp.arange(8, dtype=jnp.float32)
self.assertAllClose(f(x), jnp.cos(x))
@jtu.with_mesh([('x', 2)])
def testNoopPartitionSpecs(self):
noops = [P(), P(None), P(()), P((), None), P(None, None, ())]
x = jnp.arange(8).reshape((2, 2, 2))
for spec in noops:
y = pjit(lambda x: x * 2, in_axis_resources=spec, out_axis_resources=spec)(x)
self.assertAllClose(y, x * 2)
@jtu.with_mesh([('x', 2)])
def testVmapModifiesAxisResources(self):
h = pjit(lambda x, y: (x + y, x, y), in_axis_resources=P('x'), out_axis_resources=None)
x = jnp.arange(4)
y = jnp.arange(5*4).reshape((5, 4))
jaxpr = jax.make_jaxpr(jax.vmap(h, in_axes=(None, 0)))(x, y).jaxpr
eqn = jaxpr.eqns[0]
self.assertIs(eqn.primitive, pjit_p)
x_sync, y_sync = (spec.sync for spec in eqn.params['in_axis_resources'])
self.assertEqual(x_sync, SpecSync.IN_SYNC)
self.assertEqual(y_sync, SpecSync.DIM_PERMUTE)
x_sync, y_sync, z_sync = (spec.sync for spec in eqn.params['out_axis_resources'])
self.assertEqual(x_sync, SpecSync.DIM_PERMUTE)
self.assertEqual(y_sync, SpecSync.IN_SYNC)
self.assertEqual(z_sync, SpecSync.DIM_PERMUTE)
@jtu.with_mesh([('x', 2)])
def testVMap(self):
f = pjit(lambda x, y: (x + y, x), in_axis_resources=P('x'), out_axis_resources=P('x'))
x = jnp.arange(4)
y = jnp.arange(5*4).reshape((5, 4))
z, w = jax.vmap(f, in_axes=(None, 0), out_axes=(0, None))(x, y)
self.assertAllClose(z, x + y)
self.assertAllClose(w, x)
self.assertEqual(z.sharding_spec.sharding, (pxla.NoSharding(), pxla.Chunked([2])))
self.assertEqual(w.sharding_spec.sharding, (pxla.Chunked([2]),))
@jtu.with_mesh([('x', 2)])
def testVMapShardingConstraint(self):
f = pjit(lambda x: with_sharding_constraint(x, P('x')),
in_axis_resources=P(), out_axis_resources=P('x'))
x = jnp.arange(5*4).reshape((5, 4))
jaxpr = jax.make_jaxpr(jax.vmap(f))(x)
pjit_eqn, = jaxpr.eqns
constraint_eqn, = pjit_eqn.params['jaxpr'].eqns
self.assertEqual(constraint_eqn.params['axis_resources'].partitions, ((), ('x',)))
self.assertEqual(constraint_eqn.params['axis_resources'].sync, SpecSync.DIM_PERMUTE)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testShardingInXMap(self):
h = pjit(lambda x: x, in_axis_resources=P('x'), out_axis_resources=None)
f = xmap(lambda x: h(x * 2), in_axes=['i', ...], out_axes=['i', ...],
axis_resources={'i': 'y'})
x = jnp.arange(16).reshape((4, 4))
self.assertIn(pjit_p, xla.call_translations)
rule = xla.call_translations[pjit_p]
test_rule_called = False
def _test_rule(*args, **kwargs):
nonlocal test_rule_called
test_rule_called = True
in_axis_resources = kwargs['in_axis_resources']
self.assertEqual(len(in_axis_resources), 1)
self.assertIn(('y',), in_axis_resources[0].partitions)
return rule(*args, **kwargs)
try:
xla.call_translations[pjit_p] = _test_rule
f(x)
self.assertTrue(test_rule_called)
finally:
xla.call_translations[pjit_p] = rule
def testInfeed(self):
devices = np.array(jax.local_devices())
nr_devices = len(devices)
shape = (nr_devices * 3, nr_devices * 5)
def f_for_jit(x):
token = lax.create_token(x)
(y,), token = lax.infeed(
token, shape=(jax.ShapedArray(x.shape, np.float32),))
(z,), token = lax.infeed(
token, shape=(jax.ShapedArray(x.shape, np.float32),))
(w,), token = lax.infeed(
token, shape=(jax.ShapedArray(x.shape, np.float32),))
return x + y + z + w
x = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)
y = x * 2.
z = x * 3.
w = x * 4.
# Transfer data to infeed before executing the function. For GPUs, the
# execution of the compiled function is blocking, so transferring data
# to infeed before executing ensures that the execution does not deadlock
# waiting for the infeed data.
logging.info('Transfering to infeed for the jit call')
d = devices[0]
d.transfer_to_infeed((y,))
d.transfer_to_infeed((z,))
d.transfer_to_infeed((w,))
# JIT
logging.info('Making jit call')
res0 = jax.jit(f_for_jit)(x)
self.assertAllClose(res0, x + y + z + w, check_dtypes=True)
# PJIT
def f_for_pjit(x):
token = lax.create_token(x)
# A replicated infeed
(y,), token = lax.infeed(
token,
shape=(jax.ShapedArray(x.shape, np.float32),),
partitions=(None,))
# An infeed sharded on first axis
(z,), token = lax.infeed(
token,
shape=(jax.ShapedArray(x.shape, np.float32),),
partitions=(P(nr_devices, 1),))
# An infeed sharded on second axis
(w,), token = lax.infeed(
token,
shape=(jax.ShapedArray(x.shape, np.float32),),
partitions=(P(1, nr_devices),))
return x + y + z + w
logging.info('Transfering to infeed for the pjit call')
for didx, d in enumerate(devices):
# Transfer the whole array to all devices for replicated.
d.transfer_to_infeed((y,))
# For sharded infeed, transfer only the needed slices to each device.
d.transfer_to_infeed((z[3 * didx:3 * didx + 3, :]))
d.transfer_to_infeed((w[:, 5 * didx:5 * didx + 5],))
with mesh(devices, ['d']):
logging.info('Making pjit call')
res = pjit(
f_for_pjit, in_axis_resources=(P('d'),), out_axis_resources=P('d'))(
x)
self.assertAllClose(res0, res, check_dtypes=True)
def testOutfeed(self):
devices = np.array(jax.local_devices())
nr_devices = len(devices)
shape = (nr_devices * 3, nr_devices * 5)
def f(x):
token = lax.create_token(x)
token = lax.outfeed(token, x, partitions=(None,))
token = lax.outfeed(token, x, partitions=(P(nr_devices, 1),))
token = lax.outfeed(token, x, partitions=(P(1, nr_devices),))
return x
x = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)
def dispatch():
with mesh(devices, ['d']):
logging.info('Making pjit call')
pjit(f, in_axis_resources=(P('d'),), out_axis_resources=P('d'))(x)
execution = threading.Thread(target=dispatch)
execution.start()
def check_outfeed(d, x):
y, = d.transfer_from_outfeed(
xla_client.shape_from_pyval((x,)).with_major_to_minor_layout_if_absent())
self.assertAllClose(x, y, check_dtypes=True)
logging.info('Transfering from outfeed for the pjit call')
for didx, d in enumerate(devices):
# Transfer the whole array from all devices for replicated.
check_outfeed(d, x)
# For sharded outfeed, the results are sliced.
check_outfeed(d, x[3 * didx:3 * didx + 3, :])
check_outfeed(d, x[:, 5 * didx:5 * didx + 5])
execution.join()
@curry
def check_1d_2d_mesh(f, set_mesh):
return parameterized.named_parameters(
{"testcase_name": "_" + name, "mesh": mesh, "resources": resources}
for name, mesh, resources in (
("2", (("x", 2),), "x"),
("2x1", (("x", 2), ("y", 1)), ("x", "y")),
("2x2", (("x", 2), ("y", 2)), ("x", "y")),
))(jtu.with_mesh_from_kwargs(f) if set_mesh else f)
def spec_regex(s):
return str(s).replace(r"(", r"\(").replace(r")", r"\)")
class PJitErrorTest(jtu.JaxTestCase):
@check_1d_2d_mesh(set_mesh=True)
def testNonDivisibleArgs(self, mesh, resources):
x = jnp.ones((3, 2))
spec = P(resources, None)
mesh_size = str(np.prod([dim[1] for dim in mesh], dtype=np.int64))
with self.assertRaisesRegex(ValueError,
r"One of pjit arguments.*" + spec_regex(spec) + r".*"
r"implies that the size of its dimension 0 should be "
r"divisible by " + mesh_size + r", but it is equal to 3"):
pjit(lambda x: x, in_axis_resources=spec, out_axis_resources=None)(x)
@check_1d_2d_mesh(set_mesh=True)
def testNonDivisibleOuts(self, mesh, resources):
x = jnp.ones((3, 2))
spec = P(resources, None)
mesh_size = str(np.prod([dim[1] for dim in mesh], dtype=np.int64))
with self.assertRaisesRegex(ValueError,
r"One of pjit outputs.*" + spec_regex(spec) + r".*"
r"implies that the size of its dimension 0 should be "
r"divisible by " + mesh_size + r", but it is equal to 3"):
pjit(lambda x: x, in_axis_resources=None, out_axis_resources=P(resources, None))(x)
@check_1d_2d_mesh(set_mesh=True)
def testNonDivisibleConstraint(self, mesh, resources):
x = jnp.ones((3, 2))
spec = P(resources,)
mesh_size = str(np.prod([dim[1] for dim in mesh], dtype=np.int64))
with self.assertRaisesRegex(ValueError,
r"One of with_sharding_constraint arguments"
r".*" + spec_regex(spec) + r".*implies that the size of "
r"its dimension 0 should be divisible by " + mesh_size +
r", but it is equal to 3"):
pjit(lambda x: with_sharding_constraint(x, spec),
in_axis_resources=None, out_axis_resources=None)(x)
@check_1d_2d_mesh(set_mesh=False)
@jtu.with_mesh([('z', 1)])
def testUndefinedResourcesArgs(self, mesh, resources):
x = jnp.ones((2, 2))
spec = P(resources,)
with self.assertRaisesRegex(ValueError,
r"One of pjit arguments.*" + spec_regex(spec) + r", "
r"but resource axis x is undefined."):
pjit(lambda x: x, in_axis_resources=spec, out_axis_resources=None)(x)
@check_1d_2d_mesh(set_mesh=False)
@jtu.with_mesh([('z', 1)])
def testUndefinedResourcesOuts(self, mesh, resources):
x = jnp.ones((2, 2))
spec = P(resources,)
with self.assertRaisesRegex(ValueError,
r"One of pjit outputs.*" + spec_regex(spec) + r", "
r"but resource axis x is undefined."):
pjit(lambda x: x, in_axis_resources=None, out_axis_resources=spec)(x)
@check_1d_2d_mesh(set_mesh=False)
@jtu.with_mesh([('z', 1)])
def testUndefinedResourcesConstraint(self, mesh, resources):
x = jnp.ones((2, 2))
spec = P(resources,)
with self.assertRaisesRegex(ValueError,
r"One of with_sharding_constraint arguments"
r".*" + spec_regex(spec) + r", but resource axis "
r"x is undefined."):
pjit(lambda x: with_sharding_constraint(x, spec),
in_axis_resources=None, out_axis_resources=None)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testRankTooLowArgs(self):
x = jnp.arange(2)
spec = P('x', 'y')
error = (r"One of pjit arguments.*" + spec_regex(spec) + r", which implies "
r"that it has a rank of at least 2, but it is 1")
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: x.sum(), in_axis_resources=spec, out_axis_resources=None)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testRankTooLowOuts(self):
x = jnp.arange(2)
spec = P('x', 'y')
error = (r"One of pjit outputs.*" + spec_regex(spec) + r", which implies "
r"that it has a rank of at least 2, but it is 0")
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: x.sum(), in_axis_resources=None, out_axis_resources=spec)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testRankTooLowConstraint(self):
x = jnp.arange(2)
spec = P('x', 'y')
error = (r"One of with_sharding_constraint arguments " +
r"was given.*" + spec_regex(spec) + r", which implies "
r"that it has a rank of at least 2, but it is 1")
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: with_sharding_constraint(x, spec),
in_axis_resources=None, out_axis_resources=None)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testRepeatedInResources(self):
x = jnp.arange(2)
for spec in [P('x', 'x'), P('x', ('y', 'x'))]:
error = (r"A single in_axis_resources specification can map every mesh "
r"axis to at most one positional dimension, but " +
spec_regex(spec) + " has duplicate entries for `x`")
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: x, in_axis_resources=spec, out_axis_resources=None)(x)
@jtu.with_mesh([('x', 2), ('y', 1)])
def testRepeatedOutResources(self):
x = jnp.arange(2)
for spec in [P('x', 'x'), P('x', ('y', 'x'))]:
error = (r"A single out_axis_resources specification can map every mesh "
r"axis to at most one positional dimension, but " +
spec_regex(spec) + " has duplicate entries for `x`")
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: x, in_axis_resources=None, out_axis_resources=spec)(x)
@jtu.with_mesh([('x', 2)])
def testInputShardsXMapAxis(self):
spec = P('x')
f = xmap(pjit(lambda x: x + 2, in_axis_resources=spec, out_axis_resources=None),
in_axes=['i', ...], out_axes=['i', ...], axis_resources={'i': 'x'})
x = jnp.arange(4).reshape((2, 2))
error = (r"pjit input has an axis resources specification of " +
spec_regex(spec) + r" that uses one or more mesh axes already used by "
r"xmap to partition a named axis appearing in its named_shape \(both "
r"use mesh axes `x`\)")
with self.assertRaisesRegex(JAXTypeError, error):
f(x)
@jtu.with_mesh([('x', 2)])
def testOutputShardsXMapAxis(self):
spec = P('x')
f = xmap(pjit(lambda x: x + 2, in_axis_resources=None, out_axis_resources=spec),
in_axes=['i', ...], out_axes=['i', ...], axis_resources={'i': 'x'})
x = jnp.arange(4).reshape((2, 2))
error = (r"pjit output has an axis resources specification of " +
spec_regex(spec) + r" that uses one or more mesh axes already used by "
r"xmap to partition a named axis appearing in its named_shape \(both "
r"use mesh axes `x`\)")
with self.assertRaisesRegex(JAXTypeError, error):
f(x)
@jtu.with_mesh([('x', 2)])
def testConstraintShardsXMapAxis(self):
spec = P('x')
f = xmap(lambda x: with_sharding_constraint(x, axis_resources=spec),
in_axes=['i', ...], out_axes=['i', ...], axis_resources={'i': 'x'})
x = jnp.arange(4).reshape((2, 2))
error = (r"with_sharding_constraint input has an axis resources specification of " +
spec_regex(spec) + r" that uses one or more mesh axes already used by "
r"xmap to partition a named axis appearing in its named_shape \(both "
r"use mesh axes `x`\)")
with self.assertRaisesRegex(JAXTypeError, error):
f(x)
@jtu.with_mesh([('x', 2)])
def testCatchesInnerXMapErrors(self):
f = pjit(xmap(lambda x, y: x, in_axes=(['i'], ['j']), out_axes=['i', 'j'],
axis_resources={'i': 'x', 'j': 'x'}),
in_axis_resources=None, out_axis_resources=None)
x = jnp.arange(4)
with self.assertRaises(JAXTypeError):
f(x, x)
def testEmptyMesh(self):
error = (r"pjit requires a non-empty mesh! Are you sure that it's defined "
r"at the call site?")
with self.assertRaisesRegex(RuntimeError, error):
pjit(lambda x: x, in_axis_resources=None, out_axis_resources=None)(jnp.arange(4))
@jtu.with_mesh([('x', 2), ('y', 2)])
def testLinearizeNotImplemented(self):
# pending https://github.com/google/jax/pull/6876
@partial(pjit,
in_axis_resources=(P(None, 'x', 'y'), P('y')),
out_axis_resources=P('x'))
def f(x, y):
return x @ y
x_shape = (8, 6, 4)
y_shape = (4, 2)
x = jnp.arange(np.prod(x_shape)).reshape(x_shape)
y = jnp.arange(np.prod(y_shape)).reshape(y_shape)
with self.assertRaisesRegex(NotImplementedError, "6876"):
jax.linearize(f, x, y)
@jtu.with_mesh([('x', 2)])
def testAxisResourcesMismatch(self):
x = jnp.ones([])
p = [None, None, None]
pjit(lambda x: x, (p,), p)([x, x, x]) # OK
error = re.escape(
r"pjit in_axis_resources specification must be a tree prefix of the "
r"corresponding value, got specification (None, None, None) for value "
r"tree PyTreeDef((*, *)). Note that pjit in_axis_resources that are "
r"non-trivial pytrees should always be wrapped in a tuple representing "
r"the argument list.")
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x, y: x, p, p)(x, x) # Error, but make sure we hint at tupling
# TODO(apaszke): Disable implicit list casts and enable this
# error = re.escape(
# r"pjit in_axis_resources specification must be a tree prefix of the "
# r"corresponding value, got specification (None, None, None) for value "
# r"tree PyTreeDef(([*, *, *],)). Note that pjit in_axis_resources that "
# r"are non-trivial pytrees should always be wrapped in a tuple representing "
# r"the argument list. In particular, you're passing in a single argument "
# r"which means that pjit in_axis_resources might need to be wrapped in a "
# r"singleton tuple.")
# with self.assertRaisesRegex(ValueError, error):
# pjit(lambda x: x, p, p)([x, x, x]) # Error, but make sure we hint at singleton tuple
error = re.escape(
r"pjit out_axis_resources specification must be a tree prefix of the "
r"corresponding value, got specification [[None, None, None], None] for "
r"value tree PyTreeDef([*, *, *]).")
with self.assertRaisesRegex(ValueError, error):
pjit(lambda x: x, (p,), [p, None])([x, x, x]) # Error, we raise a generic tree mismatch message
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
|
old_webdemo.py | #!/usr/bin/env python
import sys
import os
import threading
import traceback
import json
import multiprocessing
import subprocess
import http
import html
import urllib
import argparse
from .aserver import AsyncCache, AsyncTCPServer, AsyncHTTPRequestHandler
from ..fpbench import fpcparser
from ..arithmetic import native, np
from ..arithmetic import softfloat, softposit
from ..arithmetic import ieee754, posit
from ..arithmetic import sinking
from ..arithmetic import canonicalize
from ..arithmetic import evalctx
here = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(here, 'index.html'), 'rb') as f:
index = f.read()
with open(os.path.join(here, 'evaluate.html'), 'rb') as f:
evaluate_page = f.read()
with open(os.path.join(here, 'translate.html'), 'rb') as f:
translate_page = f.read()
with open(os.path.join(here, 'titanic.css'), 'rb') as f:
css = f.read()
with open(os.path.join(here, 'titanfp.min.js'), 'rb') as f:
bundle = f.read()
with open(os.path.join(here, '../../../www/favicon.ico'), 'rb') as f:
favicon = f.read()
with open(os.path.join(here, '../../../www/piceberg_round.png'), 'rb') as f:
logo = f.read()
fpbench_root = '/home/bill/private/research/origin-FPBench'
fpbench_tools = os.path.join(fpbench_root, 'tools')
fpbench_benchmarks = os.path.join(fpbench_root, 'benchmarks')
def run_tool(toolname, core, *args):
tool = subprocess.Popen(
args=['racket', os.path.join(fpbench_tools, toolname), *args],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout_data, stderr_data = tool.communicate(input=core.sexp.encode('utf-8'))
success = True
retval = tool.wait()
if retval != 0:
success = False
print('subprocess:\n {}\nreturned {:d}'.format(' '.join(tool.args), retval),
file=sys.stderr, flush=True)
if stderr_data:
print(stderr_data, file=sys.stderr, flush=True)
return success, stdout_data.decode('utf-8')
def filter_cores(*args, benchmark_dir = fpbench_benchmarks):
if not os.path.isdir(benchmark_dir):
raise ValueError('{}: not a directory'.format(benchmark_dir))
names = os.listdir(benchmark_dir)
benchmark_files = [name for name in names
if name.lower().endswith('.fpcore')
and os.path.isfile(os.path.join(benchmark_dir, name))]
cat = subprocess.Popen(
cwd=benchmark_dir,
args=['cat', *benchmark_files],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
cat.stdin.close()
tool = subprocess.Popen(
args=['racket', os.path.join(fpbench_tools, 'filter.rkt'), *args],
stdin=cat.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout_data, stderr_data = tool.communicate()
# cleanup
success = True
for proc in [cat, tool]:
retval = proc.wait()
if retval != 0:
success = False
print('subprocess:\n {}\nreturned {:d}'.format(' '.join(proc.args), retval),
file=sys.stderr, flush=True)
cat_stderr_data = cat.stderr.read()
cat.stderr.close()
if cat_stderr_data:
print(cat_stderr_data, file=sys.stderr, flush=True)
if stderr_data:
print(stderr_data, file=sys.stderr, flush=True)
return success, stdout_data.decode('utf-8')
def demo_tool(success, output):
if success:
return output
else:
return 'Error - tool subprocess returned nonzero value'
def demo_arith(evaluator, arguments, core, ctx=None):
if arguments is None:
try:
return str(evaluator(core))
except Exception:
print('Exception in FPCore evaluation\n evaluator={}\n args={}\n core={}'
.format(repr(evaluator), repr(arguments), core.sexp))
traceback.print_exc()
return 'Error evaluating FPCore.'
else:
inputs = arguments.strip().split()
if len(inputs) != len(core.inputs):
return 'Error - wrong number of arguments (core expects {:d})'.format(len(core.inputs))
try:
return str(evaluator(core, inputs, ctx))
except Exception:
print('Exception in FPCore evaluation\n evaluator={}\n args={}\n core={}'
.format(repr(evaluator), repr(arguments), core.sexp))
traceback.print_exc()
return 'Error evaluating FPCore.'
class RaisingArgumentParser(argparse.ArgumentParser):
def error(self, message):
raise ValueError('unable to parse inputs')
DEFAULT_PROPAGATE = {'precision', 'round', 'math-library'}
DEFAULT_RECURSE = {'pre', 'spec'}
def parse_canon_args(args):
parser = RaisingArgumentParser(add_help=False)
parser.add_argument('--default', action='store_true')
parser.add_argument('--recurse', type=str, nargs='*')
parser.add_argument('--propagate', type=str, nargs='*')
ns = parser.parse_args(args.strip().split())
if ns.recurse is None and ns.propagate is None:
return DEFAULT_RECURSE, DEFAULT_PROPAGATE
if ns.recurse is None:
recurse = set()
else:
recurse = set(ns.recurse)
if ns.propagate is None:
propagate = set()
else:
propagate = set(ns.propagate)
if ns.default:
recurse.update(DEFAULT_RECURSE)
propagate.update(DEFAULT_PROPAGATE)
return recurse, propagate
def demo_canon(evaluator, arguments, core, use_prop=False):
try:
recurse, propagate = parse_canon_args(arguments)
except Exception:
print('Exception parsing arguments for canonicalizer: {}'.format(repr(arguments)))
traceback.print_exc()
return 'Error parsing arguments.'
try:
if use_prop:
return evaluator(core, recurse=recurse, propagate=propagate).sexp
else:
return evaluator(core, recurse=recurse).sexp
except Exception:
print('Exception in FPCore translation\n translator={}\n recurse={}\n propagate={}\n use_prop={}\n core={}'
.format(repr(evaluator), repr(recurse), repr(propagate), repr(use_prop), core.sexp))
traceback.print_exc()
return 'Error translating FPCore.'
class TitanfpHTTPRequestHandler(AsyncHTTPRequestHandler):
def import_core_from_query(self, content, query):
qd = urllib.parse.parse_qs(query)
return content.decode('utf-8').format(qd.get('core', [''])[-1]).encode('utf-8')
def construct_content(self, data):
pr = self.translate_path()
if pr.path == '/titanfp.min.js':
response = http.server.HTTPStatus.OK
msg = None
headers = (
('Content-Type', 'text/javascript'),
)
content = bundle
elif pr.path == '/titanic.css':
response = http.server.HTTPStatus.OK
msg = None
headers = (
('Content-Type', 'text/css'),
)
content = css
else:
response = http.server.HTTPStatus.OK
msg = None
if data is None:
if pr.path == '/favicon.ico':
headers = (
('Content-Type', 'image/x-icon'),
)
content = favicon
elif pr.path == '/piceberg_round.png':
headers = (
('Content-Type', 'image/png'),
)
content = logo
# elif pr.path == '/evaluate':
else:
headers = (
('Content-Type', 'text/html'),
)
content = self.import_core_from_query(evaluate_page, pr.query)
# elif pr.path == '/translate':
# headers = (
# ('Content-Type', 'text/html'),
# )
# content = self.import_core_from_query(translate_page, pr.query)
# else:
# print(pr)
# headers = (
# ('Content-Type', 'text/html'),
# )
# content = index
else:
try:
payload = json.loads(data.decode('utf-8'))
except Exception as e:
print('Malformed data payload:\n{}'.format(repr(data)))
traceback.print_exc()
try:
core = fpcparser.compile(payload['core'])[0]
except Exception:
print('Exception parsing FPCore {}'.format(repr(payload['core'])))
traceback.print_exc()
core = None
output = 'Error - unable to parse FPCore'
try:
if core is not None:
backend = payload['backend']
if backend == 'sink':
ctx = ieee754.ieee_ctx(int(payload['w']), int(payload['p']))
output = demo_arith(sinking.Interpreter.interpret, payload['inputs'], core, ctx)
elif backend == 'ieee754':
ctx = ieee754.ieee_ctx(int(payload['w']), int(payload['p']))
output = demo_arith(ieee754.Interpreter.interpret, payload['inputs'], core, ctx)
elif backend == 'posit':
ctx = posit.posit_ctx(int(payload['es']), int(payload['nbits']))
output = demo_arith(posit.Interpreter.interpret, payload['inputs'], core, ctx)
elif backend == 'native':
output = demo_arith(native.Interpreter.interpret, payload['inputs'], core)
elif backend == 'np':
output = demo_arith(np.Interpreter.interpret, payload['inputs'], core)
elif backend == 'softfloat':
output = demo_arith(softfloat.Interpreter.interpret, payload['inputs'], core)
elif backend == 'softposit':
output = demo_arith(softposit.Interpreter.interpret, payload['inputs'], core)
elif backend == 'canonicalize':
output = demo_canon(canonicalize.Canonicalizer.translate, payload['inputs'], core, use_prop=True)
elif backend == 'condense':
output = demo_canon(canonicalize.Condenser.translate, payload['inputs'], core, use_prop=False)
elif backend == 'minimize':
output = demo_canon(canonicalize.Minimizer.translate, payload['inputs'], core, use_prop=False)
elif backend == 'fpcore':
inputs = payload['inputs'].strip().split()
if len(inputs) != len(core.inputs):
output = 'Error - wrong number of arguments (core expects {:d})'.format(len(core.inputs))
else:
output = demo_tool(*run_tool('fpcore.rkt', core, *inputs))
elif backend == 'core2c':
output = demo_tool(*run_tool('core2c.rkt', core))
elif backend == 'core2js':
output = demo_tool(*run_tool('core2js.rkt', core))
elif backend == 'core2smtlib2':
output = demo_tool(*run_tool('core2smtlib2.rkt', core))
# elif backend == 'filter':
# inputs = payload['inputs'].strip().split()
# output = demo_tool(*filter_cores(*inputs))
else:
output = 'Unknown backend ' + repr(backend)
except Exception as e:
print('Exception running backend\n payload={}'.format(repr(payload)))
traceback.print_exc()
output = 'Error running backend.'
headers = (
('Content-Type', 'text/plain'),
)
content = html.escape(str(output)).encode('utf-8')
return response, msg, headers, content
def run():
import argparse
ncores = os.cpu_count()
#default_pool_size = max(1, min(ncores - 1, (ncores // 2) + 1))
default_pool_size = 2
parser = argparse.ArgumentParser()
parser.add_argument('--cache', type=int, default=1,
help='number of requests to cache')
parser.add_argument('--workers', type=int, default=default_pool_size,
help='number of worker processes to run in parallel')
parser.add_argument('--host', type=str, default='localhost',
help='server host')
parser.add_argument('--port', type=int, default=8000,
help='server port')
args = parser.parse_args()
cache = AsyncCache(args.cache)
with multiprocessing.Pool(args.workers, maxtasksperchild=100) as pool:
class CustomHTTPRequestHandler(TitanfpHTTPRequestHandler):
the_cache = cache
the_pool = pool
print('caching {:d} requests'.format(args.cache))
print('{:d} worker processes'.format(args.workers))
with AsyncTCPServer((args.host, args.port,), CustomHTTPRequestHandler) as server:
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
print('server on thread:', server_thread.name)
print('close stdin to stop.')
for line in sys.stdin:
pass
print('stdin closed, stopping.')
pool.close()
print('workers closing...')
pool.join()
print('workers joined successfully.')
server.shutdown()
print('goodbye!')
if __name__ == '__main__':
run()
|
MicrosoftTeams.py | import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import requests
from distutils.util import strtobool
from flask import Flask, request, Response
from gevent.pywsgi import WSGIServer
import jwt
import time
from threading import Thread
from typing import Match, Union, Optional, cast, Dict, Any, List, Tuple
import re
from jwt.algorithms import RSAAlgorithm
from tempfile import NamedTemporaryFile
from traceback import format_exc
# Disable insecure warnings
requests.packages.urllib3.disable_warnings()
''' GLOBAL VARIABLES'''
PARAMS: dict = demisto.params()
BOT_ID: str = PARAMS.get('bot_id', '')
BOT_PASSWORD: str = PARAMS.get('bot_password', '')
USE_SSL: bool = not PARAMS.get('insecure', False)
APP: Flask = Flask('demisto-teams')
PLAYGROUND_INVESTIGATION_TYPE: int = 9
GRAPH_BASE_URL: str = 'https://graph.microsoft.com'
INCIDENT_TYPE: str = PARAMS.get('incidentType', '')
URL_REGEX: str = r'http[s]?://(?:[a-zA-Z]|[0-9]|[:/$_@.&+#-]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
ENTITLEMENT_REGEX: str = \
r'(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}'
MENTION_REGEX = r'^@([^@;]+);| @([^@;]+);'
ENTRY_FOOTER: str = 'From Microsoft Teams'
INCIDENT_NOTIFICATIONS_CHANNEL = 'incidentNotificationChannel'
MESSAGE_TYPES: dict = {
'mirror_entry': 'mirrorEntry',
'incident_opened': 'incidentOpened',
'status_changed': 'incidentStatusChanged'
}
if '@' in BOT_ID:
BOT_ID, tenant_id, service_url = BOT_ID.split('@')
set_integration_context({'tenant_id': tenant_id, 'service_url': service_url})
''' HELPER FUNCTIONS '''
def epoch_seconds(d: datetime = None) -> int:
"""
Return the number of seconds for given date. If no date, return current.
:param d: timestamp datetime object
:return: timestamp in epoch
"""
if not d:
d = datetime.utcnow()
return int((d - datetime.utcfromtimestamp(0)).total_seconds())
def error_parser(resp_err: requests.Response, api: str = 'graph') -> str:
"""
Parses Microsoft API error message from Requests response
:param resp_err: response with error
:param api: API to query (graph/bot)
:return: string of error
"""
try:
response: dict = resp_err.json()
if api == 'graph':
error: dict = response.get('error', {})
err_str: str = f"{error.get('code', '')}: {error.get('message', '')}"
if err_str:
return err_str
elif api == 'bot':
error_description: str = response.get('error_description', '')
if error_description:
return error_description
# If no error message
raise ValueError()
except ValueError:
return resp_err.text
def translate_severity(severity: str) -> float:
"""
Translates Demisto text severity to int severity
:param severity: Demisto text severity
:return: Demisto integer severity
"""
severity_dictionary = {
'Unknown': 0.0,
'Informational': 0.5,
'Low': 1.0,
'Medium': 2.0,
'High': 3.0,
'Critical': 4.0
}
return severity_dictionary.get(severity, 0.0)
def create_incidents(demisto_user: dict, incidents: list) -> dict:
"""
Creates incidents according to a provided JSON object
:param demisto_user: The demisto user associated with the request (if exists)
:param incidents: The incidents JSON
:return: The creation result
"""
if demisto_user:
data = demisto.createIncidents(incidents, userID=demisto_user.get('id', ''))
else:
data = demisto.createIncidents(incidents)
return data
def process_incident_create_message(demisto_user: dict, message: str) -> str:
"""
Processes an incident creation message
:param demisto_user: The Demisto user associated with the message (if exists)
:param message: The creation message
:return: Creation result
"""
json_pattern: str = r'(?<=json=).*'
name_pattern: str = r'(?<=name=).*'
type_pattern: str = r'(?<=type=).*'
json_match: Optional[Match[str]] = re.search(json_pattern, message)
created_incident: Union[dict, list]
data: str = str()
if json_match:
if re.search(name_pattern, message) or re.search(type_pattern, message):
data = 'No other properties other than json should be specified.'
else:
incidents_json: str = json_match.group()
incidents: Union[dict, list] = json.loads(incidents_json.replace('“', '"').replace('”', '"'))
if not isinstance(incidents, list):
incidents = [incidents]
created_incident = create_incidents(demisto_user, incidents)
if not created_incident:
data = 'Failed creating incidents.'
else:
name_match: Optional[Match[str]] = re.search(name_pattern, message)
if not name_match:
data = 'Please specify arguments in the following manner: name=<name> type=[type] or json=<json>.'
else:
incident_name: str = re.sub('type=.*', '', name_match.group()).strip()
incident_type: str = str()
type_match: Optional[Match[str]] = re.search(type_pattern, message)
if type_match:
incident_type = re.sub('name=.*', '', type_match.group()).strip()
incident: dict = {'name': incident_name}
incident_type = incident_type or INCIDENT_TYPE
if incident_type:
incident['type'] = incident_type
created_incident = create_incidents(demisto_user, [incident])
if not created_incident:
data = 'Failed creating incidents.'
if created_incident:
if isinstance(created_incident, list):
created_incident = created_incident[0]
created_incident = cast(Dict[Any, Any], created_incident)
server_links: dict = demisto.demistoUrls()
server_link: str = server_links.get('server', '')
data = f"Successfully created incident {created_incident.get('name', '')}.\n" \
f"View it on: {server_link}#/WarRoom/{created_incident.get('id', '')}"
return data
def is_investigation_mirrored(investigation_id: str, mirrored_channels: list) -> int:
"""
Checks if investigation is already mirrored
:param investigation_id: Investigation ID to check if mirrored
:param mirrored_channels: List of mirrored channels to check if investigation is mirrored in
:return: Index in mirrored channels list if mirrored, else -1
"""
for index, channel in enumerate(mirrored_channels):
if channel.get('investigation_id') == investigation_id:
return index
return -1
def urlify_hyperlinks(message: str) -> str:
"""
Turns URL to markdown hyper-link
e.g. https://www.demisto.com -> [https://www.demisto.com](https://www.demisto.com)
:param message: Message to look for URLs in
:return: Formatted message with hyper-links
"""
formatted_message: str = message
# URLify markdown hyperlinks
urls = re.findall(URL_REGEX, message)
for url in urls:
formatted_message = formatted_message.replace(url, f'[{url}]({url})')
return formatted_message
def get_team_member(integration_context: dict, team_member_id: str) -> dict:
"""
Searches for a team member
:param integration_context: Cached object to search for team member in
:param team_member_id: Team member ID to search for
:return: Found team member object
"""
team_member: dict = dict()
teams: list = json.loads(integration_context.get('teams', '[]'))
for team in teams:
team_members: list = team.get('team_members', [])
for member in team_members:
if member.get('id') == team_member_id:
team_member['username'] = member.get('name', '')
team_member['user_email'] = member.get('userPrincipalName', '')
return team_member
raise ValueError('Team member was not found')
def get_team_member_id(requested_team_member: str, integration_context: dict) -> str:
"""
Gets team member ID based on name, email or principal name
:param requested_team_member: Team member name / principal name / email to look for
:param integration_context: Cached object to search for team member in
:return: Team member ID
"""
teams: list = json.loads(integration_context.get('teams', '[]'))
for team in teams:
team_members: list = team.get('team_members', [])
for team_member in team_members:
if requested_team_member in {team_member.get('name', ''), team_member.get('userPrincipalName', '')}:
return team_member.get('id')
raise ValueError(f'Team member {requested_team_member} was not found')
def create_adaptive_card(body: list, actions: list = None) -> dict:
"""
Creates Microsoft Teams adaptive card object given body and actions
:param body: Adaptive card data
:param actions: Adaptive card actions
:return: Adaptive card object
"""
adaptive_card: dict = {
'contentType': 'application/vnd.microsoft.card.adaptive',
'content': {
'$schema': 'http://adaptivecards.io/schemas/adaptive-card.json',
'version': '1.0',
'type': 'AdaptiveCard',
'msteams': {
'width': 'Full'
},
'body': body
}
}
if actions:
adaptive_card['content']['actions'] = actions
return adaptive_card
def process_tasks_list(data_by_line: list) -> dict:
"""
Processes tasks list assigned to user given from Demisto server and creates adaptive card
:param data_by_line: List of tasks to process
:return: Adaptive card of assigned tasks
"""
body: list = list()
for line in data_by_line[2:]:
split_data: list = [stat.strip() for stat in line.split('|')]
body.append({
'type': 'FactSet',
'facts': [
{
'title': 'Task:',
'value': split_data[0]
},
{
'title': 'Incident:',
'value': split_data[1]
},
{
'title': 'Due:',
'value': split_data[2]
},
{
'title': 'Link:',
'value': f'[{split_data[3]}]({split_data[3]})'
}
]
})
return create_adaptive_card(body)
def process_incidents_list(data_by_line: list) -> dict:
"""
Processes incidents list assigned to user given from Demisto server and creates adaptive card
:param data_by_line: List of incidents to process
:return: Adaptive card of assigned incidents
"""
body: list = list()
for line in data_by_line[2:]:
split_data: list = [stat.strip() for stat in line.split('|')]
body.append({
'type': 'FactSet',
'facts': [
{
'title': 'ID:',
'value': split_data[0]
},
{
'title': 'Name:',
'value': split_data[1]
},
{
'title': 'Status:',
'value': split_data[2]
},
{
'title': 'Type:',
'value': split_data[3]
},
{
'title': 'Owner:',
'value': split_data[4]
},
{
'title': 'Created:',
'value': split_data[5]
},
{
'title': 'Link:',
'value': f'[{split_data[6]}]({split_data[6]})'
}
]
})
return create_adaptive_card(body)
def process_mirror_or_unknown_message(message: str) -> dict:
"""
Processes mirror investigation command or unknown direct message and creates adaptive card
:param message: The direct message to process
:return: Adaptive card of mirror response / unknown message
"""
body: list = [{
'type': 'TextBlock',
'text': message.replace('\n', '\n\n'),
'wrap': True
}]
return create_adaptive_card(body)
def process_ask_user(message: str) -> dict:
"""
Processes ask user message and creates adaptive card
:param message: The question object
:return: Adaptive card of the question to send
"""
message_object: dict = json.loads(message)
text: str = message_object.get('message_text', '')
entitlement: str = message_object.get('entitlement', '')
options: list = message_object.get('options', [])
investigation_id: str = message_object.get('investigation_id', '')
task_id: str = message_object.get('task_id', '')
body = [
{
'type': 'TextBlock',
'text': text
}
]
actions: list = list()
for option in options:
actions.append({
'type': 'Action.Submit',
'title': option,
'data': {
'response': option,
'entitlement': entitlement,
'investigation_id': investigation_id,
'task_id': task_id
}
})
return create_adaptive_card(body, actions)
def get_bot_access_token() -> str:
"""
Retrieves Bot Framework API access token, either from cache or from Microsoft
:return: The Bot Framework API access token
"""
integration_context: dict = get_integration_context()
access_token: str = integration_context.get('bot_access_token', '')
valid_until: int = integration_context.get('bot_valid_until', int)
if access_token and valid_until:
if epoch_seconds() < valid_until:
return access_token
url: str = 'https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token'
data: dict = {
'grant_type': 'client_credentials',
'client_id': BOT_ID,
'client_secret': BOT_PASSWORD,
'scope': 'https://api.botframework.com/.default'
}
response: requests.Response = requests.post(
url,
data=data,
verify=USE_SSL
)
if not response.ok:
error = error_parser(response, 'bot')
raise ValueError(f'Failed to get bot access token [{response.status_code}] - {error}')
try:
response_json: dict = response.json()
access_token = response_json.get('access_token', '')
expires_in: int = response_json.get('expires_in', 3595)
time_now: int = epoch_seconds()
time_buffer = 5 # seconds by which to shorten the validity period
if expires_in - time_buffer > 0:
expires_in -= time_buffer
integration_context['bot_access_token'] = access_token
integration_context['bot_valid_until'] = time_now + expires_in
set_integration_context(integration_context)
return access_token
except ValueError:
raise ValueError('Failed to get bot access token')
def get_graph_access_token() -> str:
"""
Retrieves Microsoft Graph API access token, either from cache or from Microsoft
:return: The Microsoft Graph API access token
"""
integration_context: dict = get_integration_context()
access_token: str = integration_context.get('graph_access_token', '')
valid_until: int = integration_context.get('graph_valid_until', int)
if access_token and valid_until:
if epoch_seconds() < valid_until:
return access_token
tenant_id: str = integration_context.get('tenant_id', '')
if not tenant_id:
raise ValueError(
'Did not receive tenant ID from Microsoft Teams, verify the messaging endpoint is configured correctly. '
'See https://xsoar.pan.dev/docs/reference/integrations/microsoft-teams#troubleshooting for more information'
)
url: str = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'
data: dict = {
'grant_type': 'client_credentials',
'client_id': BOT_ID,
'scope': 'https://graph.microsoft.com/.default',
'client_secret': BOT_PASSWORD
}
response: requests.Response = requests.post(
url,
data=data,
verify=USE_SSL
)
if not response.ok:
error = error_parser(response)
raise ValueError(f'Failed to get Graph access token [{response.status_code}] - {error}')
try:
response_json: dict = response.json()
access_token = response_json.get('access_token', '')
expires_in: int = response_json.get('expires_in', 3595)
time_now: int = epoch_seconds()
time_buffer = 5 # seconds by which to shorten the validity period
if expires_in - time_buffer > 0:
expires_in -= time_buffer
integration_context['graph_access_token'] = access_token
integration_context['graph_valid_until'] = time_now + expires_in
set_integration_context(integration_context)
return access_token
except ValueError:
raise ValueError('Failed to get Graph access token')
def http_request(
method: str, url: str = '', json_: dict = None, api: str = 'graph', params: Optional[Dict] = None
) -> Union[dict, list]:
"""A wrapper for requests lib to send our requests and handle requests and responses better
Headers to be sent in requests
Args:
method (str): any restful method
url (str): URL to query
json_ (dict): HTTP JSON body
api (str): API to query (graph/bot)
params (dict): Object of key-value URL query parameters
Returns:
Union[dict, list]: The response in list or dict format.
"""
if api == 'graph':
access_token = get_graph_access_token()
else: # Bot Framework API
access_token = get_bot_access_token()
headers: dict = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
try:
response: requests.Response = requests.request(
method,
url,
headers=headers,
json=json_,
verify=USE_SSL,
params=params,
)
if not response.ok:
error: str = error_parser(response, api)
raise ValueError(f'Error in API call to Microsoft Teams: [{response.status_code}] - {error}')
if response.status_code in {202, 204}:
# Delete channel or remove user from channel return 204 if successful
# Update message returns 202 if the request has been accepted for processing
return {}
if response.status_code == 201:
# For channel creation query, we get a body in the response, otherwise we should just return
if not response.content:
return {}
try:
return response.json()
except ValueError:
raise ValueError(f'Error in API call to Microsoft Teams: {response.text}')
except requests.exceptions.ConnectTimeout:
error_message = 'Connection Timeout Error - potential reason may be that Microsoft Teams is not ' \
'accessible from your host.'
raise ConnectionError(error_message)
except requests.exceptions.SSLError:
error_message = 'SSL Certificate Verification Failed - try selecting \'Trust any certificate\' in ' \
'the integration configuration.'
raise ConnectionError(error_message)
except requests.exceptions.ProxyError:
error_message = 'Proxy Error - if \'Use system proxy settings\' in the integration configuration has been ' \
'selected, try deselecting it.'
raise ConnectionError(error_message)
def integration_health():
bot_framework_api_health = 'Operational'
graph_api_health = 'Operational'
try:
get_bot_access_token()
except ValueError as e:
bot_framework_api_health = f'Non operational - {str(e)}'
try:
get_graph_access_token()
except ValueError as e:
graph_api_health = f'Non operational - {str(e)}'
api_health_output: list = [{
'Bot Framework API Health': bot_framework_api_health,
'Graph API Health': graph_api_health
}]
adi_health_human_readable: str = tableToMarkdown('Microsoft API Health', api_health_output)
mirrored_channels_output = list()
integration_context: dict = get_integration_context()
teams: list = json.loads(integration_context.get('teams', '[]'))
for team in teams:
mirrored_channels: list = team.get('mirrored_channels', [])
for channel in mirrored_channels:
mirrored_channels_output.append({
'Team': team.get('team_name'),
'Channel': channel.get('channel_name'),
'Investigation ID': channel.get('investigation_id')
})
mirrored_channels_human_readable: str
if mirrored_channels_output:
mirrored_channels_human_readable = tableToMarkdown(
'Microsoft Teams Mirrored Channels', mirrored_channels_output
)
else:
mirrored_channels_human_readable = 'No mirrored channels.'
demisto.results({
'ContentsFormat': formats['json'],
'Type': entryTypes['note'],
'HumanReadable': adi_health_human_readable + mirrored_channels_human_readable,
'Contents': adi_health_human_readable + mirrored_channels_human_readable
})
def validate_auth_header(headers: dict) -> bool:
"""
Validated authorization header provided in the bot activity object
:param headers: Bot activity headers
:return: True if authorized, else False
"""
parts: list = headers.get('Authorization', '').split(' ')
if len(parts) != 2:
return False
scehma: str = parts[0]
jwt_token: str = parts[1]
if scehma != 'Bearer' or not jwt_token:
demisto.info('Authorization header validation - failed to verify schema')
return False
decoded_payload: dict = jwt.decode(jwt=jwt_token, options={'verify_signature': False})
issuer: str = decoded_payload.get('iss', '')
if issuer != 'https://api.botframework.com':
demisto.info('Authorization header validation - failed to verify issuer')
return False
integration_context: dict = get_integration_context()
open_id_metadata: dict = json.loads(integration_context.get('open_id_metadata', '{}'))
keys: list = open_id_metadata.get('keys', [])
unverified_headers: dict = jwt.get_unverified_header(jwt_token)
key_id: str = unverified_headers.get('kid', '')
key_object: dict = dict()
# Check if we got the requested key in cache
for key in keys:
if key.get('kid') == key_id:
key_object = key
break
if not key_object:
# Didn't find requested key in cache, getting new keys
try:
open_id_url: str = 'https://login.botframework.com/v1/.well-known/openidconfiguration'
response: requests.Response = requests.get(open_id_url, verify=USE_SSL)
if not response.ok:
demisto.info(f'Authorization header validation failed to fetch open ID config - {response.reason}')
return False
response_json: dict = response.json()
jwks_uri: str = response_json.get('jwks_uri', '')
keys_response: requests.Response = requests.get(jwks_uri, verify=USE_SSL)
if not keys_response.ok:
demisto.info(f'Authorization header validation failed to fetch keys - {response.reason}')
return False
keys_response_json: dict = keys_response.json()
keys = keys_response_json.get('keys', [])
open_id_metadata['keys'] = keys
except ValueError:
demisto.info('Authorization header validation - failed to parse keys response')
return False
if not keys:
# Didn't get new keys
demisto.info('Authorization header validation - failed to get keys')
return False
# Find requested key in new keys
for key in keys:
if key.get('kid') == key_id:
key_object = key
break
if not key_object:
# Didn't find requested key in new keys
demisto.info('Authorization header validation - failed to find relevant key')
return False
endorsements: list = key_object.get('endorsements', [])
if not endorsements or 'msteams' not in endorsements:
demisto.info('Authorization header validation - failed to verify endorsements')
return False
public_key: str = RSAAlgorithm.from_jwk(json.dumps(key_object))
options = {
'verify_aud': False,
'verify_exp': True,
'verify_signature': False,
}
decoded_payload = jwt.decode(jwt_token, public_key, options=options)
audience_claim: str = decoded_payload.get('aud', '')
if audience_claim != demisto.params().get('bot_id'):
demisto.info('Authorization header validation - failed to verify audience_claim')
return False
integration_context['open_id_metadata'] = json.dumps(open_id_metadata)
set_integration_context(integration_context)
return True
''' COMMANDS + REQUESTS FUNCTIONS '''
def get_team_aad_id(team_name: str) -> str:
"""
Gets Team AAD ID
:param team_name: Team name to get AAD ID of
:return: team AAD ID
"""
integration_context: dict = get_integration_context()
if integration_context.get('teams'):
teams: list = json.loads(integration_context['teams'])
for team in teams:
if team_name == team.get('team_name', ''):
return team.get('team_aad_id', '')
url: str = f"{GRAPH_BASE_URL}/beta/groups?$filter=resourceProvisioningOptions/Any(x:x eq 'Team')"
response: dict = cast(Dict[Any, Any], http_request('GET', url))
teams = response.get('value', [])
for team in teams:
if team.get('displayName', '') == team_name:
return team.get('id', '')
raise ValueError('Could not find requested team.')
# def add_member_to_team(user_principal_name: str, team_id: str):
# url: str = f'{GRAPH_BASE_URL}/v1.0/groups/{team_id}/members/$ref'
# requestjson_: dict = {
# '@odata.id': f'{GRAPH_BASE_URL}/v1.0/directoryObjects/{user_principal_name}'
# }
# http_request('POST', url, json_=requestjson_)
def get_user(user: str) -> list:
"""Retrieves the AAD ID of requested user
Args:
user (str): Display name/mail/UPN of user to get ID of.
Return:
list: List containing the requsted user object
"""
url: str = f'{GRAPH_BASE_URL}/v1.0/users'
params = {
'$filter': f"displayName eq '{user}' or mail eq '{user}' or userPrincipalName eq '{user}'",
'$select': 'id'
}
users = cast(Dict[Any, Any], http_request('GET', url, params=params))
return users.get('value', [])
def add_user_to_channel(team_aad_id: str, channel_id: str, user_id: str):
"""
Request for adding user to channel
"""
url: str = f'{GRAPH_BASE_URL}/beta/teams/{team_aad_id}/channels/{channel_id}/members'
requestjson_: dict = {
'@odata.type': '#microsoft.graph.aadUserConversationMember',
'roles': [],
'user@odata.bind': f'https://graph.microsoft.com/beta/users/{user_id}' # disable-secrets-detection
}
http_request('POST', url, json_=requestjson_)
def add_user_to_channel_command():
"""
Add user to channel (private channel only as still in beta mode)
"""
channel_name: str = demisto.args().get('channel', '')
team_name: str = demisto.args().get('team', '')
member = demisto.args().get('member', '')
user: list = get_user(member)
if not (user and user[0].get('id')):
raise ValueError(f'User {member} was not found')
team_aad_id = get_team_aad_id(team_name)
channel_id = get_channel_id(channel_name, team_aad_id, investigation_id=None)
add_user_to_channel(team_aad_id, channel_id, user[0].get('id'))
demisto.results(f'The User "{member}" has been added to channel "{channel_name}" successfully.')
# def create_group_request(
# display_name: str, mail_enabled: bool, mail_nickname: str, security_enabled: bool,
# owners_ids: list, members_ids: list = None
# ) -> str:
# url = f'{GRAPH_BASE_URL}/v1.0/groups'
# data: dict = {
# 'displayName': display_name,
# 'groupTypes': ['Unified'],
# 'mailEnabled': mail_enabled,
# 'mailNickname': mail_nickname,
# 'securityEnabled': security_enabled,
# 'owners@odata.bind': owners_ids,
# 'members@odata.bind': members_ids or owners_ids
# }
# group_creation_response: dict = cast(Dict[Any, Any], http_request('POST', url, json_=data))
# group_id: str = group_creation_response.get('id', '')
# return group_id
#
#
# def create_team_request(group_id: str) -> str:
# url = f'{GRAPH_BASE_URL}/v1.0/groups/{group_id}/team'
# team_creation_response: dict = cast(Dict[Any, Any], http_request('PUT', url, json_={}))
# team_id: str = team_creation_response.get('id', '')
# return team_id
#
#
# def add_bot_to_team(team_id: str):
# url: str = f'{GRAPH_BASE_URL}/v1.0/teams/{team_id}/installedApps'
# bot_app_id: str = ''
# data: dict = {
# 'teamsApp@odata.bind': f'https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{bot_app_id}'
# }
# print(http_request('POST', url, json_=data))
#
#
# def create_team():
# display_name: str = demisto.args().get('display_name', '')
# mail_enabled: bool = bool(strtobool(demisto.args().get('mail_enabled', True)))
# mail_nickname: str = demisto.args().get('mail_nickname', '')
# security_enabled: bool = bool(strtobool(demisto.args().get('security_enabled', True)))
# owners = argToList(demisto.args().get('owner', ''))
# members = argToList(demisto.args().get('members', ''))
# owners_ids: list = list()
# members_ids: list = list()
# users: list = get_users()
# user_id: str = str()
# for member in members:
# found_member: bool = False
# for user in users:
# if member in {user.get('displayName', ''), user.get('mail'), user.get('userPrincipalName')}:
# found_member = True
# user_id = user.get('id', '')
# members_ids.append(f'https://graph.microsoft.com/v1.0/users/{user_id}')
# break
# if not found_member:
# demisto.results({
# 'Type': entryTypes['warning'],
# 'Contents': f'User {member} was not found',
# 'ContentsFormat': formats['text']
# })
# for owner in owners:
# found_owner: bool = False
# for user in users:
# if owner in {user.get('displayName', ''), user.get('mail'), user.get('userPrincipalName')}:
# found_owner = True
# user_id = user.get('id', '')
# owners_ids.append(f'https://graph.microsoft.com/v1.0/users/{user_id}')
# break
# if not found_owner:
# demisto.results({
# 'Type': entryTypes['warning'],
# 'Contents': f'User {owner} was not found',
# 'ContentsFormat': formats['text']
# })
# if not owners_ids:
# raise ValueError('Could not find given users to be Team owners.')
# group_id: str = create_group_request(
# display_name, mail_enabled, mail_nickname, security_enabled, owners_ids, members_ids
# )
# team_id: str = create_team_request(group_id)
# add_bot_to_team(team_id)
# demisto.results(f'Team {display_name} was created successfully')
def create_channel(team_aad_id: str, channel_name: str, channel_description: str = '') -> str:
"""
Creates a Microsoft Teams channel
:param team_aad_id: Team AAD ID to create channel in
:param channel_name: Name of channel to create
:param channel_description: Description of channel to create
:return: ID of created channel
"""
url: str = f'{GRAPH_BASE_URL}/v1.0/teams/{team_aad_id}/channels'
request_json: dict = {
'displayName': channel_name,
'description': channel_description
}
channel_data: dict = cast(Dict[Any, Any], http_request('POST', url, json_=request_json))
channel_id: str = channel_data.get('id', '')
return channel_id
def create_meeting(user_id: str, subject: str, start_date_time: str, end_date_time: str) -> dict:
"""
Creates a Microsoft Teams meeting
:param user_id: The User's ID
:param subject: The meeting's subject
:param start_date_time: The meeting's start time
:param end_date_time: The meeting's end time
:return: Dict with info about the created meeting.
"""
url: str = f'{GRAPH_BASE_URL}/v1.0/users/{user_id}/onlineMeetings'
request_json: dict = {
'subject': subject
}
if start_date_time:
request_json['startDateTime'] = start_date_time
if end_date_time:
request_json['endDateTime'] = end_date_time
channel_data: dict = cast(Dict[Any, Any], http_request('POST', url, json_=request_json))
return channel_data
def create_channel_command():
channel_name: str = demisto.args().get('channel_name', '')
channel_description: str = demisto.args().get('description', '')
team_name: str = demisto.args().get('team', '')
team_aad_id = get_team_aad_id(team_name)
channel_id: str = create_channel(team_aad_id, channel_name, channel_description)
if channel_id:
demisto.results(f'The channel "{channel_name}" was created successfully')
def create_meeting_command():
subject: str = demisto.args().get('subject', '')
start_date_time: str = demisto.args().get('start_time', '')
end_date_time: str = demisto.args().get('end_time', '')
member = demisto.args().get('member', '')
user: list = get_user(member)
if not (user and user[0].get('id')):
raise ValueError(f'User {member} was not found')
meeting_data: dict = create_meeting(user[0].get('id'), subject, start_date_time, end_date_time)
thread_id = ''
message_id = ''
if chat_info := meeting_data.get('chatInfo', {}):
thread_id = chat_info.get('threadId', '')
message_id = chat_info.get('messageId', '')
participant_id, participant_display_name = get_participant_info(meeting_data.get('participants', {}))
outputs = {
'creationDateTime': meeting_data.get('creationDateTime', ''),
'threadId': thread_id,
'messageId': message_id,
'id': meeting_data.get('id', ''),
'joinWebUrl': meeting_data.get('joinWebUrl', ''),
'participantId': participant_id,
'participantDisplayName': participant_display_name
}
result = CommandResults(
readable_output=f'The meeting "{subject}" was created successfully',
outputs_prefix='MicrosoftTeams.CreateMeeting',
outputs_key_field='id',
outputs=outputs
)
return_results(result)
def get_participant_info(participants: dict) -> Tuple[str, str]:
"""
Retrieves the participant ID and name
:param participants: The participants in the Team meeting
:return: The participant ID and name
"""
participant_id = ''
participant_display_name = ''
if participants:
user = participants.get('organizer', {}).get('identity', {}).get('user', {})
if user:
participant_id = user.get('id')
participant_display_name = user.get('displayName')
return participant_id, participant_display_name
def get_channel_id(channel_name: str, team_aad_id: str, investigation_id: str = None) -> str:
"""
Retrieves Microsoft Teams channel ID
:param channel_name: Name of channel to get ID of
:param team_aad_id: AAD ID of team to search channel in
:param investigation_id: Demisto investigation ID to search mirrored channel of
:return: Requested channel ID
"""
investigation_id = investigation_id or str()
integration_context: dict = get_integration_context()
teams: list = json.loads(integration_context.get('teams', '[]'))
for team in teams:
mirrored_channels: list = team.get('mirrored_channels', [])
for channel in mirrored_channels:
if channel.get('channel_name') == channel_name or channel.get('investigation_id') == investigation_id:
return channel.get('channel_id')
url: str = f'{GRAPH_BASE_URL}/v1.0/teams/{team_aad_id}/channels'
response: dict = cast(Dict[Any, Any], http_request('GET', url))
channel_id: str = ''
channels: list = response.get('value', [])
for channel in channels:
channel_display_name: str = channel.get('displayName', '')
if channel_display_name == channel_name:
channel_id = channel.get('id', '')
break
if not channel_id:
raise ValueError(f'Could not find channel: {channel_name}')
return channel_id
def get_team_members(service_url: str, team_id: str) -> list:
"""
Retrieves team members given a team
:param team_id: ID of team to get team members of
:param service_url: Bot service URL to query
:return: List of team members
"""
url: str = f'{service_url}/v3/conversations/{team_id}/members'
response: list = cast(List[Any], http_request('GET', url, api='bot'))
return response
def update_message(service_url: str, conversation_id: str, activity_id: str, text: str):
"""
Updates a message in Microsoft Teams channel
:param service_url: Bot service URL to query
:param conversation_id: Conversation ID of message to update
:param activity_id: Activity ID of message to update
:param text: Text to update in the message
:return: None
"""
body = [{
'type': 'TextBlock',
'text': text
}]
adaptive_card: dict = create_adaptive_card(body=body)
conversation = {
'type': 'message',
'attachments': [adaptive_card]
}
url: str = f'{service_url}/v3/conversations/{conversation_id}/activities/{activity_id}'
http_request('PUT', url, json_=conversation, api='bot')
def close_channel_request(team_aad_id: str, channel_id: str):
"""
Sends an HTTP request to close a Microsoft Teams channel
:param team_aad_id: AAD ID of team to close the channel in
:param channel_id: ID of channel to close
:return: None
"""
url: str = f'{GRAPH_BASE_URL}/v1.0/teams/{team_aad_id}/channels/{channel_id}'
http_request('DELETE', url)
def close_channel():
"""
Deletes a mirrored Microsoft Teams channel
"""
integration_context: dict = get_integration_context()
channel_name: str = demisto.args().get('channel', '')
investigation: dict = demisto.investigation()
investigation_id: str = investigation.get('id', '')
channel_id: str = str()
team_aad_id: str
mirrored_channels: list
if not channel_name:
# Closing channel as part of autoclose in mirroring process
teams: list = json.loads(integration_context.get('teams', '[]'))
for team in teams:
team_aad_id = team.get('team_aad_id', '')
mirrored_channels = team.get('mirrored_channels', [])
for channel_index, channel in enumerate(mirrored_channels):
if channel.get('investigation_id') == investigation_id:
channel_id = channel.get('channel_id', '')
close_channel_request(team_aad_id, channel_id)
mirrored_channels.pop(channel_index)
team['mirrored_channels'] = mirrored_channels
break
if not channel_id:
raise ValueError('Could not find Microsoft Teams channel to close.')
integration_context['teams'] = json.dumps(teams)
set_integration_context(integration_context)
else:
team_name: str = demisto.args().get('team') or demisto.params().get('team')
team_aad_id = get_team_aad_id(team_name)
channel_id = get_channel_id(channel_name, team_aad_id, investigation_id)
close_channel_request(team_aad_id, channel_id)
demisto.results('Channel was successfully closed.')
def create_personal_conversation(integration_context: dict, team_member_id: str) -> str:
"""
Create a personal conversation with a team member
:param integration_context: Cached object to retrieve relevant data for the conversation creation
:param team_member_id: ID of team member to create a conversation with
:return: ID of created conversation
"""
bot_id: str = demisto.params().get('bot_id', '')
bot_name: str = integration_context.get('bot_name', '')
tenant_id: str = integration_context.get('tenant_id', '')
conversation: dict = {
'bot': {
'id': f'28:{bot_id}',
'name': bot_name
},
'members': [{
'id': team_member_id
}],
'channelData': {
'tenant': {
'id': tenant_id
}
}
}
service_url: str = integration_context.get('service_url', '')
if not service_url:
raise ValueError('Did not find service URL. Try messaging the bot on Microsoft Teams')
url: str = f'{service_url}/v3/conversations'
response: dict = cast(Dict[Any, Any], http_request('POST', url, json_=conversation, api='bot'))
return response.get('id', '')
def send_message_request(service_url: str, channel_id: str, conversation: dict):
"""
Sends an HTTP request to send message to Microsoft Teams
:param channel_id: ID of channel to send message in
:param conversation: Conversation message object to send
:param service_url: Bot service URL to query
:return: None
"""
url: str = f'{service_url}/v3/conversations/{channel_id}/activities'
http_request('POST', url, json_=conversation, api='bot')
def process_mentioned_users_in_message(message: str) -> Tuple[list, str]:
"""
Processes the message to include all mentioned users in the right format. For example:
Input: 'good morning @Demisto'
Output (Formatted message): 'good morning <at>@Demisto</at>'
:param message: The message to be processed
:return: A list of the mentioned users, The processed message
"""
mentioned_users: list = [''.join(user) for user in re.findall(MENTION_REGEX, message)]
for user in mentioned_users:
message = message.replace(f'@{user};', f'<at>@{user}</at>')
return mentioned_users, message
def mentioned_users_to_entities(mentioned_users: list, integration_context: dict) -> list:
"""
Returns a list of entities built from the mentioned users
:param mentioned_users: A list of mentioned users in the message
:param integration_context: Cached object to retrieve relevant data from
:return: A list of entities
"""
return [{'type': 'mention', 'mentioned': {'id': get_team_member_id(user, integration_context), 'name': user},
'text': f'<at>@{user}</at>'} for user in mentioned_users]
def send_message():
message_type: str = demisto.args().get('messageType', '')
original_message: str = demisto.args().get('originalMessage', '')
message: str = demisto.args().get('message', '')
try:
adaptive_card: dict = json.loads(demisto.args().get('adaptive_card', '{}'))
except ValueError:
raise ValueError('Given adaptive card is not in valid JSON format.')
if message_type == MESSAGE_TYPES['mirror_entry'] and ENTRY_FOOTER in original_message:
# Got a message which was already mirrored - skipping it
return
channel_name: str = demisto.args().get('channel', '')
if (not channel_name and message_type in {MESSAGE_TYPES['status_changed'], MESSAGE_TYPES['incident_opened']}) \
or channel_name == INCIDENT_NOTIFICATIONS_CHANNEL:
# Got a notification from server
channel_name = demisto.params().get('incident_notifications_channel', 'General')
severity: float = float(demisto.args().get('severity'))
# Adding disable and not enable because of adding new boolean parameter always defaults to false value in server
if (disable_auto_notifications := demisto.params().get('auto_notifications')) is not None:
disable_auto_notifications = argToBoolean(disable_auto_notifications)
else:
disable_auto_notifications = False
if not disable_auto_notifications:
severity_threshold: float = translate_severity(demisto.params().get('min_incident_severity', 'Low'))
if severity < severity_threshold:
return
else:
return
team_member: str = demisto.args().get('team_member', '') or demisto.args().get('to', '')
if not (team_member or channel_name):
raise ValueError('No channel or team member to send message were provided.')
if team_member and channel_name:
raise ValueError('Provide either channel or team member to send message to, not both.')
if not (message or adaptive_card):
raise ValueError('No message or adaptive card to send were provided.')
if message and adaptive_card:
raise ValueError('Provide either message or adaptive to send, not both.')
integration_context: dict = get_integration_context()
channel_id: str = str()
personal_conversation_id: str = str()
if channel_name:
team_name: str = demisto.args().get('team', '') or demisto.params().get('team', '')
team_aad_id: str = get_team_aad_id(team_name)
investigation_id: str = str()
if message_type == MESSAGE_TYPES['mirror_entry']:
# Got an entry from the War Room to mirror to Teams
# Getting investigation ID in case channel name is custom and not the default
investigation: dict = demisto.investigation()
investigation_id = investigation.get('id', '')
channel_id = get_channel_id(channel_name, team_aad_id, investigation_id)
elif team_member:
team_member_id: str = get_team_member_id(team_member, integration_context)
personal_conversation_id = create_personal_conversation(integration_context, team_member_id)
recipient: str = channel_id or personal_conversation_id
conversation: dict
if message:
entitlement_match: Optional[Match[str]] = re.search(ENTITLEMENT_REGEX, message)
if entitlement_match:
# In TeamsAsk process
adaptive_card = process_ask_user(message)
conversation = {
'type': 'message',
'attachments': [adaptive_card]
}
else:
# Sending regular message
formatted_message: str = urlify_hyperlinks(message)
mentioned_users, formatted_message_with_mentions = process_mentioned_users_in_message(formatted_message)
entities = mentioned_users_to_entities(mentioned_users, integration_context)
demisto.info(f'msg: {formatted_message_with_mentions}, ent: {entities}')
conversation = {
'type': 'message',
'text': formatted_message_with_mentions,
'entities': entities
}
else: # Adaptive card
conversation = {
'type': 'message',
'attachments': [adaptive_card]
}
service_url: str = integration_context.get('service_url', '')
if not service_url:
raise ValueError('Did not find service URL. Try messaging the bot on Microsoft Teams')
send_message_request(service_url, recipient, conversation)
demisto.results('Message was sent successfully.')
def mirror_investigation():
"""
Updates the integration context with a new or existing mirror.
"""
investigation: dict = demisto.investigation()
if investigation.get('type') == PLAYGROUND_INVESTIGATION_TYPE:
raise ValueError('Can not perform this action in playground.')
integration_context: dict = get_integration_context()
mirror_type: str = demisto.args().get('mirror_type', 'all')
auto_close: str = demisto.args().get('autoclose', 'true')
mirror_direction: str = demisto.args().get('direction', 'both').lower()
team_name: str = demisto.args().get('team', '')
if not team_name:
team_name = demisto.params().get('team', '')
team_aad_id: str = get_team_aad_id(team_name)
mirrored_channels: list = list()
teams: list = json.loads(integration_context.get('teams', '[]'))
team: dict = dict()
for team in teams:
if team.get('team_aad_id', '') == team_aad_id:
if team.get('mirrored_channels'):
mirrored_channels = team['mirrored_channels']
break
if mirror_direction != 'both':
mirror_type = f'{mirror_type}:{mirror_direction}'
investigation_id: str = investigation.get('id', '')
investigation_mirrored_index: int = is_investigation_mirrored(investigation_id, mirrored_channels)
if investigation_mirrored_index > -1:
# Updating channel mirror configuration
mirrored_channels[investigation_mirrored_index]['mirror_type'] = mirror_type
mirrored_channels[investigation_mirrored_index]['mirror_direction'] = mirror_direction
mirrored_channels[investigation_mirrored_index]['auto_close'] = auto_close
mirrored_channels[investigation_mirrored_index]['mirrored'] = False
demisto.results('Investigation mirror was updated successfully.')
else:
channel_name: str = demisto.args().get('channel_name', '') or f'incident-{investigation_id}'
channel_description: str = f'Channel to mirror incident {investigation_id}'
channel_id: str = create_channel(team_aad_id, channel_name, channel_description)
service_url: str = integration_context.get('service_url', '')
server_links: dict = demisto.demistoUrls()
server_link: str = server_links.get('server', '')
warroom_link: str = f'{server_link}#/WarRoom/{investigation_id}'
conversation: dict = {
'type': 'message',
'text': f'This channel was created to mirror [incident {investigation_id}]({warroom_link}) '
f'between Teams and Demisto. In order for your Teams messages to be mirrored in Demisto, '
f'you need to mention the Demisto Bot in the message.'
}
send_message_request(service_url, channel_id, conversation)
mirrored_channels.append({
'channel_id': channel_id,
'investigation_id': investigation_id,
'mirror_type': mirror_type,
'mirror_direction': mirror_direction,
'auto_close': auto_close,
'mirrored': False,
'channel_name': channel_name
})
demisto.results(f'Investigation mirrored successfully in channel {channel_name}.')
team['mirrored_channels'] = mirrored_channels
integration_context['teams'] = json.dumps(teams)
set_integration_context(integration_context)
def channel_mirror_loop():
"""
Runs in a long running container - checking for newly mirrored investigations.
"""
while True:
found_channel_to_mirror: bool = False
integration_context = {}
try:
integration_context = get_integration_context()
teams: list = json.loads(integration_context.get('teams', '[]'))
for team in teams:
mirrored_channels = team.get('mirrored_channels', [])
channel: dict
for channel in mirrored_channels:
investigation_id = channel.get('investigation_id', '')
if not channel['mirrored']:
demisto.info(f'Mirroring incident: {investigation_id} in Microsoft Teams')
channel_to_update: dict = channel
if channel_to_update['mirror_direction'] and channel_to_update['mirror_type']:
demisto.mirrorInvestigation(
channel_to_update['investigation_id'],
channel_to_update['mirror_type'],
bool(strtobool(channel_to_update['auto_close']))
)
channel_to_update['mirrored'] = True
demisto.info(f'Mirrored incident: {investigation_id} to Microsoft Teams successfully')
else:
demisto.info(f'Could not mirror {investigation_id}')
team['mirrored_channels'] = mirrored_channels
integration_context['teams'] = json.dumps(teams)
set_integration_context(integration_context)
found_channel_to_mirror = True
break
if found_channel_to_mirror:
break
except json.decoder.JSONDecodeError as json_decode_error:
demisto.error(
f'An error occurred in channel mirror loop while trying to deserialize teams from cache: '
f'{str(json_decode_error)}'
)
demisto.debug(f'Cache object: {integration_context}')
demisto.updateModuleHealth(f'An error occurred: {str(json_decode_error)}')
except Exception as e:
demisto.error(f'An error occurred in channel mirror loop: {str(e)}')
demisto.updateModuleHealth(f'An error occurred: {str(e)}')
finally:
time.sleep(5)
def member_added_handler(integration_context: dict, request_body: dict, channel_data: dict):
"""
Handles member added activity
:param integration_context: Cached object to retrieve relevant data from
:param request_body: Activity payload
:param channel_data: Microsoft Teams tenant, team and channel details
:return: None
"""
bot_id = demisto.params().get('bot_id')
team: dict = channel_data.get('team', {})
team_id: str = team.get('id', '')
team_aad_id: str = team.get('aadGroupId', '')
team_name: str = team.get('name', '')
tenant: dict = channel_data.get('tenant', {})
tenant_id: str = tenant.get('id', '')
recipient: dict = request_body.get('recipient', {})
recipient_name: str = recipient.get('name', '')
members_added: list = request_body.get('membersAdded', [])
teams: list = json.loads(integration_context.get('teams', '[]'))
service_url: str = integration_context.get('service_url', '')
if not service_url:
raise ValueError('Did not find service URL. Try messaging the bot on Microsoft Teams')
for member in members_added:
member_id = member.get('id', '')
if bot_id in member_id:
# The bot was added to a team, caching team ID and team members
demisto.info(f'The bot was added to team {team_name}')
integration_context['tenant_id'] = tenant_id
integration_context['bot_name'] = recipient_name
break
team_members: list = get_team_members(service_url, team_id)
found_team: bool = False
for team in teams:
if team.get('team_aad_id', '') == team_aad_id:
team['team_members'] = team_members
found_team = True
break
if not found_team:
# Didn't found an existing team, adding new team object
teams.append({
'team_aad_id': team_aad_id,
'team_id': team_id,
'team_name': team_name,
'team_members': team_members
})
integration_context['teams'] = json.dumps(teams)
set_integration_context(integration_context)
def direct_message_handler(integration_context: dict, request_body: dict, conversation: dict, message: str):
"""
Handles a direct message sent to the bot
:param integration_context: Cached object to retrieve relevant data from
:param request_body: Activity payload
:param conversation: Conversation object sent
:param message: The direct message sent
:return: None
"""
conversation_id: str = conversation.get('id', '')
from_property: dict = request_body.get('from', {})
user_id: str = from_property.get('id', '')
team_member: dict = get_team_member(integration_context, user_id)
username: str = team_member.get('username', '')
user_email: str = team_member.get('user_email', '')
formatted_message: str = str()
attachment: dict = dict()
return_card: bool = False
allow_external_incidents_creation: bool = demisto.params().get('allow_external_incidents_creation', False)
lowered_message = message.lower()
if lowered_message.find('incident') != -1 and (lowered_message.find('create') != -1
or lowered_message.find('open') != -1
or lowered_message.find('new') != -1):
if user_email:
demisto_user = demisto.findUser(email=user_email)
else:
demisto_user = demisto.findUser(username=username)
if not demisto_user and not allow_external_incidents_creation:
data = 'You are not allowed to create incidents.'
else:
data = process_incident_create_message(demisto_user, message)
formatted_message = urlify_hyperlinks(data)
else:
try:
data = demisto.directMessage(message, username, user_email, allow_external_incidents_creation)
return_card = True
if data.startswith('`'): # We got a list of incidents/tasks:
data_by_line: list = data.replace('```', '').strip().split('\n')
return_card = True
if data_by_line[0].startswith('Task'):
attachment = process_tasks_list(data_by_line)
else:
attachment = process_incidents_list(data_by_line)
else: # Mirror investigation command / unknown direct message
attachment = process_mirror_or_unknown_message(data)
except Exception as e:
data = str(e)
if return_card:
conversation = {
'type': 'message',
'attachments': [attachment]
}
else:
formatted_message = formatted_message or data
conversation = {
'type': 'message',
'text': formatted_message
}
service_url: str = integration_context.get('service_url', '')
if not service_url:
raise ValueError('Did not find service URL. Try messaging the bot on Microsoft Teams')
send_message_request(service_url, conversation_id, conversation)
def entitlement_handler(integration_context: dict, request_body: dict, value: dict, conversation_id: str):
"""
Handles activity the bot received as part of TeamsAsk flow, which includes entitlement
:param integration_context: Cached object to retrieve relevant data from
:param request_body: Activity payload
:param value: Object which includes
:param conversation_id: Message conversation ID
:return: None
"""
response: str = value.get('response', '')
entitlement_guid: str = value.get('entitlement', '')
investigation_id: str = value.get('investigation_id', '')
task_id: str = value.get('task_id', '')
from_property: dict = request_body.get('from', {})
team_members_id: str = from_property.get('id', '')
team_member: dict = get_team_member(integration_context, team_members_id)
demisto.handleEntitlementForUser(
incidentID=investigation_id,
guid=entitlement_guid,
taskID=task_id,
email=team_member.get('user_email', ''),
content=response
)
activity_id: str = request_body.get('replyToId', '')
service_url: str = integration_context.get('service_url', '')
if not service_url:
raise ValueError('Did not find service URL. Try messaging the bot on Microsoft Teams')
update_message(service_url, conversation_id, activity_id, 'Your response was submitted successfully.')
def message_handler(integration_context: dict, request_body: dict, channel_data: dict, message: str):
"""
Handles a message in which the bot was mentioned
:param integration_context: Cached object to retrieve relevant data from
:param request_body: Activity payload
:param channel_data: Microsoft Teams tenant, team and channel details
:param message: The message which was sent mentioning the bot
:return: None
"""
channel: dict = channel_data.get('channel', {})
channel_id: str = channel.get('id', '')
team_id: str = channel_data.get('team', {}).get('id', '')
from_property: dict = request_body.get('from', {})
team_member_id: str = from_property.get('id', '')
if integration_context.get('teams'):
teams: list = json.loads(integration_context['teams'])
for team in teams:
if team.get('team_id', '') == team_id:
mirrored_channels: list = team.get('mirrored_channels', [])
for mirrored_channel in mirrored_channels:
if mirrored_channel.get('channel_id') == channel_id:
if mirrored_channel.get('mirror_direction', '') != 'FromDemisto' \
and 'none' not in mirrored_channel.get('mirror_type', ''):
investigation_id: str = mirrored_channel.get('investigation_id', '')
username: str = from_property.get('name', '')
user_email: str = get_team_member(integration_context, team_member_id).get('user_email', '')
demisto.addEntry(
id=investigation_id,
entry=message,
username=username,
email=user_email,
footer=f'\n**{ENTRY_FOOTER}**'
)
return
@APP.route('/', methods=['POST'])
def messages() -> Response:
"""
Main handler for messages sent to the bot
"""
try:
demisto.debug('Processing POST query...')
headers: dict = cast(Dict[Any, Any], request.headers)
if validate_auth_header(headers) is False:
demisto.info(f'Authorization header failed: {str(headers)}')
else:
request_body: dict = request.json
integration_context: dict = get_integration_context()
service_url: str = request_body.get('serviceUrl', '')
if service_url:
service_url = service_url[:-1] if service_url.endswith('/') else service_url
integration_context['service_url'] = service_url
set_integration_context(integration_context)
channel_data: dict = request_body.get('channelData', {})
event_type: str = channel_data.get('eventType', '')
conversation: dict = request_body.get('conversation', {})
conversation_type: str = conversation.get('conversationType', '')
conversation_id: str = conversation.get('id', '')
message_text: str = request_body.get('text', '')
# Remove bot mention
bot_name = integration_context.get('bot_name', '')
formatted_message: str = message_text.replace(f'<at>{bot_name}</at>', '')
value: dict = request_body.get('value', {})
if event_type == 'teamMemberAdded':
demisto.info('New Microsoft Teams team member was added')
member_added_handler(integration_context, request_body, channel_data)
elif value:
# In TeamsAsk process
demisto.info('Got response from user in MicrosoftTeamsAsk process')
entitlement_handler(integration_context, request_body, value, conversation_id)
elif conversation_type == 'personal':
demisto.info('Got direct message to the bot')
direct_message_handler(integration_context, request_body, conversation, formatted_message)
else:
demisto.info('Got message mentioning the bot')
message_handler(integration_context, request_body, channel_data, formatted_message)
demisto.info('Finished processing Microsoft Teams activity successfully')
demisto.updateModuleHealth('')
return Response(status=200)
except Exception as e:
err_msg = f'Error occurred when handling incoming message {str(e)}'
demisto.error(err_msg)
return Response(response=err_msg, status=400)
def ring_user_request(call_request_data):
return http_request(method='POST', url=f'{GRAPH_BASE_URL}/v1.0/communications/calls',
json_=call_request_data)
def ring_user():
"""Rings a user on Teams.
Notes:
This is a ring only! no media plays in case the generated call is answered.
Returns:
None.
"""
bot_id = demisto.params().get('bot_id')
integration_context: dict = get_integration_context()
tenant_id: str = integration_context.get('tenant_id', '')
if not tenant_id:
raise ValueError(
'Did not receive tenant ID from Microsoft Teams, verify the messaging endpoint is configured correctly. '
'See https://xsoar.pan.dev/docs/reference/integrations/microsoft-teams#troubleshooting for more information'
)
# get user to call name and id
username_to_call = demisto.args().get('username')
user: list = get_user(username_to_call)
if not (user and user[0].get('id')):
raise ValueError(f'User {username_to_call} was not found')
call_request_data = {
"@odata.type": "#microsoft.graph.call",
"callbackUri": 'https://callback.url',
"direction": "outgoing",
"source": {
"@odata.type": "#microsoft.graph.participantInfo",
"identity": {
"@odata.type": "#microsoft.graph.identitySet",
"application": {
"@odata.type": "#microsoft.graph.identity",
"id": bot_id
}
}
},
"targets": [
{
"@odata.type": "#microsoft.graph.invitationParticipantInfo",
"identity": {
"@odata.type": "#microsoft.graph.identitySet",
"user": {
"@odata.type": "#microsoft.graph.identity",
"displayName": username_to_call,
"id": user[0].get('id')
}
}
}
],
"requestedModalities": [
"audio"
],
"mediaConfig": {
"@odata.type": "#microsoft.graph.serviceHostedMediaConfig",
},
"tenantId": tenant_id
}
response = ring_user_request(call_request_data)
return_outputs(f"Calling {username_to_call}", {}, response)
def long_running_loop():
"""
The infinite loop which runs the mirror loop and the bot app in two different threads
"""
while True:
certificate: str = demisto.params().get('certificate', '')
private_key: str = demisto.params().get('key', '')
certificate_path = str()
private_key_path = str()
server = None
try:
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('No port mapping was provided')
Thread(target=channel_mirror_loop, daemon=True).start()
demisto.info('Started channel mirror loop thread')
ssl_args = dict()
if certificate and private_key:
certificate_file = NamedTemporaryFile(delete=False)
certificate_path = certificate_file.name
certificate_file.write(bytes(certificate, 'utf-8'))
certificate_file.close()
ssl_args['certfile'] = certificate_path
private_key_file = NamedTemporaryFile(delete=False)
private_key_path = private_key_file.name
private_key_file.write(bytes(private_key, 'utf-8'))
private_key_file.close()
ssl_args['keyfile'] = private_key_path
demisto.info('Starting HTTPS Server')
else:
demisto.info('Starting HTTP Server')
server = WSGIServer(('0.0.0.0', port), APP, **ssl_args)
demisto.updateModuleHealth('')
server.serve_forever()
except Exception as e:
error_message = str(e)
demisto.error(f'An error occurred in long running loop: {error_message} - {format_exc()}')
demisto.updateModuleHealth(f'An error occurred: {error_message}')
finally:
if certificate_path:
os.unlink(certificate_path)
if private_key_path:
os.unlink(private_key_path)
if server:
server.stop()
time.sleep(5)
def test_module():
"""
Tests token retrieval for Bot Framework API
"""
get_bot_access_token()
demisto.results('ok')
def main():
""" COMMANDS MANAGER / SWITCH PANEL """
commands: dict = {
'test-module': test_module,
'long-running-execution': long_running_loop,
'send-notification': send_message,
'mirror-investigation': mirror_investigation,
'close-channel': close_channel,
'microsoft-teams-integration-health': integration_health,
'create-channel': create_channel_command,
'add-user-to-channel': add_user_to_channel_command,
# 'microsoft-teams-create-team': create_team,
# 'microsoft-teams-send-file': send_file,
'microsoft-teams-ring-user': ring_user,
'microsoft-teams-create-channel': create_channel_command,
'microsoft-teams-add-user-to-channel': add_user_to_channel_command,
'microsoft-teams-create-meeting': create_meeting_command,
}
''' EXECUTION '''
try:
support_multithreading()
handle_proxy()
command: str = demisto.command()
LOG(f'Command being called is {command}')
if command in commands.keys():
commands[command]()
# Log exceptions
except Exception as e:
return_error(f'{str(e)} - {format_exc()}')
if __name__ == 'builtins':
main()
|
BOSSMAN.py | import socket, threading
server_private_key = "8d6fsdfh39ur893uruf86we7f58734y uihuhUYGIUDHS*&AD9d8 3yuh78y(*iu(d*&D"
def handle_messages(connection: socket.socket):
'''
Receive messages sent by the server and display them to user
'''
while True:
try:
msg = connection.recv(1024)
# If there is no message, there is a chance that connection has closed
# so the connection will be closed and an error will be displayed.
# If not, it will try to decode message in order to show to user.
if msg:
if server_private_key in msg.decode():
print("This is a server message")
print(msg.decode())
else:
connection.close()
break
except Exception as e:
print(f'Error handling message from server: {e}')
connection.close()
break
def client() -> None:
'''
Main process that start client connection to the server
and handle it's input messages
'''
SERVER_ADDRESS = '127.0.1.1'
SERVER_PORT = 12000
try:
# Instantiate socket and start connection with server
socket_instance = socket.socket()
socket_instance.connect((SERVER_ADDRESS, SERVER_PORT))
# Create a thread in order to handle messages sent by server
threading.Thread(target=handle_messages, args=[socket_instance]).start()
print('Connected to BOTNET!')
# Read user's input until it quit from chat and close connection
count = 0
while True:
if count == 4:
socket_instance = socket.socket()
socket_instance.connect((SERVER_ADDRESS, SERVER_PORT))
count = 0
msg = input("Command >> ")
sent_message = server_private_key + msg
msg = sent_message
if msg == 'quit':
break
# Parse message to utf-8
socket_instance.send(msg.encode())
count += 1
# Close connection with the server
socket_instance.close()
print ("closed connection with server")
quit()
exit()
except Exception as e:
print(f'Error connecting to server socket {e}')
socket_instance.close()
if __name__ == "__main__":
client()
|
observer.py | import threading
# import mutex
import rospy
from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus
class Observer(object):
def __init__(self, name, loop_rate_hz=1):
self._name = name
self._rate = rospy.Rate(loop_rate_hz)
self._seq = 1
self._lock = threading.Lock()
self._thread = threading.Thread(
target=self._run)
self._thread.daemon = True
self._stop_event = threading.Event()
self._pub_diag = rospy.Publisher(
'/diagnostics', DiagnosticArray, queue_size=10)
def __del__(self):
if Observer:
print("{} stopped".format(self._name))
# Every derived class needs to override this
def generate_diagnostics(self):
msg = DiagnosticArray()
return msg
def _run(self):
while not rospy.is_shutdown() and not self._stopped():
diag_msg = DiagnosticArray()
diag_msg.header.stamp = rospy.get_rostime()
status_msgs = self.generate_diagnostics()
diag_msg.status.extend(status_msgs)
self._pub_diag.publish(diag_msg)
self._seq += 1
self._rate.sleep()
def start(self):
print("starting {}...".format(self._name))
self._thread.start()
def stop(self):
self._lock.acquire()
self._stop_event.set()
self._lock.release()
def _stopped(self):
self._lock.acquire()
isSet = self._stop_event.isSet()
self._lock.release()
return isSet
class ServiceObserver(Observer):
def __init__(self, name, service_name=None, service_type=None, loop_rate_hz=1):
super(ServiceObserver, self).__init__(name, loop_rate_hz)
self.name = service_name
self.type = service_type
self.client = None
try:
self.start_service()
except:
print("{} service not started".format(self.name))
super.__del__()
def start_service(self):
try:
rospy.wait_for_service(self.name, timeout=1.0)
self.client = rospy.ServiceProxy(self.name, self.type)
print("Service '" + self.name +
"' added of type" + str(self.type))
except rospy.ServiceException as exc:
print("Service {} is not running: ".format(self.name) + str(exc))
def generate_diagnostics(self):
try:
resp = self.client.call()
except rospy.ServiceException as exc:
print("Service {} did not process request: ".format(
self.name) + str(exc))
status_msg = self.diagnostics_from_response(resp)
return status_msg
# Every derived class needs to override this
def diagnostics_from_response(self, response):
msg = DiagnosticArray()
return msg
class TopicObserver(Observer):
def __init__(self, name, loop_rate_hz, topics):
super(TopicObserver, self).__init__(name, loop_rate_hz)
self._topics = topics
self._id = ""
self._num_topics = len(topics)
# Every derived class needs to override this
def calculate_attr(self, msgs):
# do calculations
return DiagnosticStatus()
def generate_diagnostics(self):
msgs = []
received_all = True
for topic, topic_type in self._topics:
try:
msgs.append(rospy.wait_for_message(topic, topic_type))
except rospy.ROSException as exc:
print("Topic {} is not found: ".format(topic) + str(exc))
received_all = False
break
status_msgs = list()
status_msg = DiagnosticStatus()
if received_all:
status_msg = self.calculate_attr(msgs)
status_msgs.append(status_msg)
return status_msgs
|
example_4_forces_control.py | #!/usr/bin/env python
##########################################################################
# MIT License
#
# Copyright (c) 2013-2017 Sensel, Inc.
#
# 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.
##########################################################################
# Python 3 compatibility
from __future__ import print_function
try:
input = raw_input
except NameError:
pass
import threading
import sys
sys.path.append('../../sensel-lib-wrappers/sensel-lib-python')
import sensel
enter_pressed = False
touching_point = (0.0, 0.0)
import pyautogui
def move_cursor():
old_touching_point = touching_point
while not enter_pressed:
moving = (touching_point[0] - old_touching_point[0],
touching_point[1] - old_touching_point[1])
pyautogui.move(moving[0], moving[1])
old_touching_point = touching_point
print("Moving Point:", end=' ')
print(moving)
def wait_for_enter():
global enter_pressed
input('Press Enter to exit...')
enter_pressed = True
return
def open_sensel():
handle = None
error, device_list = sensel.getDeviceList()
if device_list.num_devices != 0:
error, handle = sensel.openDeviceByID(device_list.devices[0].idx)
return handle
def init_frame():
error = sensel.setFrameContent(handle, sensel.FRAME_CONTENT_PRESSURE_MASK)
error, frame = sensel.allocateFrameData(handle)
error = sensel.startScanning(handle)
return frame
def scan_frames(frame, info):
error = sensel.readSensor(handle)
error, num_frames = sensel.getNumAvailableFrames(handle)
for i in range(num_frames):
error = sensel.getFrame(handle, frame)
print_frame(frame, info)
def print_frame(frame, info):
global touching_point
total_force = 0.0
max_force = -1.0
max_point = (0.0, 0.0)
for n in range(info.num_rows * info.num_cols):
total_force += frame.force_array[n]
if (frame.force_array[n] > max_force):
max_point = (n / info.num_cols, n % info.num_cols)
max_force = frame.force_array[n]
# print('Total Force: %s' % total_force)
moving = (max_point[0] - touching_point[0],
max_point[1] - touching_point[1])
pyautogui.move(moving[0], moving[1])
touching_point = max_point
# print("Touching Point:", end=' ')
# print(touching_point)
def close_sensel(frame):
error = sensel.freeFrameData(handle, frame)
error = sensel.stopScanning(handle)
error = sensel.close(handle)
if __name__ == '__main__':
handle = open_sensel()
if handle:
error, info = sensel.getSensorInfo(handle)
frame = init_frame()
t = threading.Thread(target=wait_for_enter)
t.start()
u = threading.Thread(target=move_cursor)
# u.start()
while not enter_pressed:
scan_frames(frame, info)
close_sensel(frame)
|
generate_clsim_table.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=wrong-import-position, invalid-name, no-member, no-name-in-module
# pylint: disable=import-error
"""
Create a Retro table: Propagate light outwards from a DOM and tabulate the
photons. Uses CLSim (tabulator) to do the work of photon propagation.
"""
# TODO: command-line option to simply return the metadata for a config to e.g.
# extract a hash value one would expect from the given params
from __future__ import absolute_import, division, print_function
__all__ = [
'get_average_dom_z_coords',
'generate_clsim_table',
'parse_args',
]
__author__ = 'P. Eller, J.L. Lanfranchi'
__license__ = '''Copyright 2017 Philipp Eller, Justin L. Lanfranchi
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.'''
from argparse import ArgumentParser
from collections import OrderedDict
from os import (
access, environ, getpid, pathsep, remove, X_OK
)
from os.path import (
abspath, dirname, exists, expanduser, expandvars, isfile, join, split
)
import json
from numbers import Integral
import subprocess
import sys
import threading
import time
import numpy as np
from I3Tray import I3Tray
from icecube.clsim import (
AutoSetGeant4Environment,
GetDefaultParameterizationList,
GetFlasherParameterizationList,
#GetIceCubeDOMAcceptance,
I3CLSimFunctionConstant,
I3CLSimFlasherPulse,
I3CLSimFlasherPulseSeries,
I3CLSimLightSourceToStepConverterGeant4,
I3CLSimLightSourceToStepConverterPPC,
I3CLSimSpectrumTable,
)
from icecube.clsim.tabulator import (
LinearAxis,
PowerAxis,
SphericalAxes,
)
from icecube.clsim.traysegments.common import (
configureOpenCLDevices,
parseIceModel,
)
from icecube import dataclasses
from icecube.dataclasses import (
I3Direction,
I3Particle,
I3Position,
)
from icecube.icetray import I3Frame, I3Module, I3Units, logging, traysegment
from icecube.photospline.photonics import FITSTable
from icecube.phys_services import I3GSLRandomService
if __name__ == '__main__' and __package__ is None:
RETRO_DIR = dirname(dirname(dirname(abspath(__file__))))
if RETRO_DIR not in sys.path:
sys.path.append(RETRO_DIR)
from retro.i3info.extract_gcd import extract_gcd
from retro.utils.misc import expand, hash_obj, mkdir
from retro.tables.clsim_tables import (
CLSIM_TABLE_FNAME_PROTO,
CLSIM_TABLE_METANAME_PROTO,
CLSIM_TABLE_TILE_FNAME_PROTO,
CLSIM_TABLE_TILE_METANAME_PROTO,
)
DOM_RADIUS = 0.16510*I3Units.m # 13" diameter
DOM_SURFACE_AREA = np.pi * DOM_RADIUS**2
BINNING_ORDER = {
'spherical': [
'r',
'costheta',
'phi',
't',
'costhetadir',
'deltaphidir',
],
'cartesian': [
'x',
'y',
'z',
't',
'costhetadir',
'phidir',
]
}
def get_average_dom_z_coords(geo):
"""Find average z coordinates for IceCube (non-DeepCore) and DeepCore
"z-layers" of DOMs.
A "z-layer" of DOMs is defined by all DOMs on all strings of a given string
type with shared DOM (OM) indices.
Parameters
----------
geo : (n_strings, n_doms_per_string, 3) array
(x, y, z) coordinate for string 1 (string index 0) DOM 1 (dom index 0) is found at geo[0, 0]
Returns
-------
ic_avg_z : shape (n_doms_per_string) array
dc_avg_z : shape (n_doms_per_string) array
"""
ic_avg_z = geo[:78, :, 2].mean(axis=0)
dc_avg_z = geo[78:, :, 2].mean(axis=0)
return ic_avg_z, dc_avg_z
def make_retro_pulse(x, y, z, zenith, azimuth):
"""Retro pulses originate from a DOM with an (x, y, z) coordinate and
(potentially) a zenith and azimuth orientation (though for now the latter
are ignored).
"""
pulse = I3CLSimFlasherPulse()
pulse.type = I3CLSimFlasherPulse.FlasherPulseType.retro
pulse.pos = I3Position(x, y, z)
pulse.dir = I3Direction(zenith, azimuth)
pulse.time = 0.0
pulse.numberOfPhotonsNoBias = 10000.
# Following values don't make a difference
pulse.pulseWidth = 1.0 * I3Units.ns
pulse.angularEmissionSigmaPolar = 360.0 * I3Units.deg
pulse.angularEmissionSigmaAzimuthal = 360.0 * I3Units.deg
return pulse
def unpin_threads(delay=60):
"""
When AMD OpenCL fissions the CPU device, it pins each sub-device to a
a physical core. Since we always use sub-device 0, this means that multiple
instances of the tabulator on a single machine will compete for core 0.
Reset thread affinity after *delay* seconds to prevent this from happening.
"""
def which(program):
def is_exe(fpath):
return exists(fpath) and access(fpath, X_OK)
def ext_candidates(fpath):
yield fpath
for ext in environ.get('PATHEXT', '').split(pathsep):
yield fpath + ext
fpath, _ = split(program)
if fpath:
if is_exe(program):
return program
else:
for path in environ['PATH'].split(pathsep):
exe_file = join(path, program)
for candidate in ext_candidates(exe_file):
if is_exe(candidate):
return candidate
def taskset(pid, tt=None):
# get/set the taskset affinity for pid
# uses a binary number string for the core affinity
l = [which('taskset'), '-p']
if tt:
l.append(hex(int(tt, 2))[2:])
l.append(str(pid))
p = subprocess.Popen(l, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = p.communicate()[0].split(':')[-1].strip()
if not tt:
return bin(int(output, 16))[2:]
def resetTasksetThreads(main_pid):
# reset thread taskset affinity
time.sleep(delay)
num_cpus = reduce(
lambda b, a: b + int('processor' in a), open('/proc/cpuinfo').readlines(),
0
)
tt = '1'*num_cpus
#tt = taskset(main_pid)
p = subprocess.Popen(
[which('ps'), '-Lo', 'tid', '--no-headers', '%d'%main_pid],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
for tid in p.communicate()[0].split():
tid = tid.strip()
if tid:
taskset(tid, tt)
# only do this on linux
try:
open('/proc/cpuinfo')
except IOError:
return
# and only if taskset exists
if not which('taskset'):
return
threading.Thread(target=resetTasksetThreads, args=(getpid(),)).start()
@traysegment
def TabulateRetroSources(
tray,
name,
source_gcd_i3_md5,
binning_kw,
axes,
ice_model,
angular_sensitivity,
disable_tilt,
disable_anisotropy,
hash_val,
dom_spec,
dom_x,
dom_y,
dom_z,
dom_zenith,
dom_azimuth,
seed,
n_events,
tablepath,
tile=None,
record_errors=False,
):
dom_x = dom_x * I3Units.m
dom_y = dom_y * I3Units.m
dom_z = dom_z * I3Units.m
dom_zenith = dom_zenith * I3Units.rad
dom_azimuth = dom_azimuth * I3Units.rad
tablepath = expanduser(expandvars(tablepath))
random_service = I3GSLRandomService(seed)
tray.AddModule(
'I3InfiniteSource', name + 'streams',
Stream=I3Frame.DAQ
)
tray.AddModule(
'I3MCEventHeaderGenerator',
name + 'gen_header',
Year=2009,
DAQTime=158100000000000000,
RunNumber=1,
EventID=1,
IncrementEventID=True
)
flasher_pulse_series_name = 'I3FlasherPulseSeriesMap'
def reference_source(x, y, z, zenith, azimuth, scale):
source = I3Particle()
source.pos = I3Position(x, y, z)
source.dir = I3Direction(zenith, azimuth)
source.time = 0.0
# Following are not used (at least not yet)
source.type = I3Particle.ParticleType.EMinus
source.energy = 1.0*scale
source.length = 0.0
source.location_type = I3Particle.LocationType.InIce
return source
class MakeParticle(I3Module):
def __init__(self, ctx):
super(MakeParticle, self).__init__(ctx)
self.AddOutBox('OutBox')
self.AddParameter('source_function', '', lambda: None)
self.AddParameter('n_events', '', 100)
self.reference_source = None
self.n_events = None
self.emitted_events = None
def Configure(self):
self.reference_source = self.GetParameter('source_function')
self.n_events = self.GetParameter('n_events')
self.emitted_events = 0
def DAQ(self, frame):
pulseseries = I3CLSimFlasherPulseSeries()
pulse = make_retro_pulse(
x=dom_x,
y=dom_y,
z=dom_z,
zenith=dom_zenith,
azimuth=dom_azimuth,
)
pulseseries.append(pulse)
frame[flasher_pulse_series_name] = pulseseries
frame['ReferenceParticle'] = self.reference_source(
x=dom_x,
y=dom_y,
z=dom_z,
zenith=dom_zenith,
azimuth=dom_azimuth,
scale=1.0,
)
self.PushFrame(frame)
self.emitted_events += 1
if self.emitted_events >= self.n_events:
self.RequestSuspension()
tray.AddModule(
MakeParticle,
source_function=reference_source,
n_events=n_events,
)
header = OrderedDict(FITSTable.empty_header)
header['retro_dom_table'] = 0
header['gcd_i3_md5_{:s}'.format(source_gcd_i3_md5)] = 0
for n, axname in enumerate(binning_kw.keys()):
header['ax_{:s}'.format(axname)] = n
for key, val in binning_kw[axname].items():
header['{}_{}'.format(axname, key)] = val
if axname == 't':
header['t_is_residual_time'] = 1
header['ice_{:s}'.format(ice_model.replace('.', '_'))] = 0
header['angsens_{:s}'.format(angular_sensitivity.replace('.', '_'))] = 0
header['disable_tilt'] = disable_tilt
header['disable_anisotropy'] = disable_anisotropy
header['hash_{:s}'.format(hash_val)] = 0
if tile is not None:
header['tile'] = tile
for key, value in dom_spec.items():
header[key] = value
header['dom_x'] = dom_x
header['dom_y'] = dom_y
header['dom_z'] = dom_z
header['dom_zenith'] = dom_zenith
header['dom_azimuth'] = dom_azimuth
header['seed'] = seed
header['n_events'] = n_events
if hasattr(dataclasses, 'I3ModuleGeo'):
tray.AddModule(
'I3GeometryDecomposer',
name + '_decomposeGeometry',
If=lambda frame: 'I3OMGeoMap' not in frame
)
# at the moment the Geant4 paths need to be set, even if it isn't used
# TODO: fix this
if I3CLSimLightSourceToStepConverterGeant4.can_use_geant4:
AutoSetGeant4Environment()
ppc_converter = I3CLSimLightSourceToStepConverterPPC(photonsPerStep=200)
# Is this even necessary?
ppc_converter.SetUseCascadeExtension(False)
particle_parameterizations = GetDefaultParameterizationList(
ppc_converter,
muonOnly=False,
)
# need a spectrum table in order to pass spectra to OpenCL
spectrum_table = I3CLSimSpectrumTable()
particle_parameterizations += GetFlasherParameterizationList(spectrum_table)
logging.log_debug(
'number of spectra (1x Cherenkov + Nx flasher): %d'
% len(spectrum_table),
unit='clsim',
)
opencl_devices = configureOpenCLDevices(
UseGPUs=False,
UseCPUs=True,
OverrideApproximateNumberOfWorkItems=None,
DoNotParallelize=True,
UseOnlyDeviceNumber=None,
)
medium_properties = parseIceModel(
expandvars('$I3_SRC/clsim/resources/ice/' + ice_model),
disableTilt=disable_tilt,
disableAnisotropy=disable_anisotropy,
)
tray.AddModule(
'I3CLSimTabulatorModule',
name + '_clsim',
MCTreeName='', # doesn't apply since we use pulse series
FlasherPulseSeriesName=flasher_pulse_series_name,
RandomService=random_service,
Area=DOM_SURFACE_AREA,
WavelengthAcceptance=I3CLSimFunctionConstant(1.0), #GetIceCubeDOMAcceptance(domRadius=DOM_RADIUS),
AngularAcceptance=I3CLSimFunctionConstant(1.0),
MediumProperties=medium_properties,
ParameterizationList=particle_parameterizations,
SpectrumTable=spectrum_table,
OpenCLDeviceList=opencl_devices,
PhotonsPerBunch=200,
EntriesPerPhoton=5000,
Filename=tablepath,
RecordErrors=record_errors,
TableHeader=header,
Axes=axes,
SensorNormalize=False
)
unpin_threads()
# TODO: add to CLSim invocation parmeters for detector geometry, bulk ice model, hole
# ice model (i.e. this means angular sensitivity curve in its current implementation,
# though more advanced hole ice models could mean different things), and whether to use
# time difference from direct time
def generate_clsim_table(
outdir,
gcd,
ice_model,
angular_sensitivity,
disable_tilt,
disable_anisotropy,
string,
dom,
n_events,
seed,
coordinate_system,
binning,
tableset_hash=None,
tile=None,
overwrite=False,
compress=False,
):
"""Generate a CLSim table.
See wiki.icecube.wisc.edu/index.php/Ice for information about ice models.
Parameters
----------
outdir : string
gcd : string
ice_model : str
E.g. "spice_mie", "spice_lea", ...
angular_sensitivity : str
E.g. "h2-50cm", "9" (which is equivalent to "new25" because, like, duh)
disable_tilt : bool
Whether to force no layer tilt in simulation (if tilt is present in
bulk ice model; otherwise, this has no effect)
disable_anisotropy : bool
Whether to force no bulk ice anisotropy (if anisotropy is present in
bulk ice model; otherwise, this has no effect)
string : int in [1, 86]
dom : int in [1, 60]
n_events : int > 0
Note that the number of photons is much larger than the number of
events (related to the "brightness" of the defined source).
seed : int in [0, 2**32)
Seed for CLSim's random number generator
coordinate_system : string in {"spherical", "cartesian"}
If spherical, base coordinate system is .. ::
(r, theta, phi, t, costhetadir, absdeltaphidir)
If Cartesian, base coordinate system is .. ::
(x, y, z, costhetadir, phidir)
but if any of the coordinate axes are specified to have 0 bins, they
will be omitted (but the overall order is maintained).
binning : mapping
If `coordinate_system` is "spherical", keys should be:
"n_r_bins"
"n_t_bins"
"n_costheta_bins"
"n_phi_bins"
"n_costhetadir_bins"
"n_deltaphidir_bins"
"r_max"
"r_power"
"t_max"
"t_power"
"deltaphidir_power"
If `coordinate_system` is "cartesian", keys should be:
"n_x_bins"
"n_y_bins"
"n_z_bins"
"n_costhetadir_bins"
"n_phidir_bins"
"x_min"
"x_max"
"y_min"
"y_max"
"z_min"
"z_max"
tableset_hash : str, optional
Specify if the table is a tile used to generate a larger table
tile : int >= 0, optional
Specify if the table is a tile used to generate a larger table
overwrite : bool, optional
Whether to overwrite an existing table (default: False)
compress : bool, optional
Whether to pass the resulting table through zstandard compression
(default: True)
Raises
------
ValueError
If `compress` is True but `zstd` command-line utility cannot be found
AssertionError, ValueError
If illegal argument values are passed
ValueError
If `overwrite` is False and a table already exists at the target path
Notes
-----
Binnings are as follows:
* Radial binning is regular in the space of r**(1/r_power), with
`n_r_bins` spanning from 0 to `r_max` meters.
* Time binning is regular in the space of t**(1/t_power), with
`n_t_bins` spanning from 0 to `t_max` nanoseconds.
* Position zenith angle is binned regularly in the cosine of the zenith
angle with `n_costhetadir_bins` spanning from -1 to +1.
* Position azimuth angle is binned regularly, with `n_phi_bins`
spanning from -pi to pi radians.
* Photon directionality zenith angle (relative to IcedCube coordinate
system) is binned regularly in cosine-zenith space, with
`n_costhetadir_bins` spanning from `costhetadir_min` to
`costhetadir_max`
* Photon directionality azimuth angle, assumed to be symmetric about
line from DOM to the center of the bin, so is binned as an absolute
value, i.e., from 0 to pi radians.
The following are forced upon the above binning specifications (and
remaining parameters are specified as arguments to the function)
* t_min = 0 (ns)
* r_min = 0 (m)
* costheta_min = -1
* costheta_max = 1
* phi_min = -pi (rad)
* phi_max = pi (rad)
* costhetadir_min = -1
* costhetadir_max = 1
* deltaphidir_min = 0 (rad)
* deltaphidir_min = pi (rad)
"""
assert isinstance(n_events, Integral) and n_events > 0
assert isinstance(seed, Integral) and 0 <= seed < 2**32
assert (
(tableset_hash is not None and tile is not None)
or (tableset_hash is None and tile is None)
)
n_bins_per_dim = []
for key, val in binning.items():
if not key.startswith('n_'):
continue
assert isinstance(val, Integral), '{} not an integer'.format(key)
assert val >= 0, '{} must be >= 0'.format(key)
n_bins_per_dim.append(val)
# Note: + 2 accounts for under & overflow bins in each dimension
n_bins = np.product([n + 2 for n in n_bins_per_dim if n > 0])
assert n_bins > 0
if n_bins > 2**32:
raise ValueError(
'The flattened bin index in CLSim is represented by uint32 which'
' has a max of 4 294 967 296, but the binning specified comes to'
' {} bins ({} times too many).'
.format(n_bins, n_bins / 2**32)
)
# For now, hole ice model is hard-coded in our CLSim branch to "9"
# (i.e., as.9, aka new25)
assert angular_sensitivity == '9'
ice_model = ice_model.strip()
angular_sensitivity = angular_sensitivity.strip()
assert angular_sensitivity in ['9', 'new25']
gcd_info = extract_gcd(gcd)
if compress and not any(access(join(path, 'zstd'), X_OK)
for path in environ['PATH'].split(pathsep)):
raise ValueError('`zstd` command not found in path')
outdir = expand(outdir)
mkdir(outdir)
axes = OrderedDict()
binning_kw = OrderedDict()
if coordinate_system == 'spherical':
binning['t_min'] = 0 # ns
binning['r_min'] = 0 # meters
costheta_min, costheta_max = -1.0, 1.0
phi_min, phi_max = -np.pi, np.pi # rad
binning['costhetadir_min'], binning['costhetadir_max'] = -1.0, 1.0
binning['deltaphidir_min'], binning['deltaphidir_max'] = 0.0, np.pi # rad
if binning['n_r_bins'] > 0:
assert isinstance(binning['r_power'], Integral) and binning['r_power'] > 0
r_binning_kw = OrderedDict([
('min', float(binning['r_min'])),
('max', float(binning['r_max'])),
('n_bins', int(binning['n_r_bins'])),
])
if binning['r_power'] == 1:
axes['r'] = LinearAxis(**r_binning_kw)
else:
r_binning_kw['power'] = int(binning['r_power'])
axes['r'] = PowerAxis(**r_binning_kw)
binning_kw['r'] = r_binning_kw
if binning['n_costheta_bins'] > 0:
costheta_binning_kw = OrderedDict([
('min', float(costheta_min)),
('max', float(costheta_max)),
('n_bins', int(binning['n_costheta_bins'])),
])
axes['costheta'] = LinearAxis(**costheta_binning_kw)
binning_kw['costheta'] = costheta_binning_kw
if binning['n_phi_bins'] > 0:
phi_binning_kw = OrderedDict([
('min', float(phi_min)),
('max', float(phi_max)),
('n_bins', int(binning['n_phi_bins'])),
])
axes['phi'] = LinearAxis(**phi_binning_kw)
binning_kw['phi'] = phi_binning_kw
if binning['n_t_bins'] > 0:
assert isinstance(binning['t_power'], Integral) and binning['t_power'] > 0
t_binning_kw = OrderedDict([
('min', float(binning['t_min'])),
('max', float(binning['t_max'])),
('n_bins', int(binning['n_t_bins'])),
])
if binning['t_power'] == 1:
axes['t'] = LinearAxis(**t_binning_kw)
else:
t_binning_kw['power'] = int(binning['t_power'])
axes['t'] = PowerAxis(**t_binning_kw)
binning_kw['t'] = t_binning_kw
if binning['n_costhetadir_bins'] > 0:
costhetadir_binning_kw = OrderedDict([
('min', float(binning['costhetadir_min'])),
('max', float(binning['costhetadir_max'])),
('n_bins', int(binning['n_costhetadir_bins'])),
])
axes['costhetadir'] = LinearAxis(**costhetadir_binning_kw)
binning_kw['costhetadir'] = costhetadir_binning_kw
if binning['n_deltaphidir_bins'] > 0:
assert (
isinstance(binning['deltaphidir_power'], Integral)
and binning['deltaphidir_power'] > 0
)
deltaphidir_binning_kw = OrderedDict([
('min', float(binning['deltaphidir_min'])),
('max', float(binning['deltaphidir_max'])),
('n_bins', int(binning['n_deltaphidir_bins'])),
])
if binning['deltaphidir_power'] == 1:
axes['deltaphidir'] = LinearAxis(**deltaphidir_binning_kw)
else:
deltaphidir_binning_kw['power'] = int(binning['deltaphidir_power'])
axes['deltaphidir'] = PowerAxis(**deltaphidir_binning_kw)
binning_kw['deltaphidir'] = deltaphidir_binning_kw
elif coordinate_system == 'cartesian':
binning['t_min'] = 0 # ns
binning['costhetadir_min'], binning['costhetadir_max'] = -1.0, 1.0
binning['phidir_min'], binning['phidir_max'] = -np.pi, np.pi # rad
if binning['n_x_bins'] > 0:
x_binning_kw = OrderedDict([
('min', float(binning['x_min'])),
('max', float(binning['x_max'])),
('n_bins', int(binning['n_x_bins'])),
])
axes['x'] = LinearAxis(**x_binning_kw)
binning_kw['x'] = x_binning_kw
if binning['n_y_bins'] > 0:
y_binning_kw = OrderedDict([
('min', float(binning['y_min'])),
('max', float(binning['y_max'])),
('n_bins', int(binning['n_y_bins'])),
])
axes['y'] = LinearAxis(**y_binning_kw)
binning_kw['y'] = y_binning_kw
if binning['n_z_bins'] > 0:
z_binning_kw = OrderedDict([
('min', float(binning['z_min'])),
('max', float(binning['z_max'])),
('n_bins', int(binning['n_z_bins'])),
])
axes['z'] = LinearAxis(**z_binning_kw)
binning_kw['z'] = z_binning_kw
if binning['n_t_bins'] > 0:
assert isinstance(binning['t_power'], Integral) and binning['t_power'] > 0
t_binning_kw = OrderedDict([
('min', float(binning['t_min'])),
('max', float(binning['t_max'])),
('n_bins', int(binning['n_t_bins'])),
])
if binning['t_power'] == 1:
axes['t'] = LinearAxis(**t_binning_kw)
else:
t_binning_kw['power'] = int(binning['t_power'])
axes['t'] = PowerAxis(**t_binning_kw)
binning_kw['t'] = t_binning_kw
if binning['n_costhetadir_bins'] > 0:
costhetadir_binning_kw = OrderedDict([
('min', float(binning['costhetadir_min'])),
('max', float(binning['costhetadir_max'])),
('n_bins', int(binning['n_costhetadir_bins'])),
])
axes['costhetadir'] = LinearAxis(**costhetadir_binning_kw)
binning_kw['costhetadir'] = costhetadir_binning_kw
if binning['n_phidir_bins'] > 0:
phidir_binning_kw = OrderedDict([
('min', float(binning['phidir_min'])),
('max', float(binning['phidir_max'])),
('n_bins', int(binning['n_phidir_bins'])),
])
axes['phidir'] = LinearAxis(**phidir_binning_kw)
binning_kw['phidir'] = phidir_binning_kw
binning_order = BINNING_ORDER[coordinate_system]
missing_dims = set(axes.keys()).difference(binning_order)
if missing_dims:
raise ValueError(
'`binning_order` specified is {} but is missing dimension(s) {}'
.format(binning_order, missing_dims)
)
axes_ = OrderedDict()
binning_kw_ = OrderedDict()
for dim in binning_order:
if dim in axes:
axes_[dim] = axes[dim]
binning_kw_[dim] = binning_kw[dim]
axes = axes_
binning_kw = binning_kw_
# NOTE: use SphericalAxes even if we're actually binning Cartesian since we
# don't care how it handles e.g. volumes, and Cartesian isn't implemented
# in CLSim yet
axes = SphericalAxes(axes.values())
# Construct metadata initially with items that will be hashed
metadata = OrderedDict([
('source_gcd_i3_md5', gcd_info['source_gcd_i3_md5']),
('coordinate_system', coordinate_system),
('binning_kw', binning_kw),
('ice_model', ice_model),
('angular_sensitivity', angular_sensitivity),
('disable_tilt', disable_tilt),
('disable_anisotropy', disable_anisotropy)
])
# TODO: this is hard-coded in our branch of CLSim; make parameter & fix here!
if 't' in binning:
metadata['t_is_residual_time'] = True
if tableset_hash is None:
hash_val = hash_obj(metadata, fmt='hex')[:8]
print('derived hash:', hash_val)
else:
hash_val = tableset_hash
print('tableset_hash:', hash_val)
metadata['hash_val'] = hash_val
if tile is not None:
metadata['tile'] = tile
dom_spec = OrderedDict([('string', string), ('dom', dom)])
if 'depth_idx' in dom_spec and ('subdet' in dom_spec or 'string' in dom_spec):
if 'subdet' in dom_spec:
dom_spec['string'] = dom_spec.pop('subdet')
string = dom_spec['string']
depth_idx = dom_spec['depth_idx']
if isinstance(string, str):
subdet = dom_spec['subdet'].lower()
dom_x, dom_y = 0, 0
ic_avg_z, dc_avg_z = get_average_dom_z_coords(gcd_info['geo'])
if string == 'ic':
dom_z = ic_avg_z[depth_idx]
elif string == 'dc':
dom_z = dc_avg_z[depth_idx]
else:
raise ValueError('Unrecognized subdetector {}'.format(subdet))
else:
dom_x, dom_y, dom_z = gcd_info['geo'][string - 1, depth_idx]
metadata['string'] = string
metadata['depth_idx'] = depth_idx
if tile is not None:
raise ValueError(
'Cannot produce tiled tables using "depth_idx"-style table groupings;'
' use "string"/"dom"-style tables instead.'
)
clsim_table_fname_proto = CLSIM_TABLE_FNAME_PROTO[1]
clsim_table_metaname_proto = CLSIM_TABLE_METANAME_PROTO[0]
print('Subdetector {}, depth index {} (z_avg = {} m)'
.format(subdet, depth_idx, dom_z))
elif 'string' in dom_spec and 'dom' in dom_spec:
string = dom_spec['string']
dom = dom_spec['dom']
dom_x, dom_y, dom_z = gcd_info['geo'][string - 1, dom - 1]
metadata['string'] = string
metadata['dom'] = dom
if tile is None:
clsim_table_fname_proto = CLSIM_TABLE_FNAME_PROTO[2]
clsim_table_metaname_proto = CLSIM_TABLE_METANAME_PROTO[1]
else:
clsim_table_fname_proto = CLSIM_TABLE_TILE_FNAME_PROTO[-1]
clsim_table_metaname_proto = CLSIM_TABLE_TILE_METANAME_PROTO[-1]
print('GCD = "{}"\nString {}, dom {}: (x, y, z) = ({}, {}, {}) m'
.format(gcd, string, dom, dom_x, dom_y, dom_z))
else:
raise ValueError('Cannot understand `dom_spec` {}'.format(dom_spec))
# Until someone figures out DOM tilt and ice column / bubble column / cable
# orientations for sure, we'll just set DOM orientation to zenith=pi,
# azimuth=0.
dom_zenith = np.pi
dom_azimuth = 0.0
# Now add other metadata items that are useful but not used for hashing
metadata['dom_x'] = dom_x
metadata['dom_y'] = dom_y
metadata['dom_z'] = dom_z
metadata['dom_zenith'] = dom_zenith
metadata['dom_azimuth'] = dom_azimuth
metadata['seed'] = seed
metadata['n_events'] = n_events
metapath = join(outdir, clsim_table_metaname_proto.format(**metadata))
tablepath = join(outdir, clsim_table_fname_proto.format(**metadata))
# Save metadata as a JSON file (so it's human-readable by any tool, not
# just Python--in contrast to e.g. pickle files)
json.dump(metadata, file(metapath, 'w'), sort_keys=False, indent=4)
print('='*80)
print('Metadata for the table set was written to\n "{}"'.format(metapath))
print('Table will be written to\n "{}"'.format(tablepath))
print('='*80)
exists_at = []
for fpath in [tablepath, tablepath + '.zst']:
if isfile(fpath):
exists_at.append(fpath)
if exists_at:
names = ', '.join('"{}"'.format(fp) for fp in exists_at)
if overwrite:
print('WARNING! Deleting existing table(s) at ' + names)
for fpath in exists_at:
remove(fpath)
else:
raise ValueError('Table(s) already exist at {}; not'
' overwriting.'.format(names))
print('')
tray = I3Tray()
tray.AddSegment(
TabulateRetroSources,
'TabulateRetroSources',
source_gcd_i3_md5=gcd_info['source_gcd_i3_md5'],
binning_kw=binning_kw,
axes=axes,
ice_model=ice_model,
angular_sensitivity=angular_sensitivity,
disable_tilt=disable_tilt,
disable_anisotropy=disable_anisotropy,
hash_val=hash_val,
dom_spec=dom_spec,
dom_x=dom_x,
dom_y=dom_y,
dom_z=dom_z,
dom_zenith=dom_zenith,
dom_azimuth=dom_azimuth,
seed=seed,
n_events=n_events,
tablepath=tablepath,
tile=tile,
record_errors=False,
)
logging.set_level_for_unit('I3CLSimStepToTableConverter', 'TRACE')
logging.set_level_for_unit('I3CLSimTabulatorModule', 'DEBUG')
logging.set_level_for_unit('I3CLSimLightSourceToStepConverterGeant4', 'TRACE')
logging.set_level_for_unit('I3CLSimLightSourceToStepConverterFlasher', 'TRACE')
tray.Execute()
tray.Finish()
if compress:
print('Compressing table with zstandard via command line')
print(' zstd -1 --rm "{}"'.format(tablepath))
subprocess.check_call(['zstd', '-1', '--rm', tablepath])
print('done.')
def parse_args(description=__doc__):
"""Parese command line args.
Returns
-------
args : Namespace
"""
parser = ArgumentParser(description=description)
parser.add_argument(
'--outdir', required=True,
help='Save table to this directory (default: "./")'
)
parser.add_argument(
'--overwrite', action='store_true',
help='Overwrite if the table already exists'
)
parser.add_argument(
'--compress', action='store_true',
help='Compress the table with zstd when complete'
)
parser.add_argument(
'--gcd', required=True
)
parser.add_argument(
'--ice-model', required=True
)
parser.add_argument(
'--angular-sensitivity', required=True
)
parser.add_argument(
'--disable-tilt', action='store_true',
help='Force no tilt, even if ice model contains tilt'
)
parser.add_argument(
'--disable-anisotropy', action='store_true',
help='Force no anisotropy, even if ice model contains anisotropy'
)
parser.add_argument(
'--string', type=int, required=True,
help='String number in [1, 86]'
)
parser.add_argument(
'--dom', type=int, required=True,
help='''DOM number on string, in [1, 60]'''
)
parser.add_argument(
'--n-events', type=int, required=True,
help='Number of events to simulate'
)
parser.add_argument(
'--seed', type=int, required=True,
help='Random seed to use, in range of 32 bit uint: [0, 2**32-1]'
)
subparsers = parser.add_subparsers(
dest='coordinate_system',
help='''Choose the coordinate system for binning: "spherical" or
"cartesian"'''
)
# -- Spherical (phi optional) + time + directionality binning -- #
sph_parser = subparsers.add_parser(
'spherical',
help='Use spherical binning about the DOM',
)
sph_parser.add_argument(
'--n-r-bins', type=int, required=True,
help='Number of radial bins'
)
sph_parser.add_argument(
'--n-costheta-bins', type=int, required=True,
help='Number of costheta (cosine of position zenith angle) bins'
)
sph_parser.add_argument(
'--n-phi-bins', type=int, required=True,
help='Number of phi (position azimuth) bins'
)
sph_parser.add_argument(
'--n-t-bins', type=int, required=True,
help='Number of time bins (relative to direct time)'
)
sph_parser.add_argument(
'--n-costhetadir-bins', type=int, required=True,
help='Number of costhetadir bins'
)
sph_parser.add_argument(
'--n-deltaphidir-bins', type=int, required=True,
help='''Number of deltaphidir bins (Note: span from 0 to pi; code
assumes symmetry about 0)'''
)
sph_parser.add_argument(
'--r-max', type=float, required=False,
help='Radial binning maximum value, in meters'
)
sph_parser.add_argument(
'--r-power', type=int, required=False,
help='Radial binning is regular in raidus to this power'
)
sph_parser.add_argument(
'--deltaphidir-power', type=int, required=False,
help='deltaphidir binning is regular in deltaphidir to this power'
)
sph_parser.add_argument(
'--t-max', type=float, required=False,
help='Time binning maximum value, in nanoseconds'
)
sph_parser.add_argument(
'--t-power', type=int, required=False,
help='Time binning is regular in time to this power'
)
# -- Cartesian + (optional time) + directionality binning -- #
cart_parser = subparsers.add_parser(
'cartesian',
help='Use Cartesian binning in IceCube coord system',
)
cart_parser.add_argument(
'--tableset-hash', required=False,
help='''Hash for a larger table(set) of which this is one tile (i.e.,
if --tile is provided)'''
)
cart_parser.add_argument(
'--tile', type=int, required=False,
help='Tile number; provide if this is a tile in a larger table'
)
cart_parser.add_argument(
'--n-x-bins', type=int, required=True,
help='Number of x bins'
)
cart_parser.add_argument(
'--n-y-bins', type=int, required=True,
help='Number of y bins'
)
cart_parser.add_argument(
'--n-z-bins', type=int, required=True,
help='Number of z bins'
)
cart_parser.add_argument(
'--n-t-bins', type=int, required=True,
help='Number of time bins (relative to direct time)'
)
cart_parser.add_argument(
'--n-costhetadir-bins', type=int, required=True,
help='Number of costhetadir bins'
)
cart_parser.add_argument(
'--n-phidir-bins', type=int, required=True,
help='''Number of phidir bins (Note: span from -pi to pi)'''
)
# -- Binning limits -- #
cart_parser.add_argument(
'--x-min', type=float, required=False,
help='x binning minimum value, IceCube coordinate system, in meters'
)
cart_parser.add_argument(
'--x-max', type=float, required=False,
help='x binning maximum value, IceCube coordinate system, in meters'
)
cart_parser.add_argument(
'--y-min', type=float, required=False,
help='y binning minimum value, IceCube coordinate system, in meters'
)
cart_parser.add_argument(
'--y-max', type=float, required=False,
help='y binning maximum value, IceCube coordinate system, in meters'
)
cart_parser.add_argument(
'--z-min', type=float, required=False,
help='z binning minimum value, IceCube coordinate system, in meters'
)
cart_parser.add_argument(
'--z-max', type=float, required=False,
help='z binning maximum value, IceCube coordinate system, in meters'
)
cart_parser.add_argument(
'--t-max', type=float, required=False,
help='Time binning maximum value, in nanoseconds'
)
cart_parser.add_argument(
'--t-power', type=int, required=False,
help='Time binning is regular in time to this power'
)
all_kw = vars(parser.parse_args())
general_kw = OrderedDict()
for key in (
'outdir',
'overwrite',
'compress',
'gcd',
'ice_model',
'angular_sensitivity',
'disable_tilt',
'disable_anisotropy',
'string',
'dom',
'n_events',
'seed',
'coordinate_system',
'tableset_hash',
'tile',
):
if key in all_kw:
general_kw[key] = all_kw.pop(key)
binning = all_kw
return general_kw, binning
if __name__ == '__main__':
_general_kw, _binning = parse_args()
generate_clsim_table(binning=_binning, **_general_kw)
|
Meridian_console_v22_0415.py | # #!/usr/bin/python3
# coding: UTF-8
# もしくは #!/usr/bin/env python など環境に合わせて
#2022.02.05 UDP通信動作は安定。
#2022.02.05 COMMAND WINDOWのPOWERチェックボックスでサーボ電源ON
#2022.02.05 上記サーボ電源ON中にスライドバー操作でサーボ動作(ただしスライドバーが小さいため大まかな動作確認のみに利用可)
#2022.04.05 コードを少し整理整頓
#2022.04.14 各経路でのエラーの検知と表示の機能を搭載
#2022.04.14 ROSのパブリッシュボタンを追加。ROSのサブスクライブは未実装。
#
# 取扱説明書
# ・起動方法
# 当ファイルがあるディレクトリにて、ターミナルより
# python3 Meridian_console_v22_0415.py
# と入力して実行します。必要に応じてライブラリをpip3で追加してください。
# UDP_RESV_IP,UDP_SEND_IPについては予め調べスクリプト上で書き換えておく必要があります。
# UDP_RESV_IPはターミナルにてip a もしくはipconfig,ifconfig等で調べられます。
# UDP_SEND_IPはESP32の起動時にPCシリアルモニタ上に表示されます。
# ・画面について
# Command画面
# POWER: 全サーボのパワーをオンオフします
# Action: サインカーブの首振りモーションを送信します
# ->ROS1: ROS1のjointデータをパブリッシュします(Rvisと連動できます)
# <-ROS1: ROS1のサブスクライブですが未実装です。
# Control Pad Monitor: リモコンの入力状態を標準化して表示します。
# Message画面
# IPと各経路のエラーカウント、エラー率、フレーム数、動作周波数を表示します
# ResetCounter: カウンタの値をリセットするボタンです。
# TsySKIP, PcSKIP: 連番データの取りこぼし数を表示します(今はちょっと多めです。周波数を50Hzまで下げるとゼロになります。)
# Sensor Monitor: MIUのデータを表示します。rol,pit,yawはセンサフュージョン値です。SetYawボタンでヨー軸の中央値をリセットできます。
# Axis Monitor: 各サーボの値です。パワーオン時にはスライダでサーボを動かすことができます。
from ast import Pass
import numpy as np
import socket
from contextlib import closing
import struct
import math
import dearpygui.dearpygui as dpg
import threading
import signal
import time
#import random
import atexit
#import sys
#from re import I
import rospy
from sensor_msgs.msg import JointState
import struct
#定数
TITLE_VERSION="Meridian Console v22.0414" #DPGのウィンドウタイトル兼バージョン表示
UDP_RESV_IP="192.168.1.xx" #このPCのIPアドレス
UDP_RESV_PORT=22222 #受信ポート
UDP_SEND_IP="192.168.1.xx" #送信先のESP32のIPアドレス
UDP_SEND_PORT=22224 #送信ポート
MSG_SIZE = 90 #Meridim配列の長さ(デフォルトは90)
MSG_BUFF = MSG_SIZE * 2 #Meridim配列のバイト長さ
STEP = 0.02 #1フレームあたりに増加させる制御処理用の数値
#マスターコマンド用の定数(Meridim配列0番に格納する値)
CMD_SET_YAW_CENTER = 1002 #IMUのヨー軸センターリセットコマンド
#制御コマンド用フラグ等
flag_update_yaw_center = 0 #IMUのヨー軸センターリセットフラグ(python内部用)
flag_servo_power = 0 #全サーボのパワーオンオフフラグ
flag_send_data = 0 #状態データ送信モードのオンオフフラグ(サーボパワーオフでもデータ送信可能)
flag_send_motion = 0 #計算モーション送信のオンオフフラグ
flag_ros1_pub = 0 #ROS1のjoint_statesのパブリッシュ
flag_ros1_sub = 0 #ROS1のjoint_statesのサブスクライブ
#UDP用のsocket設定
sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind((UDP_RESV_IP,UDP_RESV_PORT))
#エラー集計表示用変数
loop_count = 0 #フレーム数のカウンタ
error_count_esp_to_pc = 0 #PCからESP32へのUDP送信でのエラー数
error_count_pc_to_esp = 0 #ESP32からPCへのUDP送信でのエラー数
error_count_esp_to_tsy = 0 #ESPからTeensyへのSPI通信でのエラー数
error_count_tsy_to_esp = 0 #TeensyからESP32へのSPI通信でのエラー数
error_count_tsy_skip = 0 #Teensyが受信したデータがクロックカウントスキップしていたか
error_count_pc_skip = 0 #PCが受信したデータがクロックカウントスキップしていたか
frame_clock = 0 #送信するframe_clock(0-199)
frame_clock_resv = 0 #今回受信したframe_clock
frame_clock_resv_past = 0#前回受信したframe_clock
start = time.time() # フレームレート計測用のタイマー初期値
#Meridim配列関連
r_meridim_disp=list(range(MSG_SIZE)) #Meridim配列の受信値short表示用
r_meridim_disp_char=list(range(MSG_SIZE*2)) #Meridim配列の受信値char表示用
s_meridim=[0]*MSG_SIZE #Meridim配列の送信値用
s_meridim_motion=[0]*MSG_SIZE #Meridim配列のPC側で作成したサーボ位置命令送信用
#メッセージ表示用
message0 = "This PC's IP adress is "+UDP_RESV_IP
message1 = ""
message2 = ""
message3 = ""
#モーション計算用変数
x = 0 #増分計算用 (STEPずつ)
y = 0 #増分計算用 (1ずつ)
#def udpresv():
# pass
# デ ー タ の 送 受 信 #########################################################################
def main():
global message0
global message1
global message2
global message3
global x
global y
while (True):
message1 = "Waiting for UDP data from "+UDP_SEND_IP+"..."
with closing(sock):
while True:
global loop_count
global r_meridim_disp
global r_meridim_disp_char
global s_meridim_motion
global error_count_pc_to_esp
global error_count_esp_to_tsy
global error_count_tsy_to_esp
global error_count_esp_to_pc
global error_count_tsy_skip
global error_count_pc_skip
global frame_clock
global frame_clock_resv
global frame_clock_resv_past
global flag_servo_power
global flag_ros1_pub
global flag_ros1_sub
loop_count += 1 #このpythonを起動してからのフレーム数をカウントアップ
r_bin_data,addr = sock.recvfrom(1472)#UDPに受信したデータを転記
r_meridim=struct.unpack('90h',r_bin_data)
r_meridim_disp_char=struct.unpack('180b',r_bin_data)
message1 = "UDP data receiving from "+UDP_SEND_IP
checksum = np.array([0], dtype=np.int16)
for i in range(MSG_SIZE-1):
checksum[0] += r_meridim[i]
r_meridim_disp[i]=r_meridim[i]
checksum[0] = ~checksum[0]
temp = np.array([0], dtype=np.int16)
# エラーフラグ各種のカウントアップ
if checksum[0] == r_meridim[MSG_SIZE-1]:
if (r_meridim_disp[88] >> 14 & 1) == 1:#エラーフラグ14ビット目(ESP32のPCからのUDP受信のエラーフラグ)を調べる
error_count_pc_to_esp += 1
if (r_meridim_disp[88] >> 13 & 1) == 1:#エラーフラグ13ビット目(TeensyのESP32からのSPI受信のエラーフラグ)を調べる
error_count_esp_to_tsy += 1
if (r_meridim_disp[88] >> 12 & 1) == 1:#エラーフラグ12ビット目(ESPのTeensyからのSPI受信のエラーフラグ)を調べる
error_count_tsy_to_esp += 1
if (r_meridim_disp[88] >> 9 & 1) == 1:#エラーフラグ12ビット目(ESPのTeensyからのSPI受信のエラーフラグ)を調べる
error_count_tsy_skip += 1
temp[0] = r_meridim[88] & 0b0111111111111111 #エラーフラグ15ビット目(PCのUDP受信エラーフラグ)を下げる
else:
temp[0] = r_meridim[88] | 0b1000000000000000 #エラーフラグ15ビット目(PCのUDP受信エラーフラグ)を上げる
error_count_esp_to_pc += 1
#クロックの受信
frame_clock_resv_past = frame_clock_resv #前回受信したクロックを今回のpastとしてキープ
frame_clock_resv = r_meridim_disp[88] & 0b0000000011111111 #クロックを受信
if(frame_clock_resv == frame_clock_resv_past + 1): #受信したクロックが送信したものから+2であればスキップなし
temp[0] &= 0b1111111011111111 #PCのスキップフラグを下げる
elif((frame_clock_resv == 0 ) and (frame_clock_resv_past == 199)):
temp[0] &= 0b1111111011111111 #PCのスキップフラグを下げる
else:
print("Found data skipping on PC.")
temp[0] |= 0b0000000100000000 #PCのスキップフラグを上げる
error_count_pc_skip += 1 #スキップカウントをプラス
#送信用クロックの準備
frame_clock += 1 #送信用のframe_clockをカウントアップ
if frame_clock >199:
frame_clock=0
temp[0] &= 0b1111111100000000 #下位8ビットをクリア
temp[0] += frame_clock #下位8ビットに受信カウントに+1したものを格納
#time.sleep(1/1000) #少し休む場合
# R O S 1 joint_statesのパブリッシュ =====================================================================================
if (checksum[0] == r_meridim[MSG_SIZE-1]) and flag_ros1_pub:
joint_pub = rospy.Publisher('joint_states', JointState, queue_size=10)
rospy.init_node('joint_state_publisher_meridim')
rate = rospy.Rate(500) # 500hz
js_meridim = JointState()
js_meridim.header.stamp = rospy.Time.now()
js_meridim.name = ['c_chest_yaw', 'l_shoulder_pitch', 'l_shoulder_roll', 'l_elbow_yaw', 'l_elbow_pitch', 'l_hipjoint_yaw', 'l_hipjoint_roll', 'l_hipjoint_pitch', 'l_knee_pitch', 'l_ankle_pitch', 'l_ankle_roll', 'c_head_yaw', 'r_shoulder_pitch', 'r_shoulder_roll', 'r_elbow_yaw', 'r_elbow_pitch', 'r_hipjoint_yaw', 'r_hipjoint_roll', 'r_hipjoint_pitch', 'r_knee_pitch', 'r_ankle_pitch', 'r_ankle_roll']
js_meridim.position = [math.radians(r_meridim[21]/100), math.radians(r_meridim[23]/100), math.radians(r_meridim[25]/100), math.radians(r_meridim[27]/100), math.radians(r_meridim[29]/100), math.radians(r_meridim[31]/100), math.radians(r_meridim[33]/100), math.radians(r_meridim[35]/100), math.radians(r_meridim[37]/100), math.radians(r_meridim[39]/100), math.radians(r_meridim[41]/100), math.radians(r_meridim[51]/100), math.radians(r_meridim[53]/100), -math.radians(r_meridim[55]/100), -math.radians(r_meridim[57]/100), math.radians(r_meridim[59]/100), -math.radians(r_meridim[61]/100), -math.radians(r_meridim[63]/100), math.radians(r_meridim[65]/100), math.radians(r_meridim[67]/100), math.radians(r_meridim[69]/100), -math.radians(r_meridim[71]/100)]
js_meridim.velocity = []
#js_meridim.velocity = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
js_meridim.effort = []
joint_pub.publish(js_meridim)
rate.sleep()
# ====================================================================================================
# R O S 1 joint_statesのサブスクライブ ====================================================================================
if (checksum[0] == r_meridim[MSG_SIZE-1]) and flag_ros1_sub:
#joint_sub = rospy.Subscriber('/joint_states_sub', JointState, queue_size=10)
#rospy.init_node('joint_state_subscriber_meridim', anonymous=True)
#rate = rospy.Rate(500) # 500hz
#js_meridim = JointState()
#js_meridim.header.stamp = rospy.Time.now()
#js_meridim.name = ['c_chest_yaw', 'l_shoulder_pitch', 'l_shoulder_roll', 'l_elbow_yaw', 'l_elbow_pitch', 'l_hipjoint_yaw', 'l_hipjoint_roll', 'l_hipjoint_pitch', 'l_knee_pitch', 'l_ankle_pitch', 'l_ankle_roll', 'c_head_yaw', 'r_shoulder_pitch', 'r_shoulder_roll', 'r_elbow_yaw', 'r_elbow_pitch', 'r_hipjoint_yaw', 'r_hipjoint_roll', 'r_hipjoint_pitch', 'r_knee_pitch', 'r_ankle_pitch', 'r_ankle_roll']
#js_meridim.position = [math.radians(r_meridim[21]/100), math.radians(r_meridim[23]/100), math.radians(r_meridim[25]/100), math.radians(r_meridim[27]/100), math.radians(r_meridim[29]/100), math.radians(r_meridim[31]/100), math.radians(r_meridim[33]/100), math.radians(r_meridim[35]/100), math.radians(r_meridim[37]/100), math.radians(r_meridim[39]/100), math.radians(r_meridim[41]/100), math.radians(r_meridim[51]/100), math.radians(r_meridim[53]/100), -math.radians(r_meridim[55]/100), -math.radians(r_meridim[57]/100), math.radians(r_meridim[59]/100), -math.radians(r_meridim[61]/100), -math.radians(r_meridim[63]/100), math.radians(r_meridim[65]/100), math.radians(r_meridim[67]/100), math.radians(r_meridim[69]/100), -math.radians(r_meridim[71]/100)]
#js_meridim.velocity = []
#js_meridim.velocity = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
#js_meridim.effort = []
#joint_sub.subscribe(js_meridim)
#rate.sleep()
pass
# ====================================================================================================
signal.signal(signal.SIGINT, signal.SIG_DFL)
#if(frame_clock_resv_past != frame_clock_resv):
#PC側サーボ位置発信用に最終サーボ情報をキープ
if flag_servo_power == 2: #サーボオンボタン押下初回のみ最終受け取りサーボ情報をキープ
for i in range(21,81,2):
s_meridim_motion[i] = r_meridim[i]
flag_servo_power = 1
#送信データのベースを受信データのコピーで作成する
s_meridim=[]
s_meridim=list(r_meridim)
#キープしたエラーフラグ/送信クロックを格納
s_meridim[88] = temp[0]
#PC側でサーボ位置を計算制御する場合は以下でデータを作成
if flag_send_motion == 1: #
# xをフレームごとにカウントアップ
x += STEP
y += 1
if y>10000:
y = 0
if x>100:
x = 0
#print(np.sin(x)," " ,x)
s_meridim_motion[51] = int(np.sin(x)*3000) #プラマイ10度の間でサインカーブを出力
#サーボオンオフフラグチェック:サーボオンフラグを格納
if flag_servo_power > 0:
for i in range(20,80,2):
s_meridim[i] = 1
s_meridim[i+1] = s_meridim_motion[i+1]
else:
for i in range(20,80,2):
s_meridim[i] = 0
#マスターコマンドフラグチェック:ヨー軸センターリセットコマンドを格納
global flag_update_yaw_center
if (flag_update_yaw_center > 0):
flag_update_yaw_center -= 1
s_meridim[0] = CMD_SET_YAW_CENTER
if (flag_update_yaw_center==0):
print("Send COMMAND 'Set Yaw Center.':["+str(CMD_SET_YAW_CENTER)+"]")
#格納した送信データについてチェックサムを追加
checksum[0] = 0
checksum_int = 0
for i in range(MSG_SIZE-1):
checksum_int += s_meridim[i]
checksum[0] = ~checksum_int
s_meridim[MSG_SIZE-1]=checksum[0]
time.sleep(2/1000) #少し休む場合
#データをパックしてUDP送信
s_bin_data=struct.pack('90h',*s_meridim)
sock.sendto(s_bin_data,(UDP_SEND_IP,UDP_SEND_PORT))
#print("Frame "+str(int(frame_clock_resv - frame_clock_resv_past)))
now = time.time()-start
message2="ERROR COUNT ESP-PC:"+str("{:}".format(error_count_esp_to_pc))+\
" PC-ESP:"+str("{:}".format(error_count_pc_to_esp))+" ESP-TSY:"+str("{:}".format(error_count_esp_to_tsy))+" TsySKIP:"+\
str("{:}".format(error_count_tsy_skip))+" PcSKIP:"+str("{:}".format(error_count_pc_skip))+\
" Frames:"+str(loop_count)+" "+str(int(loop_count/now))+"Hz"
message3="ERROR RATE ESP-PC:"+str("{:.2%}".format(error_count_esp_to_pc/loop_count))+\
" PC-ESP:"+str("{:.2%}".format(error_count_pc_to_esp/loop_count))+" ESP-TSY:"+str("{:.2%}".format(error_count_esp_to_tsy/loop_count))
# 関 数 各 種 #########################################################################
def cleanup():#ctrl+cで終了したときにも確実にソケットを閉じる試み(いまのところ機能していない)
print("Meridan_console quited.")
atexit.register(cleanup)
def set_servo_power():#チェックボックスに従いサーボパワーオンフラグをオンオフ
global flag_servo_power
if flag_servo_power == 0 :
flag_servo_power = 2
print("Servo Power ON")
else:
flag_servo_power = 0
print("Servo Power OFF")
def set_data():#チェックボックスに従いデータ送信フラグをオンオフ
global flag_send_data
if flag_send_data == 0 :
flag_send_data = 1
print("Start sending Data.")
else:
flag_send_data = 0
print("Quit sending Data.")
def set_action():#チェックボックスに従いアクション送信フラグをオンオフ
global flag_send_motion
if flag_send_motion == 0 :
flag_send_motion = 1
print("Start Motion Data Streaming.")
else:
flag_send_motion = 0
print("Quit Motion Data Streaming.")
def ros1_pub():#チェックボックスに従いROS1パブリッシュフラグをオンオフ
global flag_ros1_pub
if flag_ros1_pub == 0 :
flag_ros1_pub = 1
print("Start publishing ROS1 joint_states.")
else:
flag_ros1_pub = 0
print("Quit publishing ROS1 joint_states.")
def ros1_sub():#チェックボックスに従いROS1サブスクライブフラグをオンオフ
global flag_ros1_sub
if flag_ros1_sub == 0 :
flag_ros1_sub = 1
print("Start subscribing ROS1 joint_states.")
else:
flag_ros1_sub = 0
print("Quit publishing ROS1 joint_states.")
def set_servo_angle(sender, app_data):#
global s_meridim_motion
if sender[3]=="L":
s_meridim_motion[int(sender[4:6])*2+21] = int(app_data*100)
print(f"L meri: {int(sender[4:6])*2+21}")
if sender[3]=="R":
s_meridim_motion[int(sender[4:6])*2+51] = int(app_data*100)
print(f"R meri: {int(sender[4:6])*2+51}")
print(f"sender is: {sender[3]}")
print(f"sender is: {sender[4:6]}")
print(f"app_data is: {int(app_data*100)}")
print(f"motion is: {s_meridim_motion[int(sender[4:6])+21]}")
# dearpygui に よ る コ ン ソ ー ル 画 面 描 写 #########################################################################
def dpgrun():
# dpg用関数 ==================================================
def set_yaw_center():#IMUのヨー軸センターリセットフラグを10上げる(コマンドを10回送信する)
global flag_update_yaw_center
flag_update_yaw_center = 20
def reset_counter():#カウンターのリセット
global loop_count
global error_count_pc_to_esp
global error_count_esp_to_tsy
global error_count_tsy_to_esp
global error_count_esp_to_pc
global error_count_tsy_skip
global error_count_pc_skip
global start
loop_count = 1
error_count_pc_to_esp = 0
error_count_esp_to_tsy = 0
error_count_tsy_to_esp = 0
error_count_esp_to_pc = 0
error_count_tsy_skip = 0
error_count_pc_skip = 0
start = time.time()
# dpg描画 ==================================================
dpg.create_context()
dpg.create_viewport(title=TITLE_VERSION, width=600, height=480)
# (画面左上)サーボ位置モニタリング用のウィンドウ ==================================================
with dpg.window(label="Axis Monitor", width=250, height=350,pos=[5,5]):
with dpg.group(label='LeftSide'):
for i in range(0, 15, 1):
dpg.add_slider_float(default_value=0, tag="ID L"+str(i),label="L"+str(i),max_value=100,min_value=-100,callback=set_servo_angle,pos=[10,35+i*20], width=80)
with dpg.group(label='RightSide'):
for i in range(0, 15, 1):
dpg.add_slider_float(default_value=0, tag="ID R"+str(i),label="R"+str(i),max_value=100,min_value=-100,callback=set_servo_angle,pos=[135,35+i*20], width=80)
# (画面下段)メッセージ表示用ウィンドウ(アドレス・通信エラー等) ==================================================
with dpg.window(label="Messege", width=590, height=115,pos=[5,360]):
dpg.add_button(label="ResetCounter", callback=reset_counter, width =90, pos=[470,30])
dpg.add_text(message0,tag="DispMessage0")
dpg.add_text(message1,tag="DispMessage1")
dpg.add_text(message2,tag="DispMessage2")
dpg.add_text(message3,tag="DispMessage3")
# (画面右側)センサー値モニタリング用ウィンドウ ==================================================
with dpg.window(label="Sensor Monitor", width=335, height=175,pos=[260,5]):
with dpg.group(label='LeftSide'):
dpg.add_slider_float(default_value=0, tag="mpu0", label="ac_x",max_value=327,min_value=-327,pos=[10,35], width=60)
dpg.add_slider_float(default_value=0, tag="mpu1", label="ac_y",max_value=327,min_value=-327,pos=[115,35], width=60)
dpg.add_slider_float(default_value=0, tag="mpu2", label="ac_z",max_value=327,min_value=-327,pos=[220,35], width=60)
dpg.add_slider_float(default_value=0, tag="mpu3", label="gr_x",max_value=327,min_value=-327,pos=[10,55], width=60)
dpg.add_slider_float(default_value=0, tag="mpu4", label="gr_y",max_value=327,min_value=-327,pos=[115,55], width=60)
dpg.add_slider_float(default_value=0, tag="mpu5", label="gr_z",max_value=327,min_value=-327,pos=[220,55], width=60)
dpg.add_slider_float(default_value=0, tag="mpu6", label="mg_x",max_value=327,min_value=-327,pos=[10,75], width=60)
dpg.add_slider_float(default_value=0, tag="mpu7", label="mg_y",max_value=327,min_value=-327,pos=[115,75], width=60)
dpg.add_slider_float(default_value=0, tag="mpu8", label="mg_z",max_value=327,min_value=-327,pos=[220,75], width=60)
dpg.add_slider_float(default_value=0, tag="mpu9", label="temp",max_value=327,min_value=-327,pos=[10,95], width=60)
dpg.add_slider_float(default_value=0, tag="mpu10", label="rol",max_value=327,min_value=-327,pos=[10,120], width=60)
dpg.add_slider_float(default_value=0, tag="mpu11", label="pit",max_value=327,min_value=-327,pos=[115,120], width=60)
dpg.add_slider_float(default_value=0, tag="mpu12", label="yaw",max_value=327,min_value=-327,pos=[220,120], width=60)
dpg.add_button(label="SetYaw", callback=set_yaw_center, width =50, pos=[270,148])
# (画面右側中央段)コマンド送信/リモコン値表示用ウィンドウ ==================================================
with dpg.window(label="Command", width=335, height=170,pos=[260,185]):
dpg.add_checkbox(label="Power", tag="Power", callback=set_servo_power, pos=[8,27])
dpg.add_checkbox(label="Action", tag="Action", callback=set_action, pos=[8,50])
dpg.add_checkbox(label="->ROS1", tag="ROS1pub", callback=ros1_pub, pos=[100,27])
dpg.add_checkbox(label="<-ROS1", tag="ROS1sub", callback=ros1_sub, pos=[100,50])
dpg.add_text("Control Pad Monitor", pos=[10,100])
dpg.add_text("button",tag="pad_button", pos=[170,100])
dpg.add_slider_int(default_value=0, tag="pad_Lx", label="Lx",max_value=127,min_value=-127, pos=[10,120], width=40)
dpg.add_slider_int(default_value=0, tag="pad_Ly", label="Ly",max_value=127,min_value=-127, pos=[90,120], width=40)
dpg.add_slider_int(default_value=0, tag="pad_Rx", label="Rx",max_value=127,min_value=-127, pos=[170,120], width=40)
dpg.add_slider_int(default_value=0, tag="pad_Ry", label="Ry",max_value=127,min_value=-127, pos=[250,120], width=40)
dpg.add_slider_int(default_value=0, tag="pad_L2v", label="L2v",max_value=255,min_value=0, pos=[90,140], width=40)
dpg.add_slider_int(default_value=0, tag="pad_R2v", label="R2v",max_value=255,min_value=0, pos=[170,140], width=40)
# dpg変数値の登録
with dpg.value_registry():
dpg.add_int_value(tag="button_data")
dpg.setup_dearpygui()
dpg.show_viewport()
# dpg 描 画 内 容 の デ ー タ 更 新 ==================================================
while dpg.is_dearpygui_running():
#メッセージ欄の表示更新
dpg.set_value("DispMessage0", message0) #メッセージ欄表示用
dpg.set_value("DispMessage1", message1) #メッセージ欄表示用
dpg.set_value("DispMessage2", message2) #メッセージ欄表示用
dpg.set_value("DispMessage3", message3) #メッセージ欄表示用
#サーボデータとIMUデータの表示更新
for i in range(0, 15, 1):
#global button
idld = r_meridim_disp[21+i*2]
idrd = r_meridim_disp[51+i*2]
idsensor = r_meridim_disp[i+2]/10000
dpg.set_value("ID L"+str(i), idld/100) #サーボIDと数値の表示L側
dpg.set_value("ID R"+str(i), idrd/100) #サーボIDと数値の表示R側
if i < 13: #IMUデータの更新
if i < 11:
dpg.set_value("mpu"+str(i),idsensor)
else:
dpg.set_value("mpu"+str(i),idsensor*100)
#リモコンデータの表示更新
dpg.set_value("pad_button", str(r_meridim_disp[80]))
dpg.set_value("pad_Lx", r_meridim_disp_char[163])
dpg.set_value("pad_Ly", r_meridim_disp_char[162])
dpg.set_value("pad_Rx", r_meridim_disp_char[165])
dpg.set_value("pad_Ry", r_meridim_disp_char[164])
padL2val = (r_meridim_disp_char[167])
if (padL2val<0):
padL2val = 256+padL2val
if (r_meridim_disp[80]&256==0):
padL2val = 0
padR2val = (r_meridim_disp_char[166])
if (padR2val<0):
padR2val = 256+padR2val
if (r_meridim_disp[80]&512==0):
padR2val = 0
dpg.set_value("pad_L2v", padL2val)
dpg.set_value("pad_R2v", padR2val)
dpg.set_value("button_data", r_meridim_disp[80])
#dpg表示更新処理
dpg.render_dearpygui_frame()
dpg.destroy_context()
#スレッド2つで送受信と画面描写を並列処理
if __name__ == '__main__':
thread1 = threading.Thread(target=dpgrun) #dearpyguiによるコンソール画面描写スレッド
thread1.start()
# thread2 = threading.Thread(target=udpresv)
# thread2.start()
#sys.exit(main())
main()
|
test_sigma_dut.py | # Test cases for sigma_dut
# Copyright (c) 2017, Qualcomm Atheros, Inc.
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import logging
logger = logging.getLogger()
import os
import socket
import subprocess
import threading
import time
import hostapd
from utils import HwsimSkip
from hwsim import HWSimRadio
from test_dpp import check_dpp_capab, update_hapd_config
from test_suite_b import check_suite_b_192_capa, suite_b_as_params, suite_b_192_rsa_ap_params
def check_sigma_dut():
if not os.path.exists("./sigma_dut"):
raise HwsimSkip("sigma_dut not available")
def sigma_dut_cmd(cmd, port=9000, timeout=2):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
sock.settimeout(timeout)
addr = ('127.0.0.1', port)
sock.connect(addr)
sock.send(cmd + "\r\n")
try:
res = sock.recv(1000)
running = False
done = False
for line in res.splitlines():
if line.startswith("status,RUNNING"):
running = True
elif line.startswith("status,INVALID"):
done = True
elif line.startswith("status,ERROR"):
done = True
elif line.startswith("status,COMPLETE"):
done = True
if running and not done:
# Read the actual response
res = sock.recv(1000)
except:
res = ''
pass
sock.close()
res = res.rstrip()
logger.debug("sigma_dut: '%s' --> '%s'" % (cmd, res))
return res
def sigma_dut_cmd_check(cmd, port=9000, timeout=2):
res = sigma_dut_cmd(cmd, port=port, timeout=timeout)
if "COMPLETE" not in res:
raise Exception("sigma_dut command failed: " + cmd)
return res
def start_sigma_dut(ifname, debug=False, hostapd_logdir=None, cert_path=None):
check_sigma_dut()
cmd = [ './sigma_dut',
'-M', ifname,
'-S', ifname,
'-F', '../../hostapd/hostapd',
'-G',
'-w', '/var/run/wpa_supplicant/',
'-j', ifname ]
if debug:
cmd += [ '-d' ]
if hostapd_logdir:
cmd += [ '-H', hostapd_logdir ]
if cert_path:
cmd += [ '-C', cert_path ]
sigma = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
for i in range(20):
try:
res = sigma_dut_cmd("HELLO")
break
except:
time.sleep(0.05)
return sigma
def stop_sigma_dut(sigma):
sigma.terminate()
sigma.wait()
out, err = sigma.communicate()
logger.debug("sigma_dut stdout: " + str(out))
logger.debug("sigma_dut stderr: " + str(err))
def sigma_dut_wait_connected(ifname):
for i in range(50):
res = sigma_dut_cmd("sta_is_connected,interface," + ifname)
if "connected,1" in res:
break
time.sleep(0.2)
if i == 49:
raise Exception("Connection did not complete")
def test_sigma_dut_basic(dev, apdev):
"""sigma_dut basic functionality"""
sigma = start_sigma_dut(dev[0].ifname)
res = sigma_dut_cmd("UNKNOWN")
if "status,INVALID,errorCode,Unknown command" not in res:
raise Exception("Unexpected sigma_dut response to unknown command")
tests = [ ("ca_get_version", "status,COMPLETE,version,1.0"),
("device_get_info", "status,COMPLETE,vendor"),
("device_list_interfaces,interfaceType,foo", "status,ERROR"),
("device_list_interfaces,interfaceType,802.11",
"status,COMPLETE,interfaceType,802.11,interfaceID," + dev[0].ifname) ]
for cmd, response in tests:
res = sigma_dut_cmd(cmd)
if response not in res:
raise Exception("Unexpected %s response: %s" % (cmd, res))
stop_sigma_dut(sigma)
def test_sigma_dut_open(dev, apdev):
"""sigma_dut controlled open network association"""
try:
run_sigma_dut_open(dev, apdev)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_open(dev, apdev):
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
hapd = hostapd.add_ap(apdev[0], { "ssid": "open" })
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_encryption,interface,%s,ssid,%s,encpType,none" % (ifname, "open"))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s" % (ifname, "open"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_psk_pmf(dev, apdev):
"""sigma_dut controlled PSK+PMF association"""
try:
run_sigma_dut_psk_pmf(dev, apdev)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_psk_pmf(dev, apdev):
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
ssid = "test-pmf-required"
params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
params["ieee80211w"] = "2"
hapd = hostapd.add_ap(apdev[0], params)
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_psk,interface,%s,ssid,%s,passphrase,%s,encpType,aes-ccmp,keymgmttype,wpa2,PMF,Required" % (ifname, "test-pmf-required", "12345678"))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-pmf-required"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_psk_pmf_bip_cmac_128(dev, apdev):
"""sigma_dut controlled PSK+PMF association with BIP-CMAC-128"""
try:
run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-CMAC-128", "AES-128-CMAC")
finally:
dev[0].set("ignore_old_scan_res", "0")
def test_sigma_dut_psk_pmf_bip_cmac_256(dev, apdev):
"""sigma_dut controlled PSK+PMF association with BIP-CMAC-256"""
try:
run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-CMAC-256", "BIP-CMAC-256")
finally:
dev[0].set("ignore_old_scan_res", "0")
def test_sigma_dut_psk_pmf_bip_gmac_128(dev, apdev):
"""sigma_dut controlled PSK+PMF association with BIP-GMAC-128"""
try:
run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-GMAC-128", "BIP-GMAC-128")
finally:
dev[0].set("ignore_old_scan_res", "0")
def test_sigma_dut_psk_pmf_bip_gmac_256(dev, apdev):
"""sigma_dut controlled PSK+PMF association with BIP-GMAC-256"""
try:
run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-GMAC-256", "BIP-GMAC-256")
finally:
dev[0].set("ignore_old_scan_res", "0")
def test_sigma_dut_psk_pmf_bip_gmac_256_mismatch(dev, apdev):
"""sigma_dut controlled PSK+PMF association with BIP-GMAC-256 mismatch"""
try:
run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-GMAC-256", "AES-128-CMAC",
failure=True)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_psk_pmf_cipher(dev, apdev, sigma_cipher, hostapd_cipher,
failure=False):
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
ssid = "test-pmf-required"
params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
params["ieee80211w"] = "2"
params["group_mgmt_cipher"] = hostapd_cipher
hapd = hostapd.add_ap(apdev[0], params)
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_psk,interface,%s,ssid,%s,passphrase,%s,encpType,aes-ccmp,keymgmttype,wpa2,PMF,Required,GroupMgntCipher,%s" % (ifname, "test-pmf-required", "12345678", sigma_cipher))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-pmf-required"))
if failure:
ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND",
"CTRL-EVENT-CONNECTED"], timeout=10)
if ev is None:
raise Exception("Network selection result not indicated")
if "CTRL-EVENT-CONNECTED" in ev:
raise Exception("Unexpected connection")
res = sigma_dut_cmd("sta_is_connected,interface," + ifname)
if "connected,1" in res:
raise Exception("Connection reported")
else:
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_sae(dev, apdev):
"""sigma_dut controlled SAE association"""
if "SAE" not in dev[0].get_capability("auth_alg"):
raise HwsimSkip("SAE not supported")
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
ssid = "test-sae"
params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
params['wpa_key_mgmt'] = 'SAE'
params["ieee80211w"] = "2"
hapd = hostapd.add_ap(apdev[0], params)
sigma_dut_cmd_check("sta_reset_default,interface,%s" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, "test-sae", "12345678"))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
if dev[0].get_status_field('sae_group') != '19':
raise Exception("Expected default SAE group not used")
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2,ECGroupID,20" % (ifname, "test-sae", "12345678"))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
if dev[0].get_status_field('sae_group') != '20':
raise Exception("Expected SAE group not used")
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_sae_password(dev, apdev):
"""sigma_dut controlled SAE association and long password"""
if "SAE" not in dev[0].get_capability("auth_alg"):
raise HwsimSkip("SAE not supported")
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
try:
ssid = "test-sae"
params = hostapd.wpa2_params(ssid=ssid)
params['sae_password'] = 100*'B'
params['wpa_key_mgmt'] = 'SAE'
params["ieee80211w"] = "2"
hapd = hostapd.add_ap(apdev[0], params)
sigma_dut_cmd_check("sta_reset_default,interface,%s" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, "test-sae", 100*'B'))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_sta_override_rsne(dev, apdev):
"""sigma_dut and RSNE override on STA"""
try:
run_sigma_dut_sta_override_rsne(dev, apdev)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_sta_override_rsne(dev, apdev):
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
ssid = "test-psk"
params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
hapd = hostapd.add_ap(apdev[0], params)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
tests = [ "30120100000fac040100000fac040100000fac02",
"30140100000fac040100000fac040100000fac02ffff" ]
for test in tests:
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,%s,type,PSK,passphrase,%s,EncpType,aes-ccmp,KeyMgmtType,wpa2" % (ifname, "test-psk", "12345678"))
sigma_dut_cmd_check("dev_configure_ie,interface,%s,IE_Name,RSNE,Contents,%s" % (ifname, test))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-psk"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
dev[0].dump_monitor()
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,%s,type,PSK,passphrase,%s,EncpType,aes-ccmp,KeyMgmtType,wpa2" % (ifname, "test-psk", "12345678"))
sigma_dut_cmd_check("dev_configure_ie,interface,%s,IE_Name,RSNE,Contents,300101" % ifname)
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-psk"))
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
if ev is None:
raise Exception("Association rejection not reported")
if "status_code=40" not in ev:
raise Exception("Unexpected status code: " + ev)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_ap_psk(dev, apdev):
"""sigma_dut controlled AP"""
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-psk,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK,PSK,12345678")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].connect("test-psk", psk="12345678", scan_freq="2412")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_pskhex(dev, apdev, params):
"""sigma_dut controlled AP and PSKHEX"""
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_pskhex.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
psk = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-psk,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK,PSKHEX," + psk)
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].connect("test-psk", raw_psk=psk, scan_freq="2412")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_suite_b(dev, apdev, params):
"""sigma_dut controlled STA Suite B"""
check_suite_b_192_capa(dev)
logdir = params['logdir']
with open("auth_serv/ec2-ca.pem", "r") as f:
with open(os.path.join(logdir, "suite_b_ca.pem"), "w") as f2:
f2.write(f.read())
with open("auth_serv/ec2-user.pem", "r") as f:
with open("auth_serv/ec2-user.key", "r") as f2:
with open(os.path.join(logdir, "suite_b.pem"), "w") as f3:
f3.write(f.read())
f3.write(f2.read())
dev[0].flush_scan_cache()
params = suite_b_as_params()
params['ca_cert'] = 'auth_serv/ec2-ca.pem'
params['server_cert'] = 'auth_serv/ec2-server.pem'
params['private_key'] = 'auth_serv/ec2-server.key'
params['openssl_ciphers'] = 'SUITEB192'
hostapd.add_ap(apdev[1], params)
params = { "ssid": "test-suite-b",
"wpa": "2",
"wpa_key_mgmt": "WPA-EAP-SUITE-B-192",
"rsn_pairwise": "GCMP-256",
"group_mgmt_cipher": "BIP-GMAC-256",
"ieee80211w": "2",
"ieee8021x": "1",
'auth_server_addr': "127.0.0.1",
'auth_server_port': "18129",
'auth_server_shared_secret': "radius",
'nas_identifier': "nas.w1.fi" }
hapd = hostapd.add_ap(apdev[0], params)
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname, cert_path=logdir)
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,type,eaptls,interface,%s,ssid,%s,PairwiseCipher,AES-GCMP-256,GroupCipher,AES-GCMP-256,GroupMgntCipher,BIP-GMAC-256,keymgmttype,SuiteB,clientCertificate,suite_b.pem,trustedRootCA,suite_b_ca.pem,CertType,ECC" % (ifname, "test-suite-b"))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-suite-b"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_suite_b_rsa(dev, apdev, params):
"""sigma_dut controlled STA Suite B (RSA)"""
check_suite_b_192_capa(dev)
logdir = params['logdir']
with open("auth_serv/rsa3072-ca.pem", "r") as f:
with open(os.path.join(logdir, "suite_b_ca_rsa.pem"), "w") as f2:
f2.write(f.read())
with open("auth_serv/rsa3072-user.pem", "r") as f:
with open("auth_serv/rsa3072-user.key", "r") as f2:
with open(os.path.join(logdir, "suite_b_rsa.pem"), "w") as f3:
f3.write(f.read())
f3.write(f2.read())
dev[0].flush_scan_cache()
params = suite_b_192_rsa_ap_params()
hapd = hostapd.add_ap(apdev[0], params)
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname, cert_path=logdir)
cmd = "sta_set_security,type,eaptls,interface,%s,ssid,%s,PairwiseCipher,AES-GCMP-256,GroupCipher,AES-GCMP-256,GroupMgntCipher,BIP-GMAC-256,keymgmttype,SuiteB,clientCertificate,suite_b_rsa.pem,trustedRootCA,suite_b_ca_rsa.pem,CertType,RSA" % (ifname, "test-suite-b")
tests = [ "",
",TLSCipher,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
",TLSCipher,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" ]
for extra in tests:
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check(cmd + extra)
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-suite-b"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_ap_suite_b(dev, apdev, params):
"""sigma_dut controlled AP Suite B"""
check_suite_b_192_capa(dev)
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_suite_b.sigma-hostapd")
params = suite_b_as_params()
params['ca_cert'] = 'auth_serv/ec2-ca.pem'
params['server_cert'] = 'auth_serv/ec2-server.pem'
params['private_key'] = 'auth_serv/ec2-server.key'
params['openssl_ciphers'] = 'SUITEB192'
hostapd.add_ap(apdev[1], params)
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-suite-b,MODE,11ng")
sigma_dut_cmd_check("ap_set_radius,NAME,AP,IPADDR,127.0.0.1,PORT,18129,PASSWORD,radius")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,SuiteB")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].connect("test-suite-b", key_mgmt="WPA-EAP-SUITE-B-192",
ieee80211w="2",
openssl_ciphers="SUITEB192",
eap="TLS", identity="tls user",
ca_cert="auth_serv/ec2-ca.pem",
client_cert="auth_serv/ec2-user.pem",
private_key="auth_serv/ec2-user.key",
pairwise="GCMP-256", group="GCMP-256",
scan_freq="2412")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_cipher_gcmp_128(dev, apdev, params):
"""sigma_dut controlled AP with GCMP-128/BIP-GMAC-128 cipher"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-GCMP-128", "BIP-GMAC-128",
"GCMP")
def test_sigma_dut_ap_cipher_gcmp_256(dev, apdev, params):
"""sigma_dut controlled AP with GCMP-256/BIP-GMAC-256 cipher"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-GCMP-256", "BIP-GMAC-256",
"GCMP-256")
def test_sigma_dut_ap_cipher_ccmp_128(dev, apdev, params):
"""sigma_dut controlled AP with CCMP-128/BIP-CMAC-128 cipher"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-CCMP-128", "BIP-CMAC-128",
"CCMP")
def test_sigma_dut_ap_cipher_ccmp_256(dev, apdev, params):
"""sigma_dut controlled AP with CCMP-256/BIP-CMAC-256 cipher"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-CCMP-256", "BIP-CMAC-256",
"CCMP-256")
def test_sigma_dut_ap_cipher_ccmp_gcmp_1(dev, apdev, params):
"""sigma_dut controlled AP with CCMP-128+GCMP-256 ciphers (1)"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-CCMP-128 AES-GCMP-256",
"BIP-GMAC-256", "CCMP")
def test_sigma_dut_ap_cipher_ccmp_gcmp_2(dev, apdev, params):
"""sigma_dut controlled AP with CCMP-128+GCMP-256 ciphers (2)"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-CCMP-128 AES-GCMP-256",
"BIP-GMAC-256", "GCMP-256", "CCMP")
def test_sigma_dut_ap_cipher_gcmp_256_group_ccmp(dev, apdev, params):
"""sigma_dut controlled AP with GCMP-256/CCMP/BIP-GMAC-256 cipher"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-GCMP-256", "BIP-GMAC-256",
"GCMP-256", "CCMP", "AES-CCMP-128")
def run_sigma_dut_ap_cipher(dev, apdev, params, ap_pairwise, ap_group_mgmt,
sta_cipher, sta_cipher_group=None, ap_group=None):
check_suite_b_192_capa(dev)
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_cipher.sigma-hostapd")
params = suite_b_as_params()
params['ca_cert'] = 'auth_serv/ec2-ca.pem'
params['server_cert'] = 'auth_serv/ec2-server.pem'
params['private_key'] = 'auth_serv/ec2-server.key'
params['openssl_ciphers'] = 'SUITEB192'
hostapd.add_ap(apdev[1], params)
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-suite-b,MODE,11ng")
sigma_dut_cmd_check("ap_set_radius,NAME,AP,IPADDR,127.0.0.1,PORT,18129,PASSWORD,radius")
cmd = "ap_set_security,NAME,AP,KEYMGNT,SuiteB,PMF,Required,PairwiseCipher,%s,GroupMgntCipher,%s" % (ap_pairwise, ap_group_mgmt)
if ap_group:
cmd += ",GroupCipher,%s" % ap_group
sigma_dut_cmd_check(cmd)
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
if sta_cipher_group is None:
sta_cipher_group = sta_cipher
dev[0].connect("test-suite-b", key_mgmt="WPA-EAP-SUITE-B-192",
ieee80211w="2",
openssl_ciphers="SUITEB192",
eap="TLS", identity="tls user",
ca_cert="auth_serv/ec2-ca.pem",
client_cert="auth_serv/ec2-user.pem",
private_key="auth_serv/ec2-user.key",
pairwise=sta_cipher, group=sta_cipher_group,
scan_freq="2412")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_override_rsne(dev, apdev):
"""sigma_dut controlled AP overriding RSNE"""
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-psk,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK,PSK,12345678")
sigma_dut_cmd_check("dev_configure_ie,NAME,AP,interface,%s,IE_Name,RSNE,Contents,30180100000fac040200ffffffff000fac040100000fac020c00" % iface)
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].connect("test-psk", psk="12345678", scan_freq="2412")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_sae(dev, apdev, params):
"""sigma_dut controlled AP with SAE"""
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_sae.sigma-hostapd")
if "SAE" not in dev[0].get_capability("auth_alg"):
raise HwsimSkip("SAE not supported")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].request("SET sae_groups ")
dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
ieee80211w="2", scan_freq="2412")
if dev[0].get_status_field('sae_group') != '19':
raise Exception("Expected default SAE group not used")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_sae_password(dev, apdev, params):
"""sigma_dut controlled AP with SAE and long password"""
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_sae_password.sigma-hostapd")
if "SAE" not in dev[0].get_capability("auth_alg"):
raise HwsimSkip("SAE not supported")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK," + 100*'C')
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].request("SET sae_groups ")
dev[0].connect("test-sae", key_mgmt="SAE", sae_password=100*'C',
ieee80211w="2", scan_freq="2412")
if dev[0].get_status_field('sae_group') != '19':
raise Exception("Expected default SAE group not used")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_sae_group(dev, apdev, params):
"""sigma_dut controlled AP with SAE and specific group"""
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_sae_group.sigma-hostapd")
if "SAE" not in dev[0].get_capability("auth_alg"):
raise HwsimSkip("SAE not supported")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678,ECGroupID,20")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].request("SET sae_groups ")
dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
ieee80211w="2", scan_freq="2412")
if dev[0].get_status_field('sae_group') != '20':
raise Exception("Expected SAE group not used")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_psk_sae(dev, apdev, params):
"""sigma_dut controlled AP with PSK+SAE"""
if "SAE" not in dev[0].get_capability("auth_alg"):
raise HwsimSkip("SAE not supported")
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_psk_sae.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK-SAE,PSK,12345678")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[2].request("SET sae_groups ")
dev[2].connect("test-sae", key_mgmt="SAE", psk="12345678",
scan_freq="2412", ieee80211w="0", wait_connect=False)
dev[0].request("SET sae_groups ")
dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
scan_freq="2412", ieee80211w="2")
dev[1].connect("test-sae", psk="12345678", scan_freq="2412")
ev = dev[2].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.1)
dev[2].request("DISCONNECT")
if ev is not None:
raise Exception("Unexpected connection without PMF")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_owe(dev, apdev):
"""sigma_dut controlled OWE station"""
try:
run_sigma_dut_owe(dev, apdev)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_owe(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
try:
params = { "ssid": "owe",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"ieee80211w": "2",
"rsn_pairwise": "CCMP" }
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,owe,Type,OWE" % ifname)
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,owe,channel,1" % ifname)
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
dev[0].dump_monitor()
sigma_dut_cmd("sta_reassoc,interface,%s,Channel,1,bssid,%s" % (ifname, bssid))
dev[0].wait_connected()
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
dev[0].wait_disconnected()
dev[0].dump_monitor()
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,owe,Type,OWE,ECGroupID,20" % ifname)
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,owe,channel,1" % ifname)
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
dev[0].wait_disconnected()
dev[0].dump_monitor()
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,owe,Type,OWE,ECGroupID,0" % ifname)
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,owe,channel,1" % ifname)
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
if ev is None:
raise Exception("Association not rejected")
if "status_code=77" not in ev:
raise Exception("Unexpected rejection reason: " + ev)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_owe(dev, apdev, params):
"""sigma_dut controlled AP with OWE"""
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_owe.sigma-hostapd")
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,owe,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,OWE")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_owe_ecgroupid(dev, apdev):
"""sigma_dut controlled AP with OWE and ECGroupID"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface)
try:
sigma_dut_cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,owe,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,OWE,ECGroupID,20 21,PMF,Required")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
owe_group="20", scan_freq="2412")
dev[0].request("REMOVE_NETWORK all")
dev[0].wait_disconnected()
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
owe_group="21", scan_freq="2412")
dev[0].request("REMOVE_NETWORK all")
dev[0].wait_disconnected()
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
owe_group="19", scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
dev[0].request("DISCONNECT")
if ev is None:
raise Exception("Association not rejected")
if "status_code=77" not in ev:
raise Exception("Unexpected rejection reason: " + ev)
dev[0].dump_monitor()
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_owe_transition_mode(dev, apdev, params):
"""sigma_dut controlled AP with OWE and transition mode"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_owe_transition_mode.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,1,CHANNEL,1,SSID,owe,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,WLAN_TAG,1,KEYMGNT,OWE")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,2,CHANNEL,1,SSID,owe,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,WLAN_TAG,2,KEYMGNT,NONE")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
res1 = sigma_dut_cmd_check("ap_get_mac_address,NAME,AP,WLAN_TAG,1,Interface,24G")
res2 = sigma_dut_cmd_check("ap_get_mac_address,NAME,AP,WLAN_TAG,2,Interface,24G")
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
dev[1].connect("owe", key_mgmt="NONE", scan_freq="2412")
if dev[0].get_status_field('bssid') not in res1:
raise Exception("Unexpected ap_get_mac_address WLAN_TAG,1: " + res1)
if dev[1].get_status_field('bssid') not in res2:
raise Exception("Unexpected ap_get_mac_address WLAN_TAG,2: " + res2)
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_owe_transition_mode_2(dev, apdev, params):
"""sigma_dut controlled AP with OWE and transition mode (2)"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_owe_transition_mode_2.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,1,CHANNEL,1,SSID,owe,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,WLAN_TAG,1,KEYMGNT,NONE")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,2,CHANNEL,1,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,WLAN_TAG,2,KEYMGNT,OWE")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
res1 = sigma_dut_cmd_check("ap_get_mac_address,NAME,AP,WLAN_TAG,1,Interface,24G")
res2 = sigma_dut_cmd_check("ap_get_mac_address,NAME,AP,WLAN_TAG,2,Interface,24G")
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
dev[1].connect("owe", key_mgmt="NONE", scan_freq="2412")
if dev[0].get_status_field('bssid') not in res2:
raise Exception("Unexpected ap_get_mac_address WLAN_TAG,2: " + res1)
if dev[1].get_status_field('bssid') not in res1:
raise Exception("Unexpected ap_get_mac_address WLAN_TAG,1: " + res2)
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def dpp_init_enrollee(dev, id1):
logger.info("Starting DPP initiator/enrollee in a thread")
time.sleep(1)
cmd = "DPP_AUTH_INIT peer=%d role=enrollee" % id1
if "OK" not in dev.request(cmd):
raise Exception("Failed to initiate DPP Authentication")
ev = dev.wait_event(["DPP-CONF-RECEIVED"], timeout=5)
if ev is None:
raise Exception("DPP configuration not completed (Enrollee)")
logger.info("DPP initiator/enrollee done")
def test_sigma_dut_dpp_qr_resp_1(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 1)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 1)
def test_sigma_dut_dpp_qr_resp_2(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 2)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 2)
def test_sigma_dut_dpp_qr_resp_3(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 3)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 3)
def test_sigma_dut_dpp_qr_resp_4(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 4)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 4)
def test_sigma_dut_dpp_qr_resp_5(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 5)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 5)
def test_sigma_dut_dpp_qr_resp_6(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 6)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 6)
def test_sigma_dut_dpp_qr_resp_7(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 7)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 7)
def test_sigma_dut_dpp_qr_resp_chan_list(dev, apdev):
"""sigma_dut DPP/QR responder (channel list override)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 1, chan_list='81/2 81/6 81/1',
listen_chan=2)
def run_sigma_dut_dpp_qr_resp(dev, apdev, conf_idx, chan_list=None,
listen_chan=None):
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
sigma = start_sigma_dut(dev[0].ifname)
try:
cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
if chan_list:
cmd += ",DPPChannelList," + chan_list
res = sigma_dut_cmd(cmd)
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
t = threading.Thread(target=dpp_init_enrollee, args=(dev[1], id1))
t.start()
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPConfIndex,%d,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfEnrolleeRole,STA,DPPSigningKeyECC,P-256,DPPBS,QR,DPPTimeout,6" % conf_idx
if listen_chan:
cmd += ",DPPListenChannel," + str(listen_chan)
res = sigma_dut_cmd(cmd, timeout=10)
t.join()
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_qr_init_enrollee(dev, apdev):
"""sigma_dut DPP/QR initiator as Enrollee"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
params = { "ssid": "DPPNET01",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "DPP",
"rsn_pairwise": "CCMP",
"dpp_connector": ap_connector,
"dpp_csign": csign_pub,
"dpp_netaccesskey": ap_netaccesskey }
try:
hapd = hostapd.add_ap(apdev[0], params)
except:
raise HwsimSkip("DPP not supported")
sigma = start_sigma_dut(dev[0].ifname)
try:
dev[0].set("dpp_config_processing", "2")
cmd = "DPP_CONFIGURATOR_ADD key=" + csign
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
dev[1].set("dpp_configurator_params",
" conf=sta-dpp ssid=%s configurator=%d" % ("DPPNET01".encode("hex"), conf_id));
cmd = "DPP_LISTEN 2437 role=configurator"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
dev[0].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev):
"""sigma_dut DPP/QR (mutual) initiator as Enrollee"""
run_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev)
def test_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev):
"""sigma_dut DPP/QR (mutual) initiator as Enrollee (extra check)"""
run_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev,
extra="DPPAuthDirection,Mutual,")
def run_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev, extra=''):
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
params = { "ssid": "DPPNET01",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "DPP",
"rsn_pairwise": "CCMP",
"dpp_connector": ap_connector,
"dpp_csign": csign_pub,
"dpp_netaccesskey": ap_netaccesskey }
try:
hapd = hostapd.add_ap(apdev[0], params)
except:
raise HwsimSkip("DPP not supported")
sigma = start_sigma_dut(dev[0].ifname)
try:
dev[0].set("dpp_config_processing", "2")
cmd = "DPP_CONFIGURATOR_ADD key=" + csign
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
dev[1].set("dpp_configurator_params",
" conf=sta-dpp ssid=%s configurator=%d" % ("DPPNET01".encode("hex"), conf_id));
cmd = "DPP_LISTEN 2437 role=configurator qr=mutual"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,%sDPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes" % extra, timeout=10)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
dev[0].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def dpp_init_conf_mutual(dev, id1, conf_id, own_id=None):
time.sleep(1)
logger.info("Starting DPP initiator/configurator in a thread")
cmd = "DPP_AUTH_INIT peer=%d conf=sta-dpp ssid=%s configurator=%d" % (id1, "DPPNET01".encode("hex"), conf_id)
if own_id is not None:
cmd += " own=%d" % own_id
if "OK" not in dev.request(cmd):
raise Exception("Failed to initiate DPP Authentication")
ev = dev.wait_event(["DPP-CONF-SENT"], timeout=10)
if ev is None:
raise Exception("DPP configuration not completed (Configurator)")
logger.info("DPP initiator/configurator done")
def test_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev):
"""sigma_dut DPP/QR (mutual) responder as Enrollee"""
run_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev)
def test_sigma_dut_dpp_qr_mutual_resp_enrollee_pending(dev, apdev):
"""sigma_dut DPP/QR (mutual) responder as Enrollee (response pending)"""
run_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev, ',DPPDelayQRResponse,1')
def run_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev, extra=None):
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
params = { "ssid": "DPPNET01",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "DPP",
"rsn_pairwise": "CCMP",
"dpp_connector": ap_connector,
"dpp_csign": csign_pub,
"dpp_netaccesskey": ap_netaccesskey }
try:
hapd = hostapd.add_ap(apdev[0], params)
except:
raise HwsimSkip("DPP not supported")
sigma = start_sigma_dut(dev[0].ifname)
try:
dev[0].set("dpp_config_processing", "2")
cmd = "DPP_CONFIGURATOR_ADD key=" + csign
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
t = threading.Thread(target=dpp_init_conf_mutual,
args=(dev[1], id1, conf_id, id0))
t.start()
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,20,DPPWaitForConnect,Yes"
if extra:
cmd += extra
res = sigma_dut_cmd(cmd, timeout=25)
t.join()
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
dev[0].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def dpp_resp_conf_mutual(dev, conf_id, uri):
logger.info("Starting DPP responder/configurator in a thread")
dev.set("dpp_configurator_params",
" conf=sta-dpp ssid=%s configurator=%d" % ("DPPNET01".encode("hex"), conf_id));
cmd = "DPP_LISTEN 2437 role=configurator qr=mutual"
if "OK" not in dev.request(cmd):
raise Exception("Failed to initiate DPP listen")
if uri:
ev = dev.wait_event(["DPP-SCAN-PEER-QR-CODE"], timeout=10)
if ev is None:
raise Exception("QR Code scan for mutual authentication not requested")
res = dev.request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
ev = dev.wait_event(["DPP-CONF-SENT"], timeout=10)
if ev is None:
raise Exception("DPP configuration not completed (Configurator)")
logger.info("DPP responder/configurator done")
def test_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev):
"""sigma_dut DPP/QR (mutual) initiator as Enrollee"""
run_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev, False)
def test_sigma_dut_dpp_qr_mutual_init_enrollee_pending(dev, apdev):
"""sigma_dut DPP/QR (mutual) initiator as Enrollee (response pending)"""
run_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev, True)
def run_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev, resp_pending):
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
params = { "ssid": "DPPNET01",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "DPP",
"rsn_pairwise": "CCMP",
"dpp_connector": ap_connector,
"dpp_csign": csign_pub,
"dpp_netaccesskey": ap_netaccesskey }
try:
hapd = hostapd.add_ap(apdev[0], params)
except:
raise HwsimSkip("DPP not supported")
sigma = start_sigma_dut(dev[0].ifname)
try:
dev[0].set("dpp_config_processing", "2")
cmd = "DPP_CONFIGURATOR_ADD key=" + csign
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
if not resp_pending:
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
uri = None
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
t = threading.Thread(target=dpp_resp_conf_mutual,
args=(dev[1], conf_id, uri))
t.start()
time.sleep(1)
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,10,DPPWaitForConnect,Yes"
res = sigma_dut_cmd(cmd, timeout=15)
t.join()
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
dev[0].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_qr_init_enrollee_psk(dev, apdev):
"""sigma_dut DPP/QR initiator as Enrollee (PSK)"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
params = hostapd.wpa2_params(ssid="DPPNET01",
passphrase="ThisIsDppPassphrase")
hapd = hostapd.add_ap(apdev[0], params)
sigma = start_sigma_dut(dev[0].ifname)
try:
dev[0].set("dpp_config_processing", "2")
cmd = "DPP_CONFIGURATOR_ADD"
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
dev[1].set("dpp_configurator_params",
" conf=sta-psk ssid=%s pass=%s configurator=%d" % ("DPPNET01".encode("hex"), "ThisIsDppPassphrase".encode("hex"), conf_id));
cmd = "DPP_LISTEN 2437 role=configurator"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkConnectResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
dev[0].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_qr_init_configurator_1(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 1)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1)
def test_sigma_dut_dpp_qr_init_configurator_2(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 2)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 2)
def test_sigma_dut_dpp_qr_init_configurator_3(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 3)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 3)
def test_sigma_dut_dpp_qr_init_configurator_4(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 4)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 4)
def test_sigma_dut_dpp_qr_init_configurator_5(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 5)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 5)
def test_sigma_dut_dpp_qr_init_configurator_6(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 6)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 6)
def test_sigma_dut_dpp_qr_init_configurator_7(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 7)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 7)
def test_sigma_dut_dpp_qr_init_configurator_both(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator or Enrollee (conf index 1)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1, "Both")
def test_sigma_dut_dpp_qr_init_configurator_neg_freq(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (neg_freq)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1, extra='DPPSubsequentChannel,81/11')
def run_sigma_dut_dpp_qr_init_configurator(dev, apdev, conf_idx,
prov_role="Configurator",
extra=None):
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
sigma = start_sigma_dut(dev[0].ifname)
try:
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
cmd = "DPP_LISTEN 2437 role=enrollee"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,%s,DPPConfIndex,%d,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6" % (prov_role, conf_idx)
if extra:
cmd += "," + extra
res = sigma_dut_cmd(cmd)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_incompatible_roles_init(dev, apdev):
"""sigma_dut DPP roles incompatible (Initiator)"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
sigma = start_sigma_dut(dev[0].ifname)
try:
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
cmd = "DPP_LISTEN 2437 role=enrollee"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6"
res = sigma_dut_cmd(cmd)
if "BootstrapResult,OK,AuthResult,ROLES_NOT_COMPATIBLE" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
def dpp_init_enrollee_mutual(dev, id1, own_id):
logger.info("Starting DPP initiator/enrollee in a thread")
time.sleep(1)
cmd = "DPP_AUTH_INIT peer=%d own=%d role=enrollee" % (id1, own_id)
if "OK" not in dev.request(cmd):
raise Exception("Failed to initiate DPP Authentication")
ev = dev.wait_event(["DPP-CONF-RECEIVED",
"DPP-NOT-COMPATIBLE"], timeout=5)
if ev is None:
raise Exception("DPP configuration not completed (Enrollee)")
logger.info("DPP initiator/enrollee done")
def test_sigma_dut_dpp_incompatible_roles_resp(dev, apdev):
"""sigma_dut DPP roles incompatible (Responder)"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
sigma = start_sigma_dut(dev[0].ifname)
try:
cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
res = sigma_dut_cmd(cmd)
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
t = threading.Thread(target=dpp_init_enrollee_mutual, args=(dev[1], id1, id0))
t.start()
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6"
res = sigma_dut_cmd(cmd, timeout=10)
t.join()
if "BootstrapResult,OK,AuthResult,ROLES_NOT_COMPATIBLE" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_pkex_init_configurator(dev, apdev):
"""sigma_dut DPP/PKEX initiator as Configurator"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
sigma = start_sigma_dut(dev[0].ifname)
try:
cmd = "DPP_BOOTSTRAP_GEN type=pkex"
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id1 = int(res)
cmd = "DPP_PKEX_ADD own=%d identifier=test code=secret" % (id1)
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to set PKEX data (responder)")
cmd = "DPP_LISTEN 2437 role=enrollee"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,6")
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
def dpp_init_conf(dev, id1, conf, conf_id, extra):
logger.info("Starting DPP initiator/configurator in a thread")
cmd = "DPP_AUTH_INIT peer=%d conf=%s %s configurator=%d" % (id1, conf, extra, conf_id)
if "OK" not in dev.request(cmd):
raise Exception("Failed to initiate DPP Authentication")
ev = dev.wait_event(["DPP-CONF-SENT"], timeout=5)
if ev is None:
raise Exception("DPP configuration not completed (Configurator)")
logger.info("DPP initiator/configurator done")
def test_sigma_dut_ap_dpp_qr(dev, apdev, params):
"""sigma_dut controlled AP (DPP)"""
run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-dpp", "sta-dpp")
def test_sigma_dut_ap_dpp_qr_legacy(dev, apdev, params):
"""sigma_dut controlled AP (legacy)"""
run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-psk", "sta-psk",
extra="pass=%s" % "qwertyuiop".encode("hex"))
def test_sigma_dut_ap_dpp_qr_legacy_psk(dev, apdev, params):
"""sigma_dut controlled AP (legacy)"""
run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-psk", "sta-psk",
extra="psk=%s" % (32*"12"))
def run_sigma_dut_ap_dpp_qr(dev, apdev, params, ap_conf, sta_conf, extra=""):
check_dpp_capab(dev[0])
logdir = os.path.join(params['logdir'], "sigma_dut_ap_dpp_qr.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default,program,DPP")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
cmd = "DPP_CONFIGURATOR_ADD"
res = dev[0].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
res = dev[0].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
t = threading.Thread(target=dpp_init_conf,
args=(dev[0], id1, ap_conf, conf_id, extra))
t.start()
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6")
t.join()
if "ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/1 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id1 = int(res)
uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
res = dev[0].request("DPP_QR_CODE " + uri1)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id0b = int(res)
dev[1].set("dpp_config_processing", "2")
cmd = "DPP_LISTEN 2412"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
cmd = "DPP_AUTH_INIT peer=%d conf=%s %s configurator=%d" % (id0b, sta_conf, extra, conf_id)
if "OK" not in dev[0].request(cmd):
raise Exception("Failed to initiate DPP Authentication")
dev[1].wait_connected()
sigma_dut_cmd_check("ap_reset_default")
finally:
dev[1].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def test_sigma_dut_ap_dpp_pkex_responder(dev, apdev, params):
"""sigma_dut controlled AP as DPP PKEX responder"""
check_dpp_capab(dev[0])
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_dpp_pkex_responder.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
run_sigma_dut_ap_dpp_pkex_responder(dev, apdev)
finally:
stop_sigma_dut(sigma)
def dpp_init_conf_pkex(dev, conf_id, check_config=True):
logger.info("Starting DPP PKEX initiator/configurator in a thread")
time.sleep(1.5)
cmd = "DPP_BOOTSTRAP_GEN type=pkex"
res = dev.request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id = int(res)
cmd = "DPP_PKEX_ADD own=%d init=1 conf=ap-dpp configurator=%d code=password" % (id, conf_id)
res = dev.request(cmd)
if "FAIL" in res:
raise Exception("Failed to initiate DPP PKEX")
if not check_config:
return
ev = dev.wait_event(["DPP-CONF-SENT"], timeout=5)
if ev is None:
raise Exception("DPP configuration not completed (Configurator)")
logger.info("DPP initiator/configurator done")
def run_sigma_dut_ap_dpp_pkex_responder(dev, apdev):
sigma_dut_cmd_check("ap_reset_default,program,DPP")
cmd = "DPP_CONFIGURATOR_ADD"
res = dev[0].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
t = threading.Thread(target=dpp_init_conf_pkex, args=(dev[0], conf_id))
t.start()
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,PKEX,DPPPKEXCode,password,DPPTimeout,6,DPPWaitForConnect,No", timeout=10)
t.join()
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
sigma_dut_cmd_check("ap_reset_default")
def test_sigma_dut_dpp_pkex_responder_proto(dev, apdev):
"""sigma_dut controlled STA as DPP PKEX responder and error case"""
check_dpp_capab(dev[0])
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_pkex_responder_proto(dev, apdev)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_pkex_responder_proto(dev, apdev):
cmd = "DPP_CONFIGURATOR_ADD"
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
dev[1].set("dpp_test", "44")
t = threading.Thread(target=dpp_init_conf_pkex, args=(dev[1], conf_id,
False))
t.start()
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPProvisioningRole,Enrollee,DPPBS,PKEX,DPPPKEXCode,password,DPPTimeout,6", timeout=10)
t.join()
if "BootstrapResult,Timeout" not in res:
raise Exception("Unexpected result: " + res)
def dpp_proto_init(dev, id1):
time.sleep(1)
logger.info("Starting DPP initiator/configurator in a thread")
cmd = "DPP_CONFIGURATOR_ADD"
res = dev.request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
cmd = "DPP_AUTH_INIT peer=%d conf=sta-dpp configurator=%d" % (id1, conf_id)
if "OK" not in dev.request(cmd):
raise Exception("Failed to initiate DPP Authentication")
def test_sigma_dut_dpp_proto_initiator(dev, apdev):
"""sigma_dut DPP protocol testing - Initiator"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("InvalidValue", "AuthenticationRequest", "WrappedData",
"BootstrapResult,OK,AuthResult,Errorsent",
None),
("InvalidValue", "AuthenticationConfirm", "WrappedData",
"BootstrapResult,OK,AuthResult,Errorsent",
None),
("MissingAttribute", "AuthenticationRequest", "InitCapabilities",
"BootstrapResult,OK,AuthResult,Errorsent",
"Missing or invalid I-capabilities"),
("InvalidValue", "AuthenticationConfirm", "InitAuthTag",
"BootstrapResult,OK,AuthResult,Errorsent",
"Mismatching Initiator Authenticating Tag"),
("MissingAttribute", "ConfigurationResponse", "EnrolleeNonce",
"BootstrapResult,OK,AuthResult,OK,ConfResult,Errorsent",
"Missing or invalid Enrollee Nonce attribute") ]
for step, frame, attr, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_proto_initiator(dev, step, frame, attr, result,
fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_initiator(dev, step, frame, attr, result, fail):
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
cmd = "DPP_LISTEN 2437 role=enrollee"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6,DPPStep,%s,DPPFrameType,%s,DPPIEAttribute,%s" % (step, frame, attr),
timeout=10)
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly: " + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def test_sigma_dut_dpp_proto_responder(dev, apdev):
"""sigma_dut DPP protocol testing - Responder"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("MissingAttribute", "AuthenticationResponse", "DPPStatus",
"BootstrapResult,OK,AuthResult,Errorsent",
"Missing or invalid required DPP Status attribute"),
("MissingAttribute", "ConfigurationRequest", "EnrolleeNonce",
"BootstrapResult,OK,AuthResult,OK,ConfResult,Errorsent",
"Missing or invalid Enrollee Nonce attribute") ]
for step, frame, attr, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_proto_responder(dev, step, frame, attr, result,
fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_responder(dev, step, frame, attr, result, fail):
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
t = threading.Thread(target=dpp_proto_init, args=(dev[1], id1))
t.start()
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6,DPPStep,%s,DPPFrameType,%s,DPPIEAttribute,%s" % (step, frame, attr), timeout=10)
t.join()
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly:" + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def test_sigma_dut_dpp_proto_stop_at_initiator(dev, apdev):
"""sigma_dut DPP protocol testing - Stop at RX on Initiator"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("AuthenticationResponse",
"BootstrapResult,OK,AuthResult,Errorsent",
None),
("ConfigurationRequest",
"BootstrapResult,OK,AuthResult,OK,ConfResult,Errorsent",
None)]
for frame, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_proto_stop_at_initiator(dev, frame, result, fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_stop_at_initiator(dev, frame, result, fail):
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
cmd = "DPP_LISTEN 2437 role=enrollee"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6,DPPStep,Timeout,DPPFrameType,%s" % (frame))
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly: " + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def test_sigma_dut_dpp_proto_stop_at_responder(dev, apdev):
"""sigma_dut DPP protocol testing - Stop at RX on Responder"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("AuthenticationRequest",
"BootstrapResult,OK,AuthResult,Errorsent",
None),
("AuthenticationConfirm",
"BootstrapResult,OK,AuthResult,Errorsent",
None) ]
for frame, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_proto_stop_at_responder(dev, frame, result, fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_stop_at_responder(dev, frame, result, fail):
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
t = threading.Thread(target=dpp_proto_init, args=(dev[1], id1))
t.start()
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6,DPPStep,Timeout,DPPFrameType,%s" % (frame), timeout=10)
t.join()
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly:" + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def dpp_proto_init_pkex(dev):
time.sleep(1)
logger.info("Starting DPP PKEX initiator/configurator in a thread")
cmd = "DPP_CONFIGURATOR_ADD"
res = dev.request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
cmd = "DPP_BOOTSTRAP_GEN type=pkex"
res = dev.request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id = int(res)
cmd = "DPP_PKEX_ADD own=%d init=1 conf=sta-dpp configurator=%d code=secret" % (id, conf_id)
if "FAIL" in dev.request(cmd):
raise Exception("Failed to initiate DPP PKEX")
def test_sigma_dut_dpp_proto_initiator_pkex(dev, apdev):
"""sigma_dut DPP protocol testing - Initiator (PKEX)"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("InvalidValue", "PKEXCRRequest", "WrappedData",
"BootstrapResult,Errorsent",
None),
("MissingAttribute", "PKEXExchangeRequest", "FiniteCyclicGroup",
"BootstrapResult,Errorsent",
"Missing or invalid Finite Cyclic Group attribute"),
("MissingAttribute", "PKEXCRRequest", "BSKey",
"BootstrapResult,Errorsent",
"No valid peer bootstrapping key found") ]
for step, frame, attr, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_proto_initiator_pkex(dev, step, frame, attr,
result, fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_initiator_pkex(dev, step, frame, attr, result, fail):
cmd = "DPP_BOOTSTRAP_GEN type=pkex"
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id1 = int(res)
cmd = "DPP_PKEX_ADD own=%d code=secret" % (id1)
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to set PKEX data (responder)")
cmd = "DPP_LISTEN 2437 role=enrollee"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCode,secret,DPPTimeout,6,DPPStep,%s,DPPFrameType,%s,DPPIEAttribute,%s" % (step, frame, attr))
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly: " + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def test_sigma_dut_dpp_proto_responder_pkex(dev, apdev):
"""sigma_dut DPP protocol testing - Responder (PKEX)"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("InvalidValue", "PKEXCRResponse", "WrappedData",
"BootstrapResult,Errorsent",
None),
("MissingAttribute", "PKEXExchangeResponse", "DPPStatus",
"BootstrapResult,Errorsent",
"No DPP Status attribute"),
("MissingAttribute", "PKEXCRResponse", "BSKey",
"BootstrapResult,Errorsent",
"No valid peer bootstrapping key found") ]
for step, frame, attr, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_proto_responder_pkex(dev, step, frame, attr,
result, fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_responder_pkex(dev, step, frame, attr, result, fail):
t = threading.Thread(target=dpp_proto_init_pkex, args=(dev[1],))
t.start()
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCode,secret,DPPTimeout,6,DPPStep,%s,DPPFrameType,%s,DPPIEAttribute,%s" % (step, frame, attr), timeout=10)
t.join()
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly:" + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def init_sigma_dut_dpp_proto_peer_disc_req(dev, apdev):
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
params = { "ssid": "DPPNET01",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "DPP",
"rsn_pairwise": "CCMP",
"dpp_connector": ap_connector,
"dpp_csign": csign_pub,
"dpp_netaccesskey": ap_netaccesskey }
try:
hapd = hostapd.add_ap(apdev[0], params)
except:
raise HwsimSkip("DPP not supported")
dev[0].set("dpp_config_processing", "2")
cmd = "DPP_CONFIGURATOR_ADD key=" + csign
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
dev[1].set("dpp_configurator_params",
" conf=sta-dpp ssid=%s configurator=%d" % ("DPPNET01".encode("hex"), conf_id));
cmd = "DPP_LISTEN 2437 role=configurator"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
def test_sigma_dut_dpp_proto_peer_disc_req(dev, apdev):
"""sigma_dut DPP protocol testing - Peer Discovery Request"""
sigma = start_sigma_dut(dev[0].ifname)
try:
init_sigma_dut_dpp_proto_peer_disc_req(dev, apdev)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes,DPPStep,MissingAttribute,DPPFrameType,PeerDiscoveryRequest,DPPIEAttribute,TransactionID", timeout=10)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,Errorsent" not in res:
raise Exception("Unexpected result: " + res)
finally:
dev[0].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_self_config(dev, apdev):
"""sigma_dut DPP Configurator enrolling an AP and using self-configuration"""
check_dpp_capab(dev[0])
hapd = hostapd.add_ap(apdev[0], { "ssid": "unconfigured" })
check_dpp_capab(hapd)
sigma = start_sigma_dut(dev[0].ifname)
try:
dev[0].set("dpp_config_processing", "2")
addr = hapd.own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/1 mac=" + addr
res = hapd.request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id = int(res)
uri = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,AP,DPPBS,QR,DPPTimeout,6")
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
update_hapd_config(hapd)
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPCryptoIdentifier,P-256,DPPBS,QR,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPAuthDirection,Single,DPPConfIndex,1,DPPTimeout,6,DPPWaitForConnect,Yes,DPPSelfConfigure,Yes"
res = sigma_dut_cmd(cmd, timeout=10)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
dev[0].set("dpp_config_processing", "0")
def test_sigma_dut_ap_dpp_self_config(dev, apdev, params):
"""sigma_dut DPP AP Configurator using self-configuration"""
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_dpp_self_config.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
run_sigma_dut_ap_dpp_self_config(dev, apdev)
finally:
stop_sigma_dut(sigma)
dev[0].set("dpp_config_processing", "0")
def run_sigma_dut_ap_dpp_self_config(dev, apdev):
check_dpp_capab(dev[0])
sigma_dut_cmd_check("ap_reset_default,program,DPP")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfEnrolleeRole,AP,DPPBS,QR,DPPConfIndex,1,DPPSelfConfigure,Yes,DPPTimeout,6", timeout=10)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
dev[0].set("dpp_config_processing", "2")
addr = dev[0].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/11 mac=" + addr
res = dev[0].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id = int(res)
uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id)
cmd = "DPP_LISTEN 2462 role=enrollee"
if "OK" not in dev[0].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6"
res = sigma_dut_cmd(cmd)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
dev[0].wait_connected()
dev[0].request("DISCONNECT")
dev[0].wait_disconnected()
sigma_dut_cmd_check("ap_reset_default")
def test_sigma_dut_preconfigured_profile(dev, apdev):
"""sigma_dut controlled connection using preconfigured profile"""
try:
run_sigma_dut_preconfigured_profile(dev, apdev)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_preconfigured_profile(dev, apdev):
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
params = hostapd.wpa2_params(ssid="test-psk", passphrase="12345678")
hapd = hostapd.add_ap(apdev[0], params)
dev[0].connect("test-psk", psk="12345678", scan_freq="2412",
only_add_network=True)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s" % (ifname, "test-psk"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_wps_pbc(dev, apdev):
"""sigma_dut and WPS PBC Enrollee"""
try:
run_sigma_dut_wps_pbc(dev, apdev)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_wps_pbc(dev, apdev):
ssid = "test-wps-conf"
hapd = hostapd.add_ap(apdev[0],
{ "ssid": "wps", "eap_server": "1", "wps_state": "2",
"wpa_passphrase": "12345678", "wpa": "2",
"wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
hapd.request("WPS_PBC")
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
cmd = "start_wps_registration,interface,%s" % ifname
cmd += ",WpsRole,Enrollee"
cmd += ",WpsConfigMethod,PBC"
sigma_dut_cmd_check(cmd, timeout=15)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
hapd.disable()
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
dev[0].flush_scan_cache()
def test_sigma_dut_sta_scan_bss(dev, apdev):
"""sigma_dut sta_scan_bss"""
hapd = hostapd.add_ap(apdev[0], { "ssid": "test" })
sigma = start_sigma_dut(dev[0].ifname)
try:
cmd = "sta_scan_bss,Interface,%s,BSSID,%s" % (dev[0].ifname, \
hapd.own_addr())
res = sigma_dut_cmd(cmd, timeout=10)
if "ssid,test,bsschannel,1" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
|
test_connection.py | from __future__ import with_statement
from __future__ import absolute_import
from test.UdsTest import UdsTest
from udsoncan.connections import *
from test.stub import StubbedIsoTPSocket
import socket
import threading
import time
import unittest
try:
_STACK_UNVAILABLE_REASON = u''
_interface_name = u'vcan0'
import isotp
import can
s = isotp.socket()
s.bind(_interface_name,rxid=1,txid=2)
s.close()
_STACK_POSSIBLE = True
except Exception, e:
_STACK_UNVAILABLE_REASON = unicode(e)
_STACK_POSSIBLE = False
class TestIsoTPSocketConnection(UdsTest):
def setUp(self):
self.tpsock1 = StubbedIsoTPSocket(timeout=0.1)
self.tpsock2 = StubbedIsoTPSocket(timeout=0.1)
def test_open(self):
conn = IsoTPSocketConnection(interface=u'vcan0', rxid=0x001, txid=0x002, tpsock=self.tpsock1, name=u'unittest')
self.assertFalse(conn.is_open())
conn.open()
self.assertTrue(conn.is_open())
conn.close()
self.assertFalse(conn.is_open())
def test_transmit(self):
conn1 = IsoTPSocketConnection(interface=u'vcan0', rxid=0x100, txid=0x101, tpsock=self.tpsock1, name=u'unittest')
conn2 = IsoTPSocketConnection(interface=u'vcan0', rxid=0x101, txid=0x100, tpsock=self.tpsock2, name=u'unittest')
with conn1.open():
with conn2.open():
payload1 = "\x00\x01\x02\x03\x04"
conn1.send(payload1)
payload2 = conn2.wait_frame(timeout=0.3)
self.assertEqual(payload1, payload2)
class TestSocketConnection(UdsTest):
def server_sock_thread_task(self):
self.thread_started=True
self.sock1, addr = self.server_sock.accept()
def setUp(self):
self.thread_started = False
self.server_sock_thread = threading.Thread(target=self.server_sock_thread_task)
self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_sock.setblocking(False)
self.sock1 = None
self.sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_sock.settimeout(0.5)
self.server_sock.bind((u'127.0.0.1', 0))
self.server_sock.listen(1)
self.server_sock_thread.start()
t1 = time.time()
while not self.thread_started:
if (time.time() - t1) > 0.5:
raise RuntimeError(u'Timeout while connecting sockets together.')
time.sleep(0.01)
time.sleep(0.01)
self.sock2.connect(self.server_sock.getsockname())
t1 = time.time()
while self.sock1 is None:
if (time.time() - t1) > 0.5:
raise RuntimeError(u'Timeout while connecting sockets together.')
def tearDown(self):
if isinstance(self.sock1, socket.socket):
self.sock1.close()
if isinstance(self.sock2, socket.socket):
self.sock2.close()
if isinstance(self.server_sock, socket.socket):
self.server_sock.close()
def test_open(self):
conn = SocketConnection(self.sock1, name=u'unittest')
self.assertFalse(conn.is_open())
conn.open()
self.assertTrue(conn.is_open())
conn.close()
self.assertFalse(conn.is_open())
def test_transmit(self):
conn1 = SocketConnection(self.sock1, name=u'unittest')
conn2 = SocketConnection(self.sock2, name=u'unittest')
with conn1.open():
with conn2.open():
payload1 = "\x00\x01\x02\x03\x04"
conn1.send(payload1)
payload2 = conn2.wait_frame(timeout=1, exception=True)
self.assertEqual(payload1, payload2)
class TestQueueConnection(UdsTest):
def setUp(self):
self.conn = QueueConnection(name=u'unittest')
self.conn.open()
def tearDown(self):
self.conn.close()
def test_open(self):
self.assertTrue(self.conn.is_open())
def test_receive(self):
payload = "\x00\x01\x02\x03"
self.conn.fromuserqueue.put(payload)
frame = self.conn.wait_frame()
self.assertEqual(frame, payload)
def test_send(self):
payload = "\x00\x01\x02\x03"
self.conn.send(payload)
frame = self.conn.touserqueue.get()
self.assertEqual(frame, payload)
def test_truncate(self):
payload = "\x00\x01\x02\x03"*5000
self.conn.send(payload)
frame = self.conn.touserqueue.get()
self.assertEqual(len(frame), 4095)
self.assertEqual(frame, payload[0:4095])
self.conn.fromuserqueue.put(payload)
frame = self.conn.wait_frame()
self.assertEqual(len(frame), 4095)
self.assertEqual(frame, payload[0:4095])
def test_reopen(self):
payload = "\x00\x01\x02\x03"
self.conn.send(payload)
self.conn.fromuserqueue.put(payload)
self.conn.close()
self.conn.open()
with self.assertRaises(TimeoutException):
self.conn.wait_frame(timeout=0.05, exception=True)
self.assertTrue(self.conn.touserqueue.empty())
class TestPythonIsoTpConnection(UdsTest):
def __init__(self, *args, **kwargs):
UdsTest.__init__(self, *args, **kwargs)
if not hasattr(self.__class__, u'_next_id'):
self.__class__._next_id=1
self.stack_txid = self.__class__._next_id
self.stack_rxid = self.__class__._next_id +1
self.__class__._next_id += 2
def make_bus(self):
return can.interface.Bus(bustype=u'socketcan', channel=u'vcan0', bitrate=500000, receive_own_messages=True)
def setUp(self):
self.vcan0_bus = self.make_bus()
addr = isotp.Address(isotp.AddressingMode.Normal_11bits, rxid=self.stack_rxid, txid=self.stack_txid)
self.conn = PythonIsoTpConnection(isotp.CanStack(bus=self.vcan0_bus, address=addr), name=u'unittest')
self.conn.open()
def test_open(self):
self.assertTrue(self.conn.is_open())
def test_receive(self):
self.vcan0_bus.send(can.Message(arbitration_id = self.stack_rxid, data = "\x03\x01\x02\x03", is_extended_id = False))
frame = self.conn.wait_frame(timeout=1)
self.assertEqual(frame, "\x01\x02\x03")
def test_send(self):
self.conn.send("\xAA\xBB\xCC\xDD\xEE\xFF")
t1 = time.time()
msg = self.vcan0_bus.recv(1)
self.assertIsNotNone(msg)
self.assertEqual(msg.data, '\x06\xAA\xBB\xCC\xDD\xEE\xFF')
def test_reopen(self):
self.conn.send("\x0A\x0B\x0C\x0D")
self.vcan0_bus.send(can.Message(arbitration_id = self.stack_rxid, data = "\x03\x01\x02\x03", is_extended_id = False))
self.conn.close()
self.vcan0_bus.shutdown()
self.vcan0_bus = self.make_bus()
self.conn.open(bus=self.vcan0_bus)
with self.assertRaises(TimeoutException):
self.conn.wait_frame(timeout=0.05, exception=True)
self.assertIsNone(self.vcan0_bus.recv(0))
def tearDown(self):
self.conn.close()
self.vcan0_bus.shutdown()
TestPythonIsoTpConnection = unittest.skipIf(_STACK_POSSIBLE == False, u'Cannot test TestPythonIsoTpConnection. %s' % _STACK_UNVAILABLE_REASON)(TestPythonIsoTpConnection)
|
treebot.py | # -*- coding: utf-8 -*-
import LINETCR
from LINETCR.lib.curve.ttypes import *
from datetime import datetime
import time,random,sys,json,codecs,threading,glob,requests,urllib
cl = LINETCR.LINE()
cl.login(token="Eoxe8DekCfJya0GNjEBc.yT2ChqpRlJtFWnXILcd8Ra.L6jRYlaLE1yyWh0OFL6TmeegZujAU0VvBrZE3uSwta0=")
cl.loginResult()
ki = ki2 = ki3 = ki4 = ki5 = cl
print u"login success"
reload(sys)
sys.setdefaultencoding('utf-8')
helpMessage ="""Ŧяәәƅoŧ v2.7
~~~~~~~ Command ~~~~~~~
¤ Tagall - Tagall Member Group
¤ Lurking - Set Point Read
¤ Result - Reading Point
¤ Ginfo - Info Grup
~~~~~~ Command Admin ~~~~~~
¤ Glist - List Group BOT
¤ Cancel - Cancel All Pending Grup
¤ Mid @ - Get MID
¤ Invite - Invite Via Send Contact
¤ Invite: - Via MID
¤ Whitelist @ - Via Tag
¤ Whitelist: - Via Mid
¤ Whitelist - Via Send Contact
¤ Blacklist @ - Via Tag
¤ Blacklist: - Via Mid
¤ Blacklist - Via Send Contact
¤ Clear ban - Delete All Blacklist
¤ Link on - Open QR
¤ Link off - Close QR
¤ Gurl - Open QR And Get Link
¤ Url - Get QR Link
¤ Gname - Change Name Group
¤ Banlist - Cek Tersangka Kriminal
¤ Details grup - Via Gid
¤ Inviteme: - Via Gid
¤ Info grup
¤ Clear grup
~~~~~ Command for kicker ~~~~~
¤ Nuke
¤ Ratakan
¤ Kick @ - Via Tag
¤ Kick: - Via MID
~~~~~~ Command Player ~~~~~~
¤ Bc:ct
¤ Bc:grup
¤ Block @
¤ Blocklist
¤ Spam on/off
¤ Uni
¤ Bot:ct - Contact BOT
¤ Bot:grup - Grup Joined BOT
¤ Allname: - Change All Name BOT
¤ Allbio: - Change All Bio BOT
¤ Bot sp - Tes Speed BOT
¤ Speed - Tes Speed
¤ Mycopy @ - Copy Profile
¤ Mybackup @ - Backup Profile
~~~~~~ Command Setting ~~~~~~
¤ [Like:on/off]
¤ [Add on/off]
¤ [Auto join on/off]
¤ [Contact on/off]
¤ [Leave on/off]
¤ [Share on/off]
¤ [Add on/off]
¤ [Jam on/off]
¤ [Jam say:]
¤ [Com on/off]
¤ [Message set:]
¤ [Comment set:]
¤ [Message add:]
~~~~ Auto Setting Command ~~~~~
¤ [Panick:on/off]
¤ [Protect on]
¤ [Qrprotect on/off]
¤ [Inviteprotect on/off]
¤ [Cancelprotect on/off]
¤ [Staff add/remove @]
~~~~~~~~ For Admin ~~~~~~~~
"""
KAC=[cl,ki,ki2,ki3,ki4,ki5]
mid = cl.getProfile().mid
kimid = ki.getProfile().mid
ki2mid = ki2.getProfile().mid
ki3mid = ki3.getProfile().mid
ki4mid = ki4.getProfile().mid
ki5mid = ki5.getProfile().mid
Bots = [mid,kimid,ki2mid,ki3mid,ki4mid,ki5mid,"u9489706a45fcf78bea076c6b77f7067d"]
admsa = "u9489706a45fcf78bea076c6b77f7067d"
admin = "u9489706a45fcf78bea076c6b77f7067d"
wait = {
'contact':False,
'autoJoin':True,
'autoCancel':{"on":True,"members":20},
'leaveRoom':True,
'timeline':False,
'autoAdd':True,
'message':" ",
"lang":"JP",
"comment":"Auto Like",
"commentOn":False,
"likeOn":False,
"commentBlack":{},
"wblack":False,
"dblack":False,
"clock":False,
"cNames":"",
"blacklist":{},
"wblacklist":False,
"dblacklist":False,
"protect":True,
"cancelprotect":False,
"inviteprotect":False,
"linkprotect":False,
}
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 = ki.getProfile()
backup = ki.getProfile()
backup.displayName = contact.displayName
backup.statusMessage = contact.statusMessage
backup.pictureStatus = contact.pictureStatus
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 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_ == "ucd886b532f581aa4de98af5898719392":
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=1001)
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:
ki.sendText(msg.to,"-> " + _name + " was here")
break
elif invite in wait["blacklist"]:
cl.sendText(msg.to,"Sorry, " + _name + " On Blacklist")
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:
ki.findAndAddContactsByMid(target)
ki.inviteIntoGroup(msg.to,[target])
random.choice(KAC).sendText(msg.to,"Invited this nigga💋: \n➡" + _name)
wait2["ricoinvite"] = False
break
except:
cl.sendText(msg.to,"Negative, Err0r Detected")
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 = "menempatkan URL\n" + msg.contentMetadata["postEndUrl"]
else:
msg.text = "URL→\n" + msg.contentMetadata["postEndUrl"]
cl.sendText(msg.to,msg.text)
elif msg.text is None:
return
elif msg.text.lower() == 'help':
if wait["lang"] == "JP":
cl.sendText(msg.to,helpMessage)
else:
cl.sendText(msg.to,helpMessage)
elif "Mybot" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': kimid}
ki.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': ki2mid}
ki2.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': ki3mid}
ki3.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': ki4mid}
ki4.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': ki5mid}
ki5.sendMessage(msg)
msg.contentType = 13
elif "Pro1" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': kimid}
ki.sendMessage(msg)
elif "Pro2" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': ki2mid}
ki2.sendMessage(msg)
elif "Pro3" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': ki3mid}
ki3.sendMessage(msg)
elif "Pro4" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': ki4mid}
ki4.sendMessage(msg)
elif "Pro5" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': ki5mid}
ki5.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
ki.sendMessage(msg)
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
ki2.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
ki3.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
ki4.sendMessage(msg)
elif msg.text in ["Cancel","cancel"]:
if msg.from_ in admin:
if msg.toType == 2:
group = cl.getGroup(msg.to)
if group.invitee is not None:
gInviMids = [contact.mid for contact in group.invitee]
cl.cancelGroupInvitation(msg.to, gInviMids)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"No invites👈")
else:
cl.sendText(msg.to,"Invite people inside not👈")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Tidak ada undangan👈")
else:
cl.sendText(msg.to,"invitan tidak ada")
elif "Contact" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': msg.to}
cl.sendMessage(msg)
elif "Pro1 mid" == msg.text:
ki.sendText(msg.to,kimid)
elif "Pro2 mid" == msg.text:
ki2.sendText(msg.to,ki2mid)
elif "Pro3 mid" == msg.text:
ki3.sendText(msg.to,ki3mid)
elif "Pro4 mid" == msg.text:
ki4.sendText(msg.to,ki4mid)
elif "Pro5 mid" == msg.text:
ki5.sendText(msg.to,ki5mid)
elif "All mid" == msg.text:
ki.sendText(msg.to,kimid)
ki2.sendText(msg.to,ki2mid)
ki3.sendText(msg.to,ki3mid)
ki4.sendText(msg.to,ki4mid)
ki5.sendText(msg.to,ki5mid)
elif "Timeline: " in msg.text:
tl_text = msg.text.replace("Timeline: ","")
cl.sendText(msg.to,"line://home/post?userMid="+mid+"&postId="+cl.new_post(tl_text)["result"]["post"]["postInfo"]["postId"])
elif "Allname: " in msg.text:
string = msg.text.replace("Allname: ","")
if len(string.decode('utf-8')) <= 20:
profile = ki.getProfile()
profile.displayName = string
ki.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = ki2.getProfile()
profile.displayName = string
ki2.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = ki3.getProfile()
profile.displayName = string
ki3.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = ki4.getProfile()
profile.displayName = string
ki4.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = ki5.getProfile()
profile.displayName = string
ki5.updateProfile(profile)
elif "Allbio: " in msg.text:
string = msg.text.replace("Allbio: ","")
if len(string.decode('utf-8')) <= 500:
profile = ki.getProfile()
profile.statusMessage = string
ki.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = ki2.getProfile()
profile.statusMessage = string
ki2.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = ki3.getProfile()
profile.statusMessage = string
ki3.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = ki4.getProfile()
profile.statusMessage = string
ki4.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = ki5.getProfile()
profile.statusMessage = string
ki5.updateProfile(profile)
#---------------------------------------------------------
elif "1pro: " in msg.text:
string = msg.text.replace("1pro: ","")
if len(string.decode('utf-8')) <= 20:
profile = ki.getProfile()
profile.displayName = string
ki.updateProfile(profile)
ki.sendText(msg.to,"Update Names👉" + string + "👈")
#--------------------------------------------------------
elif "2pro: " in msg.text:
string = msg.text.replace("2pro: ","")
if len(string.decode('utf-8')) <= 20:
profile = ki2.getProfile()
profile.displayName = string
ki2.updateProfile(profile)
ki2.sendText(msg.to,"Update Names👉" + string + "👈")
#--------------------------------------------------------
elif "3pro: " in msg.text:
string = msg.text.replace("3pro: ","")
if len(string.decode('utf-8')) <= 20:
profile = ki3.getProfile()
profile.displayName = string
ki3.updateProfile(profile)
ki3.sendText(msg.to,"Update Names👉" + string + "👈")
#--------------------------------------------------------
elif "4pro: " in msg.text:
string = msg.text.replace("4pro: ","")
if len(string.decode('utf-8')) <= 20:
profile = ki4.getProfile()
profile.displayName = string
ki4.updateProfile(profile)
ki4.sendText(msg.to,"Update Names👉" + string + "👈")
#--------------------------------------------------------
elif "5pro: " in msg.text:
string = msg.text.replace("5pro: ","")
if len(string.decode('utf-8')) <= 20:
profile = ki5.getProfile()
profile.displayName = string
ki5.updateProfile(profile)
ki5.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 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,"It's already on 👈")
else:
cl.sendText(msg.to,"It is already open ô€¨👈")
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,"It's already on ��👈")
else:
cl.sendText(msg.to,"It is already open ô€¨👈")
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,"It's already on 👈")
else:
cl.sendText(msg.to,"It is already open ô€¨����👈")
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,"It's already on 👈")
else:
cl.sendText(msg.to,"It is already open ô€¨👈")
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,"It's already off 👈")
else:
cl.sendText(msg.to,"It is already open ô€¨👈")
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,"It's already 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,"It's already 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,"It's already 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,"It's already 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,"It's already 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,"It's already 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,"It's already 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,"this hall is off ô€œ👈")
else:
cl.sendText(msg.to,"already turned off ô€œô€„‰👈")
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,"this hall is off ô€œ👈")
else:
cl.sendText(msg.to,"already turned off ô€œô€„‰👈")
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"]:
if wait["inviteprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"this hall is off ô€œ👈")
else:
cl.sendText(msg.to,"already turned off ô€œô€„‰👈")
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"]:
if wait["cancelprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"this hall is off ô€œ👈")
else:
cl.sendText(msg.to,"already turned off ô€œô€„‰👈")
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,"It was off invitation denied👈\nPlease send by determining the number of people when you turn on👈")
else:
cl.sendText(msg.to,"Off invitation denied👈Mention the amount open when you want to send")
else:
num = int(strnum)
wait["autoCancel"]["on"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,strnum + "The following groups invited will be automatically rejected👈")
else:
cl.sendText(msg.to,strnum + "The team declined to create the following automatic invitation")
except:
if wait["lang"] == "JP":
kk.sendText(msg.to,"The value is incorrect👈")
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,"Already opened")
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,"It's 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() == 'settings':
md = ""
if wait["contact"] == True: md+="☞ Contact → ✔\n"
else: md+="☞ Contact → ❌\n"
if wait["autoJoin"] == True: md+="☞ Auto Join → ✔\n"
else: md+="☞ Auto Join → ❌\n"
if wait["autoCancel"]["on"] == True:md+="☞ Auto cancel: " + str(wait["autoCancel"]["members"]) + " → ✔\n"
else: md+="☞ Group cancel → ❌\n"
if wait["leaveRoom"] == True: md+="☞ Auto leave → ✔\n"
else: md+="☞ Auto leave → ❌\n"
if wait["timeline"] == True: md+="☞ share → ✔\n"
else:md+="☞ Share → ❌\n"
if wait["autoAdd"] == True: md+="☞ Auto add → ✔\n"
else:md+="☞ Auto add → ❌\n"
if wait["commentOn"] == True: md+="☞ Auto comment → ✔\n"
else:md+="☞ Auto comment → ❌\n"
if wait["protect"] == True: md+="☞ Protect → ✔\n"
else:md+="☞ Protect → ❌\n"
if wait["linkprotect"] == True: md+="☞ Link Protect → ✔\n"
else:md+="☞ Link Protect → ❌\n"
if wait["inviteprotect"] == True: md+="☞ Invitation Protect → ✔\n"
else:md+="☞ Invitation Protect → ❌\n"
if wait["cancelprotect"] == True: md+="☞ Cancel Protect → ✔\n"
else:md+="☞ Cancel Protect → ❌\n"
if wait["likeOn"] == True: md+="☞ Auto like → ✔\n"
else:md+="☞ Auto like → ❌\n"
cl.sendText(msg.to,md)
#msg.contentType = 13
#msg.contentMetadata = {'mid': admsa}
#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 ["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,"It is already off👈")
else:
cl.sendText(msg.to,"It is already turned off👈")
else:
wait["autoAdd"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already Off👈")
else:
cl.sendText(msg.to,"To enable-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,"We changed the message🛡")
else:
cl.sendText(msg.to,"Change information")
elif msg.text in ["Message add check","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,"Additional auto messages have been set as follows \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 english👈")
else:
wait["lang"] = "JP"
cl.sendText(msg.to,"I changed the language to thai👈")
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,"It is a string that can not be changed👈")
else:
wait["comment"] = c
cl.sendText(msg.to,"This has been changed👈\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,"I was on👈")
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 ["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 is currently set as follows:👈\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 blacklistô€œô€…”👈")
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 blacklistô€œô€…”👈")
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,"It is already off🛡")
else:
wait["clock"] = False
cl.sendText(msg.to,"Is Off")
elif "Jam say: " in msg.text:
n = msg.text.replace("Jam say: ","")
if len(n.decode("utf-8")) > 30:
cl.sendText(msg.to,"too long")
else:
wait["cName"] = n
cl.sendText(msg.to,"This has been changed🛡\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,"Updated👈")
else:
cl.sendText(msg.to,"Please Unlock Name")
elif msg.text == "Lurking":
if msg.toType == 2:
cl.sendText(msg.to, "Set reading point:" + 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 == "Result":
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, "---------------\nActive readers:%s\n\n\n\nPassive readers:\n%s\n\n---------------\nIn the last seen point:\n[%s]\n---------------\n [☸]➦Powered By: Ŧяәәƅoŧ•┅─────" % (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, "Auto set reading point in:" + datetime.now().strftime('\n%Y-%m-%d %H:%M:%S'))
else:
cl.sendText(msg.to, "Reading point has not been set.")
#-----------------------[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 == []:
ki.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"
#----------------------ADMIN COMMAND------------------------------#
elif ("Kick " 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 "Tagall" in msg.text:
group = cl.getGroup(msg.to)
k = len(group.members)//500
for j in xrange(k+1):
msg = Message(to=msg.to)
txt = u''
s=0
d=[]
for i in group.members[j*500 : (j+1)*500]:
d.append({"S":str(s), "E" :str(s+8), "M":i.mid})
s += 9
txt += u'@Krampus\n'
msg.text = txt
msg.contentMetadata = {u'MENTION':json.dumps({"MENTIONEES":d})}
cl.sendMessage(msg)
elif "Ratakan" in msg.text:
if msg.from_ in admin:
nk0 = msg.text.replace("Ratakan","")
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,"Success Bosqu")
cl.sendText(msg.to,"Christ Mouko Sundla")
elif msg.text in ["List grup"]:
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,"There are no groups at this time")
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.members))
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,"There are no pending groups at this time")
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 = ki.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,"There are no groups at this time")
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,"There are no pending groups at this time")
elif "Details grup: " in msg.text:
if msg.from_ in admin:
gid = msg.text.replace("/DetailsGroup: ","")
if gid in [""," "]:
cl.sendText(msg.to,"Invalid id group")
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,"Successfully rejected the invite from the group " + gid.name)
else:
cl.sendText(msg.to,"Group not found")
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,"Successfully accepted all invites from the group :\n" + _list)
else:
cl.sendText(msg.to,"There are no pending groups at this time")
elif "Myname: " in msg.text:
string = msg.text.replace("Myname: ","")
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Update Bio" + string)
elif "Mybio: " in msg.text:
string = msg.text.replace("Mybio: ","")
if len(string.decode('utf-8')) <= 500:
profile = cl.getProfile()
profile.statusMessage = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Update Bio" + string)
elif ("Gname: " in msg.text):
if msg.toType == 2:
group = cl.getGroup(msg.to)
group.name = msg.text.replace("Gname: ","")
cl.updateGroup(group)
else:
cl.sendText(msg.to,"Can not Change Group Name")
elif "Kick: " in msg.text:
if msg.from_ in admin:
midd = msg.text.replace("Kick: ","")
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 "Mysteal @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Mysteal @","")
_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)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
cl.sendImageWithURL(msg.to, path)
except:
pass
print "[Command]dp executed"
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, "No Target Copy")
else:
for target in targets:
try:
ki.cloneContactProfile(target)
ki2.cloneContactProfile(target)
ki3.cloneContactProfile(target)
ki4.cloneContactProfile(target)
ki5.cloneContactProfile(target)
cl.sendText(msg.to, "Success Copy Profile")
except Exception as e:
print e
elif msg.text in ["Mybackup"]:
try:
cl.updateDisplayPicture(mybackup.pictureStatus)
cl.updateProfile(mybackup)
cl.sendText(msg.to, "Backup Success Bosqu")
except Exception as e:
cl.sendText(msg.to, str (e))
elif msg.text in ["Backup"]:
try:
ki.updateDisplayPicture(backup.pictureStatus)
ki.updateProfile(backup)
ki2.updateDisplayPicture(backup.pictureStatus)
ki2.updateProfile(backup)
ki3.updateDisplayPicture(backup.pictureStatus)
ki3.updateProfile(backup)
ki4.updateDisplayPicture(backup.pictureStatus)
ki4.updateProfile(backup)
ki5.updateDisplayPicture(backup.pictureStatus)
ki5.updateProfile(backup)
cl.sendText(msg.to, "Backup Success Bosqu")
except Exception as e:
cl.sendText(msg.to, str (e))
elif "Bc:ct " in msg.text:
bctxt = msg.text.replace("Bc:ct ", "")
a = cl.getAllContactIds()
for manusia in a:
cl.sendText(manusia, (bctxt))
elif "Bot:ct " in msg.text:
if msg.from_ in admin:
bctxt = msg.text.replace("Bot:ct ", "")
b = ki.getAllContactIds()
for manusia in b:
ki.sendText(manusia, (bctxt))
c = ki2.getAllContactIds()
for manusia in c:
ki2.sendText(manusia, (bctxt))
d = ki3.getAllContactIds()
for manusia in d:
ki3.sendText(manusia, (bctxt))
e = ki4.getAllContactIds()
for manusia in e:
ki4.sendText(manusia, (bctxt))
f = ki5.getAllContactIds()
for manusia in f:
ki5.sendText(manusia, (bctxt))
elif "Bc:grup " in msg.text:
bctxt = msg.text.replace("Bc:grup ", "")
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 = ki.getGroupIdsJoined()
for manusia in b:
ki.sendText(manusia, (bctxt))
c = ki2.getGroupIdsJoined()
for manusia in c:
ki2.sendText(manusia, (bctxt))
d = ki3.getGroupIdsJoined()
for manusia in d:
ki3.sendText(manusia, (bctxt))
e = ki4.getGroupIdsJoined()
for manusia in e:
ki4.sendText(manusia, (bctxt))
f = ki5.getGroupIdsJoined()
for manusia in f:
ki5.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")
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","speed"]:
start = time.time()
cl.sendText(msg.to, "Waitting...")
elapsed_time = time.time() - start
cl.sendText(msg.to, "%sseconds" % (elapsed_time))
elif msg.text.lower() == 'me':
msg.contentType = 13
msg.contentMetadata = {'mid': mid}
cl.sendMessage(msg)
elif cms(msg.text,["creator","Creator"]):
msg.contentType = 13
msg.contentMetadata = {'mid': admsa}
cl.sendText(msg.to," My Creator ")
cl.sendMessage(msg)
cl.sendText(msg.to," Dont Kick out From group ")
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,"Maybe I'm not in that group")
elif msg.text in ["Clear grup"]:
if msg.from_ in admin:
gid = cl.getGroupIdsJoined()
gid = ki.getGroupIdsJoined()
gid = ki2.getGroupIdsJoined()
gid = ki3.getGroupIdsJoined()
gid = ki4.getGroupIdsJoined()
gid = ki5.getGroupIdsJoined()
for i in gid:
ki.leaveGroup(i)
ki2.leaveGroup(i)
ki3.leaveGroup(i)
ki4.leaveGroup(i)
ki5.leaveGroup(i)
if wait["lang"] == "JP":
cl.sendText(msg.to,"Bot Exits In all groups")
else:
cl.sendText(msg.to,"He decline all invitations")
elif msg.text == "Ginfo":
group = cl.getGroup(msg.to)
try:
gCreator = group.creator.displayName
except:
gCreator = "Error"
md = "[Group Name : ]\n" + group.name + "\n\n[Id Grup : ]\n" + group.id + "\n\n[Group Creator :]\n" + gCreator + "\n\n[Group Image : ]\nhttp://dl.profile.line-cdn.net/" + group.pictureStatus
if group.preventJoinByTicket is False: md += "\n\nKode Url : Diizinkan"
else: md += "\n\node Url : Blocked"
if group.invitee is None: md += "\nNumber of Members : " + str(len(group.members)) + " Orang" + "\nUnanswered Invitations : 0 Orang"
else: md += "\nNumber of Members : " + str(len(group.members)) + " Orang" + "\nUnanswered Invitations : " + str(len(group.invitee)) + " Orang"
cl.sendText(msg.to,md)
elif msg.text == "Uni":
cl.sendText(msg.to,"Hai 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 ".music" in msg.text.lower():
songname = msg.text.lower().replace(".music","")
params = {"songname":" songname"}
r = requests.get('https://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
cl.sendMessage(msg.to, song[4])
elif ".Youtube " in msg.text:
query = msg.text.replace(".Youtube ","")
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')
for a in soup.select('.yt-lockup-title > a[title]'):
if '&List' not in a['href']:
cl.sendText(msg.to,'http://www.youtube.com' + a['href'] + a['title'])
elif "Block @" in msg.text:
if msg.toType == 2:
print "[block] OK"
_name = msg.text.replace("Block @","")
_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.blockContact(target)
cl.sendText(msg.to, "Success block contact~")
except Exception as e:
print e
elif msg.text.lower() == 'blocklist':
blockedlist = cl.getBlockedContactIds()
cl.sendText(msg.to, "Please wait...")
kontak = cl.getContacts(blockedlist)
num=1
msgs="User Blocked List\n"
for ids in kontak:
msgs+="\n%i. %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n\nTotal %i blocked user(s)" % len(kontak)
cl.sendText(msg.to, msgs)
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"+ 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,"send contact 😉")
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:
ki.sendText(msg.to, g.mid)
else:
pass
elif "Mymid" == msg.text:
cl.sendText(msg.to,mid)
elif msg.text in ["Link on"]:
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,"URL open")
else:
cl.sendText(msg.to,"URL open")
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 ["Link off"]:
if msg.toType == 2:
group = cl.getGroup(msg.to)
group.preventJoinByTicket = True
cl.updateGroup(group)
if wait["lang"] == "JP":
cl.sendText(msg.to,"URL close👈")
else:
cl.sendText(msg.to,"URL close👈")
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,"line://ti/g/" + gurl)
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 ["Gurl"]:
if msg.toType == 2:
x = cl.getGroup(msg.to)
if x.preventJoinByTicket == True:
x.preventJoinByTicket = False
cl.updateGroup(x)
gurl = cl.reissueGroupTicket(msg.to)
cl.sendText(msg.to,"line://ti/g/" + gurl)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can't be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
elif msg.text in ["S1glist"]:
gs = ki.getGroupIdsJoined()
L = "☫『 Groups List 』☫\n"
for i in gs:
L += "[⭐] %s \n" % (ki.getGroup(i).name + " | [ " + str(len (ki.getGroup(i).members)) + " ]")
ki.sendText(msg.to, L + "\nTotal Group : [ " + str(len(gs)) +" ]")
elif msg.text in ["S2glist"]:
gs = ki2.getGroupIdsJoined()
L = "☫『 Groups List 』☫\n"
for i in gs:
L += "[⭐] %s \n" % (ki2.getGroup(i).name + " | [ " + str(len (ki2.getGroup(i).members)) + " ]")
ki2.sendText(msg.to, L + "\nTotal Group : [ " + str(len(gs)) +" ]")
elif msg.text in ["S3glist"]:
gs = ki3.getGroupIdsJoined()
L = "☫『 Groups List 』☫\n"
for i in gs:
L += "[⭐] %s \n" % (ki3.getGroup(i).name + " | [ " + str(len (ki3.getGroup(i).members)) + " ]")
ki3.sendText(msg.to, L + "\nTotal Group : [ " + str(len(gs)) +" ]")
elif msg.text in ["S4glist"]:
gs = ki4.getGroupIdsJoined()
L = "☫『 Groups List 』☫\n"
for i in gs:
L += "[⭐] %s \n" % (ki4.getGroup(i).name + " | [ " + str(len (ki4.getGroup(i).members)) + " ]")
ki4.sendText(msg.to, L + "\nTotal Group : [ " + str(len(gs)) +" ]")
elif msg.text in ["S5glist"]:
gs = ki5.getGroupIdsJoined()
L = "☫『 Groups List 』☫\n"
for i in gs:
L += "[⭐] %s \n" % (ki5.getGroup(i).name + " | [ " + str(len (ki5.getGroup(i).members)) + " ]")
ki5.sendText(msg.to, L + "\nTotal Group : [ " + str(len(gs)) +" ]")
elif msg.text == "Link bokep":
ki.sendText(msg.to,"nekopoi.host")
ki.sendText(msg.to,"sexvideobokep.com")
ki.sendText(msg.to,"memek.com")
ki.sendText(msg.to,"pornktube.com")
ki.sendText(msg.to,"faketaxi.com")
ki.sendText(msg.to,"videojorok.com")
ki.sendText(msg.to,"watchmygf.mobi")
ki.sendText(msg.to,"xnxx.com")
ki.sendText(msg.to,"pornhd.com")
ki.sendText(msg.to,"xvideos.com")
ki.sendText(msg.to,"vidz7.com")
ki.sendText(msg.to,"m.xhamster.com")
ki.sendText(msg.to,"xxmovies.pro")
ki.sendText(msg.to,"youporn.com")
ki.sendText(msg.to,"pornhub.com")
ki.sendText(msg.to,"anyporn.com")
ki.sendText(msg.to,"hdsexdino.com")
ki.sendText(msg.to,"rubyourdick.com")
ki.sendText(msg.to,"anybunny.mobi")
ki.sendText(msg.to,"cliphunter.com")
ki.sendText(msg.to,"sexloving.net")
ki.sendText(msg.to,"free.goshow.tv")
ki.sendText(msg.to,"eporner.com")
ki.sendText(msg.to,"Pornhd.josex.net")
ki.sendText(msg.to,"m.hqporner.com")
ki.sendText(msg.to,"m.spankbang.com")
ki.sendText(msg.to,"m.4tube.com")
ki.sendText(msg.to,"brazzers.com")
#-----------------------------------------------------------
elif "#leave" in msg.text:
try:
import sys
sys.exit()
except:
pass
#-----------------------------------------------------------
elif msg.text in ["Bot sp","Bot speed"]:
start = time.time()
ki.sendText(msg.to, "Waiting...")
elapsed_time = time.time() - start
ki.sendText(msg.to, "%sseconds" % (elapsed_time))
elapsed_time = time.time() - start
ki2.sendText(msg.to, "%sseconds" % (elapsed_time))
elapsed_time = time.time() - start
ki3.sendText(msg.to, "%sseconds" % (elapsed_time))
elapsed_time = time.time() - start
ki4.sendText(msg.to, "%sseconds" % (elapsed_time))
elapsed_time = time.time() - start
elif msg.text.lower() == 'responsname':
profile = ki.getProfile()
text = profile.displayName
ki.sendText(msg.to, text)
profile = ki2.getProfile()
text = profile.displayName
ki2.sendText(msg.to, text)
profile = ki3.getProfile()
text = profile.displayName
ki3.sendText(msg.to, text)
profile = ki4.getProfile()
text = profile.displayName
ki4.sendText(msg.to, text)
#------------------------------------------------------------------
elif "Steal home @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Steal home @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = cl.getContact(target)
cu = cl.channel.getCover(target)
path = str(cu)
cl.sendImageWithURL(msg.to, path)
except:
pass
print "[Command]dp executed"
#------------------------------------------------------------------
elif "Blacklist @" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "[BL]ok"
_name = msg.text.replace("Blacklist @","")
_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:
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,"Success Boss")
except:
cl.sendText(msg.to,"Error")
elif "Blacklist all" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "ok"
_name = msg.text.replace("Blacklist all","")
gs = cl.getGroup(msg.to)
cl.sendText(msg.to,"Semua Telah Di Hapus")
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,"Success Boss")
except:
cl.sentText(msg.to,"Berhasil Dihapus")
elif "Whitelist @" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "[WL]ok"
_name = msg.text.replace("Whitelist @","")
_nametarget = _name.rstrip(' ')
gs = ki.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Not found.")
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,"Success Boss")
except:
cl.sendText(msg.to,"There was no blacklist user")
elif "Blacklist: " in msg.text:
if msg.from_ in admin:
nk0 = msg.text.replace("Blacklist: ","")
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 "Whitelist: " in msg.text:
if msg.from_ in admin:
nk0 = msg.text.replace("Whitelist: ","")
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,"clear")
elif msg.text in ["Whitelist"]:
if msg.from_ in admin:
wait["wblacklist"] = True
cl.sendText(msg.to,"send contact to ban")
elif msg.text in ["Blacklist"]:
if msg.from_ in admin:
wait["dblacklist"] = True
cl.sendText(msg.to,"send contact to ban")
elif msg.text in ["Banlist"]:
if msg.from_ in admin:
if wait["blacklist"] == {}:
cl.sendText(msg.to,"Nothing double thumbs up")
else:
cl.sendText(msg.to,"Daftar Banlist")
mc = "[⎈]Blacklist [⎈]\n"
for mi_d in wait["blacklist"]:
mc += "[✗] " + cl.getContact(mi_d).displayName + " \n"
cl.sendText(msg.to, mc + "")
elif msg.text in ["Ban cek","Cekban"]:
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 Blacklist [⎈]"
for mm in matched_list:
cocoa += "\n" + mm + "\n"
cl.sendText(msg.to,cocoa + "")
elif msg.text.lower() == 'kill':
if msg.from_ in admin:
if msg.toType == 2:
group = ki.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
if matched_list == []:
ki.sendText(msg.to,"No Blacklist List")
return
for jj in matched_list:
try:
cl.kickoutFromGroup(msg.to,[jj])
ki.kickoutFromGroup(msg.to,[jj])
ki2.kickoutFromGroup(msg.to,[jj])
ki3.kickoutFromGroup(msg.to,[jj])
ki4.kickoutFromGroup(msg.to,[jj])
ki5.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 = ki.getGroup(msg.to)
gs = ki2.getGroup(msg.to)
gs = ki3.getGroup(msg.to)
gs = ki4.getGroup(msg.to)
gs = ki5.getGroup(msg.to)
cl.sendText(msg.to,"Christ Mouko Sundla")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"No Member")
ki2.sendText(msg.to,"Nothing Bosqu")
else:
for target in targets:
if not target in Bots:
try:
klist=[cl,ki,ki2,ki3,ki4,ki5]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
ki.sendText(msg,to,"Hahaha")
ki2.sendText(msg,to,"Fakyu Sundal")
#-----------------------------------------------
elif msg.text.lower() == ["join all"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
ki5.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 ["Sayang","Kuy","All join","Minna"]:
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)
ki.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
ki5.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
ki.updateGroup(G)
elif msg.text.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)
ki.acceptGroupInvitationByTicket(msg.to,Ticket)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
ki5.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
ki.updateGroup(G)
#-----------------------------------------------
elif "Pro1 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)
ki.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
ki.updateGroup(G)
#-----------------------------------------------
elif "Pro2 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)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki2.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
ki2.updateGroup(G)
#-----------------------------------------------
elif "Pro3 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)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki2.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
ki2.updateGroup(G)
#-----------------------------------------------
elif "Pro4 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)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki3.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
ki3.updateGroup(G)
#-----------------------------------------------
elif "Pro5 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)
ki5.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki5.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
ki5.updateGroup(G)
#-----------------------------------------------
elif msg.text in ["See you","Dadah","Good bye","Sayonara"]:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
cl.sendText(msg.to,"Bye Bye😘 " + str(ginfo.name) + "")
ki.leaveGroup(msg.to)
ki2.leaveGroup(msg.to)
ki3.leaveGroup(msg.to)
ki4.leaveGroup(msg.to)
ki5.leaveGroup(msg.to)
except:
pass
#-----------------------------------------------
elif "Pro1 bye" in msg.text:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
ki.leaveGroup(msg.to)
except:
pass
#-----------------------------------------------
elif "Pro2 bye" in msg.text:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
ki.leaveGroup(msg.to)
except:
pass
#-----------------------------------------------
elif "Pro3 bye" in msg.text:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
ki3.leaveGroup(msg.to)
except:
pass
#-----------------------------------------------
elif "Pro4 bye" in msg.text:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
ki4.leaveGroup(msg.to)
except:
pass
#-----------------------------------------------
elif "Pro5 bye" in msg.text:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
ki5.leaveGroup(msg.to)
except:
pass
#-----------------------------------------------
elif msg.text in ["Welcome","wc","welcome","Wc"]:
ginfo = cl.getGroup(msg.to)
cl.sendText(msg.to,"Welcom to Group " + str(ginfo.name))
cl.sendText(msg.to,"Owner Group " + str(ginfo.name) + " :\n" + ginfo.creator.displayName )
#-----------------------------------------------
if op.type == 19:
try:
if op.param3 in mid:
if op.param2 in kimid:
G = ki.getGroup(op.param1)
G.preventJoinByTicket = False
ki.updateGroup(G)
Ticket = ki.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
else:
G = ki.getGroup(op.param1)
ki.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ki.updateGroup(G)
Ticket = ki.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
ki.updateGroup(G)
wait["blacklist"][op.param2] = True
elif op.param3 in kimid:
if op.param2 in ki2mid:
G = ki2.getGroup(op.param1)
G.preventJoinByTicket = False
ki2.updateGroup(G)
Ticket = ki2.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki2.updateGroup(G)
else:
G = ki2.getGroup(op.param1)
ki2.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ki2.updateGroup(G)
Ticket = ki2.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki.updateGroup(G)
elif op.param3 in ki3mid:
if op.param2 in ki2mid:
G = ki2.getGroup(op.param1)
G.preventJoinByTicket = False
ki2.updateGroup(G)
Ticket = ki2.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki2.updateGroup(G)
else:
G = cl.getGroup(op.param1)
ki2.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ki2.updateGroup(G)
Ticket = ki2.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki2.updateGroup(G)
elif op.param3 in ki2mid:
if op.param2 in ki3mid:
G = ki3.getGroup(op.param1)
G.preventJoinByTicket = False
ki3.updateGroup(G)
Ticket = ki3.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki3.updateGroup(G)
else:
G = cl.getGroup(op.param1)
ki4.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ki4.updateGroup(G)
Ticket = ki3.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
elif op.param3 in ki4mid:
if op.param2 in ki5mid:
G = ki5.getGroup(op.param1)
G.preventJoinByTicket = False
ki5.updateGroup(G)
Ticket = ki5.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
else:
G = ki5.getGroup(op.param1)
ki5.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ki5.updateGroup(G)
Ticket = ki5.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki5.updateGroup(G)
elif op.param3 in ki5mid:
if op.param2 in ki4mid:
G = ki4.getGroup(op.param1)
G.preventJoinByTicket = False
ki4.updateGroup(G)
Ticket = ki4.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki4.updateGroup(G)
else:
G = ki4.getGroup(op.param1)
ki4.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ki4.updateGroup(G)
Ticket = ki4.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki4.updateGroup(G)
elif op.param3 in ki6mid:
if op.param2 in ki5mid:
G = ki5.getGroup(op.param1)
G.preventJoinByTicket = False
ki5.updateGroup(G)
Ticket = ki5.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki5.updateGroup(G)
else:
G = ki5.getGroup(op.param1)
ki5.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ki5.updateGroup(G)
Ticket = ki5.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki5.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
ki4.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 = ki.getGroup(op.param1)
G.preventJoinByTicket = True
ki.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():
count = 1
while True:
try:
for posts in cl.activity(1)["result"]["posts"]:
if posts["postInfo"]["liked"] is False:
if wait["likeOn"] == True:
cl.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
ki.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
ki2.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
ki3.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
ki4.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
ki5.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
print "Like"
if wait["commentOn"] == True:
if posts["userInfo"]["writerMid"] in wait["commentBlack"]:
pass
else:
cl.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"])
ki.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"])
ki2.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"])
ki3.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"])
ki4.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"])
ki5.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"])
except:
count += 1
if(count == 50):
sys.exit(0)
else:
pass
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)
#------------------------------------------------------------------------------------------
|
callbacks_test.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Keras callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import csv
import os
import re
import shutil
import sys
import threading
import unittest
from absl.testing import parameterized
import numpy as np
from tensorflow.python import keras
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import context
from tensorflow.python.framework import random_seed
from tensorflow.python.keras import keras_parameterized
from tensorflow.python.keras import testing_utils
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import summary_ops_v2
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training import adam
from tensorflow.python.util import tf_contextlib
try:
import h5py # pylint:disable=g-import-not-at-top
except ImportError:
h5py = None
try:
import requests # pylint:disable=g-import-not-at-top
except ImportError:
requests = None
TRAIN_SAMPLES = 10
TEST_SAMPLES = 10
NUM_CLASSES = 2
INPUT_DIM = 3
NUM_HIDDEN = 5
BATCH_SIZE = 5
class Counter(keras.callbacks.Callback):
"""Counts the number of times each callback method was run.
Attributes:
method_counts: dict. Contains the counts of time each callback method was
run.
"""
def __init__(self):
self.method_counts = collections.defaultdict(int)
methods_to_count = [
'on_batch_begin', 'on_batch_end', 'on_epoch_begin', 'on_epoch_end',
'on_predict_batch_begin', 'on_predict_batch_end', 'on_predict_begin',
'on_predict_end', 'on_test_batch_begin', 'on_test_batch_end',
'on_test_begin', 'on_test_end', 'on_train_batch_begin',
'on_train_batch_end', 'on_train_begin', 'on_train_end'
]
for method_name in methods_to_count:
setattr(self, method_name,
self.wrap_with_counts(method_name, getattr(self, method_name)))
def wrap_with_counts(self, method_name, method):
def _call_and_count(*args, **kwargs):
self.method_counts[method_name] += 1
return method(*args, **kwargs)
return _call_and_count
def _get_numpy():
return np.ones((10, 10)), np.ones((10, 1))
def _get_sequence():
class MySequence(keras.utils.data_utils.Sequence):
def __getitem__(self, _):
return np.ones((2, 10)), np.ones((2, 1))
def __len__(self):
return 5
return MySequence(), None
@keras_parameterized.run_with_all_model_types
@keras_parameterized.run_all_keras_modes
class CallbackCountsTest(keras_parameterized.TestCase):
def _check_counts(self, counter, expected_counts):
"""Checks that the counts registered by `counter` are those expected."""
for method_name, expected_count in expected_counts.items():
self.assertEqual(
counter.method_counts[method_name],
expected_count,
msg='For method {}: expected {}, got: {}'.format(
method_name, expected_count, counter.method_counts[method_name]))
def _get_model(self):
layers = [
keras.layers.Dense(10, activation='relu'),
keras.layers.Dense(1, activation='sigmoid')
]
model = testing_utils.get_model_from_layers(layers, input_shape=(10,))
model.compile(
adam.AdamOptimizer(0.001),
'binary_crossentropy',
run_eagerly=testing_utils.should_run_eagerly())
return model
@parameterized.named_parameters(('with_numpy', _get_numpy()),
('with_sequence', _get_sequence()))
def test_callback_hooks_are_called_in_fit(self, data):
x, y = data
val_x, val_y = np.ones((4, 10)), np.ones((4, 1))
model = self._get_model()
counter = Counter()
model.fit(
x,
y,
validation_data=(val_x, val_y),
batch_size=2,
epochs=5,
callbacks=[counter])
self._check_counts(
counter, {
'on_batch_begin': 25,
'on_batch_end': 25,
'on_epoch_begin': 5,
'on_epoch_end': 5,
'on_predict_batch_begin': 0,
'on_predict_batch_end': 0,
'on_predict_begin': 0,
'on_predict_end': 0,
'on_test_batch_begin': 10,
'on_test_batch_end': 10,
'on_test_begin': 5,
'on_test_end': 5,
'on_train_batch_begin': 25,
'on_train_batch_end': 25,
'on_train_begin': 1,
'on_train_end': 1
})
@parameterized.named_parameters(('with_numpy', _get_numpy()),
('with_sequence', _get_sequence()))
def test_callback_hooks_are_called_in_evaluate(self, data):
x, y = data
model = self._get_model()
counter = Counter()
model.evaluate(x, y, batch_size=2, callbacks=[counter])
self._check_counts(
counter, {
'on_test_batch_begin': 5,
'on_test_batch_end': 5,
'on_test_begin': 1,
'on_test_end': 1
})
@parameterized.named_parameters(('with_numpy', _get_numpy()),
('with_sequence', _get_sequence()))
def test_callback_hooks_are_called_in_predict(self, data):
x = data[0]
model = self._get_model()
counter = Counter()
model.predict(x, batch_size=2, callbacks=[counter])
self._check_counts(
counter, {
'on_predict_batch_begin': 5,
'on_predict_batch_end': 5,
'on_predict_begin': 1,
'on_predict_end': 1
})
def test_callback_list_methods(self):
counter = Counter()
callback_list = keras.callbacks.CallbackList([counter])
batch = 0
callback_list.on_test_batch_begin(batch)
callback_list.on_test_batch_end(batch)
callback_list.on_predict_batch_begin(batch)
callback_list.on_predict_batch_end(batch)
self._check_counts(
counter, {
'on_test_batch_begin': 1,
'on_test_batch_end': 1,
'on_predict_batch_begin': 1,
'on_predict_batch_end': 1
})
class KerasCallbacksTest(keras_parameterized.TestCase):
def _get_model(self, input_shape=None):
layers = [
keras.layers.Dense(3, activation='relu'),
keras.layers.Dense(2, activation='softmax')
]
model = testing_utils.get_model_from_layers(layers, input_shape=input_shape)
model.compile(
loss='mse',
optimizer='rmsprop',
metrics=[keras.metrics.CategoricalAccuracy(name='my_acc')],
run_eagerly=testing_utils.should_run_eagerly())
return model
@keras_parameterized.run_with_all_model_types
@keras_parameterized.run_all_keras_modes
def test_progbar_logging(self):
model = self._get_model(input_shape=(3,))
x = array_ops.ones((50, 3))
y = array_ops.zeros((50, 2))
dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).batch(10)
expected_log = r'(.*- loss:.*- my_acc:.*)+'
with self.captureWritesToStream(sys.stdout) as printed:
model.fit(dataset, epochs=2, steps_per_epoch=10)
self.assertRegexpMatches(printed.contents(), expected_log)
@keras_parameterized.run_with_all_model_types(exclude_models='functional')
@keras_parameterized.run_all_keras_modes
def test_progbar_logging_deferred_model_build(self):
model = self._get_model()
self.assertFalse(model.built)
x = array_ops.ones((50, 3))
y = array_ops.zeros((50, 2))
dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).batch(10)
expected_log = r'(.*- loss:.*- my_acc:.*)+'
with self.captureWritesToStream(sys.stdout) as printed:
model.fit(dataset, epochs=2, steps_per_epoch=10)
self.assertRegexpMatches(printed.contents(), expected_log)
@keras_parameterized.run_with_all_model_types
def test_ModelCheckpoint(self):
if h5py is None:
return # Skip test if models cannot be saved.
layers = [
keras.layers.Dense(NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'),
keras.layers.Dense(NUM_CLASSES, activation='softmax')
]
model = testing_utils.get_model_from_layers(layers, input_shape=(10,))
model.compile(
loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc'])
temp_dir = self.get_temp_dir()
self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True)
filepath = os.path.join(temp_dir, 'checkpoint')
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
# case 1
monitor = 'val_loss'
save_best_only = False
mode = 'auto'
model = keras.models.Sequential()
model.add(
keras.layers.Dense(
NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'))
model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax'))
model.compile(
loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc'])
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
assert os.path.exists(filepath)
os.remove(filepath)
# case 2
mode = 'min'
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
assert os.path.exists(filepath)
os.remove(filepath)
# case 3
mode = 'max'
monitor = 'val_acc'
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
assert os.path.exists(filepath)
os.remove(filepath)
# case 4
save_best_only = True
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
assert os.path.exists(filepath)
os.remove(filepath)
# Case: metric not available.
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor='unknown',
save_best_only=True)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
# File won't be written.
assert not os.path.exists(filepath)
# case 5
save_best_only = False
period = 2
mode = 'auto'
filepath = os.path.join(temp_dir, 'checkpoint.{epoch:02d}.h5')
cbks = [
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode=mode,
period=period)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=4,
verbose=1)
assert os.path.exists(filepath.format(epoch=2))
assert os.path.exists(filepath.format(epoch=4))
os.remove(filepath.format(epoch=2))
os.remove(filepath.format(epoch=4))
assert not os.path.exists(filepath.format(epoch=1))
assert not os.path.exists(filepath.format(epoch=3))
# Invalid use: this will raise a warning but not an Exception.
keras.callbacks.ModelCheckpoint(
filepath,
monitor=monitor,
save_best_only=save_best_only,
mode='unknown')
def test_EarlyStopping(self):
with self.cached_session():
np.random.seed(123)
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
model = testing_utils.get_small_sequential_mlp(
num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM)
model.compile(
loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc'])
cases = [
('max', 'val_acc'),
('min', 'val_loss'),
('auto', 'val_acc'),
('auto', 'loss'),
('unknown', 'unknown')
]
for mode, monitor in cases:
patience = 0
cbks = [
keras.callbacks.EarlyStopping(
patience=patience, monitor=monitor, mode=mode)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=5,
verbose=0)
def test_EarlyStopping_reuse(self):
with self.cached_session():
np.random.seed(1337)
patience = 3
data = np.random.random((100, 1))
labels = np.where(data > 0.5, 1, 0)
model = keras.models.Sequential((keras.layers.Dense(
1, input_dim=1, activation='relu'), keras.layers.Dense(
1, activation='sigmoid'),))
model.compile(
optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])
weights = model.get_weights()
stopper = keras.callbacks.EarlyStopping(monitor='acc', patience=patience)
hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20)
assert len(hist.epoch) >= patience
# This should allow training to go for at least `patience` epochs
model.set_weights(weights)
hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20)
assert len(hist.epoch) >= patience
def test_EarlyStopping_with_baseline(self):
with self.cached_session():
np.random.seed(1337)
baseline = 0.5
(data, labels), _ = testing_utils.get_test_data(
train_samples=100,
test_samples=50,
input_shape=(1,),
num_classes=NUM_CLASSES)
model = testing_utils.get_small_sequential_mlp(
num_hidden=1, num_classes=1, input_dim=1)
model.compile(
optimizer='sgd', loss='binary_crossentropy', metrics=['acc'])
stopper = keras.callbacks.EarlyStopping(monitor='acc',
baseline=baseline)
hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20)
assert len(hist.epoch) == 1
patience = 3
stopper = keras.callbacks.EarlyStopping(monitor='acc',
patience=patience,
baseline=baseline)
hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20)
assert len(hist.epoch) >= patience
def test_EarlyStopping_final_weights_when_restoring_model_weights(self):
class DummyModel(object):
def __init__(self):
self.stop_training = False
self.weights = -1
def get_weights(self):
return self.weights
def set_weights(self, weights):
self.weights = weights
def set_weight_to_epoch(self, epoch):
self.weights = epoch
early_stop = keras.callbacks.EarlyStopping(monitor='val_loss',
patience=2,
restore_best_weights=True)
early_stop.model = DummyModel()
losses = [0.2, 0.15, 0.1, 0.11, 0.12]
# The best configuration is in the epoch 2 (loss = 0.1000).
epochs_trained = 0
early_stop.on_train_begin()
for epoch in range(len(losses)):
epochs_trained += 1
early_stop.model.set_weight_to_epoch(epoch=epoch)
early_stop.on_epoch_end(epoch, logs={'val_loss': losses[epoch]})
if early_stop.model.stop_training:
break
# The best configuration is in epoch 2 (loss = 0.1000),
# and while patience = 2, we're restoring the best weights,
# so we end up at the epoch with the best weights, i.e. epoch 2
self.assertEqual(early_stop.model.get_weights(), 2)
def test_RemoteMonitor(self):
if requests is None:
return
monitor = keras.callbacks.RemoteMonitor()
# This will raise a warning since the default address in unreachable:
monitor.on_epoch_end(0, logs={'loss': 0.})
def test_LearningRateScheduler(self):
with self.cached_session():
np.random.seed(1337)
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
model = testing_utils.get_small_sequential_mlp(
num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM)
model.compile(
loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
cbks = [keras.callbacks.LearningRateScheduler(lambda x: 1. / (1. + x))]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=5,
verbose=0)
assert (
float(keras.backend.get_value(
model.optimizer.lr)) - 0.2) < keras.backend.epsilon()
cbks = [keras.callbacks.LearningRateScheduler(lambda x, lr: lr / 2)]
model.compile(
loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=2,
verbose=0)
assert (
float(keras.backend.get_value(
model.optimizer.lr)) - 0.01 / 4) < keras.backend.epsilon()
def test_ReduceLROnPlateau(self):
with self.cached_session():
np.random.seed(1337)
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
def make_model():
random_seed.set_random_seed(1234)
np.random.seed(1337)
model = testing_utils.get_small_sequential_mlp(
num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM)
model.compile(
loss='categorical_crossentropy',
optimizer=keras.optimizers.SGD(lr=0.1))
return model
# TODO(psv): Make sure the callback works correctly when min_delta is
# set as 0. Test fails when the order of this callback and assertion is
# interchanged.
model = make_model()
cbks = [
keras.callbacks.ReduceLROnPlateau(
monitor='val_loss',
factor=0.1,
min_delta=0,
patience=1,
cooldown=5)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=5,
verbose=0)
self.assertAllClose(
float(keras.backend.get_value(model.optimizer.lr)), 0.1, atol=1e-4)
model = make_model()
# This should reduce the LR after the first epoch (due to high epsilon).
cbks = [
keras.callbacks.ReduceLROnPlateau(
monitor='val_loss',
factor=0.1,
min_delta=10,
patience=1,
cooldown=5)
]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=5,
verbose=2)
self.assertAllClose(
float(keras.backend.get_value(model.optimizer.lr)), 0.01, atol=1e-4)
def test_ReduceLROnPlateau_patience(self):
class DummyOptimizer(object):
def __init__(self):
self.lr = keras.backend.variable(1.0)
class DummyModel(object):
def __init__(self):
self.optimizer = DummyOptimizer()
reduce_on_plateau = keras.callbacks.ReduceLROnPlateau(
monitor='val_loss', patience=2)
reduce_on_plateau.model = DummyModel()
losses = [0.0860, 0.1096, 0.1040]
lrs = []
for epoch in range(len(losses)):
reduce_on_plateau.on_epoch_end(epoch, logs={'val_loss': losses[epoch]})
lrs.append(keras.backend.get_value(reduce_on_plateau.model.optimizer.lr))
# The learning rates should be 1.0 except the last one
for lr in lrs[:-1]:
self.assertEqual(lr, 1.0)
self.assertLess(lrs[-1], 1.0)
def test_ReduceLROnPlateau_backwards_compatibility(self):
with test.mock.patch.object(logging, 'warning') as mock_log:
reduce_on_plateau = keras.callbacks.ReduceLROnPlateau(epsilon=1e-13)
self.assertRegexpMatches(
str(mock_log.call_args), '`epsilon` argument is deprecated')
self.assertFalse(hasattr(reduce_on_plateau, 'epsilon'))
self.assertTrue(hasattr(reduce_on_plateau, 'min_delta'))
self.assertEqual(reduce_on_plateau.min_delta, 1e-13)
def test_CSVLogger(self):
with self.cached_session():
np.random.seed(1337)
temp_dir = self.get_temp_dir()
self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True)
filepath = os.path.join(temp_dir, 'log.tsv')
sep = '\t'
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
def make_model():
np.random.seed(1337)
model = testing_utils.get_small_sequential_mlp(
num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM)
model.compile(
loss='categorical_crossentropy',
optimizer=keras.optimizers.SGD(lr=0.1),
metrics=['accuracy'])
return model
# case 1, create new file with defined separator
model = make_model()
cbks = [keras.callbacks.CSVLogger(filepath, separator=sep)]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
assert os.path.exists(filepath)
with open(filepath) as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read())
assert dialect.delimiter == sep
del model
del cbks
# case 2, append data to existing file, skip header
model = make_model()
cbks = [keras.callbacks.CSVLogger(filepath, separator=sep, append=True)]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1,
verbose=0)
# case 3, reuse of CSVLogger object
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=2,
verbose=0)
with open(filepath) as csvfile:
list_lines = csvfile.readlines()
for line in list_lines:
assert line.count(sep) == 4
assert len(list_lines) == 5
output = ' '.join(list_lines)
assert len(re.findall('epoch', output)) == 1
os.remove(filepath)
def test_stop_training_csv(self):
# Test that using the CSVLogger callback with the TerminateOnNaN callback
# does not result in invalid CSVs.
np.random.seed(1337)
tmpdir = self.get_temp_dir()
self.addCleanup(shutil.rmtree, tmpdir, ignore_errors=True)
with self.cached_session():
fp = os.path.join(tmpdir, 'test.csv')
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
cbks = [keras.callbacks.TerminateOnNaN(), keras.callbacks.CSVLogger(fp)]
model = keras.models.Sequential()
for _ in range(5):
model.add(keras.layers.Dense(2, input_dim=INPUT_DIM, activation='relu'))
model.add(keras.layers.Dense(NUM_CLASSES, activation='linear'))
model.compile(loss='mean_squared_error',
optimizer='rmsprop')
def data_generator():
i = 0
max_batch_index = len(x_train) // BATCH_SIZE
tot = 0
while 1:
if tot > 3 * len(x_train):
yield (np.ones([BATCH_SIZE, INPUT_DIM]) * np.nan,
np.ones([BATCH_SIZE, NUM_CLASSES]) * np.nan)
else:
yield (x_train[i * BATCH_SIZE: (i + 1) * BATCH_SIZE],
y_train[i * BATCH_SIZE: (i + 1) * BATCH_SIZE])
i += 1
tot += 1
i %= max_batch_index
history = model.fit_generator(data_generator(),
len(x_train) // BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=20)
loss = history.history['loss']
assert len(loss) > 1
assert loss[-1] == np.inf or np.isnan(loss[-1])
values = []
with open(fp) as f:
for x in csv.reader(f):
# In windows, due to \r\n line ends we may end up reading empty lines
# after each line. Skip empty lines.
if x:
values.append(x)
assert 'nan' in values[-1], 'The last epoch was not logged.'
def test_TerminateOnNaN(self):
with self.cached_session():
np.random.seed(1337)
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
cbks = [keras.callbacks.TerminateOnNaN()]
model = keras.models.Sequential()
initializer = keras.initializers.Constant(value=1e5)
for _ in range(5):
model.add(
keras.layers.Dense(
2,
input_dim=INPUT_DIM,
activation='relu',
kernel_initializer=initializer))
model.add(keras.layers.Dense(NUM_CLASSES))
model.compile(loss='mean_squared_error', optimizer='rmsprop')
history = model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=20)
loss = history.history['loss']
self.assertEqual(len(loss), 1)
self.assertEqual(loss[0], np.inf)
@unittest.skipIf(
os.name == 'nt',
'use_multiprocessing=True does not work on windows properly.')
def test_LambdaCallback(self):
with self.cached_session():
np.random.seed(1337)
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.to_categorical(y_test)
y_train = keras.utils.to_categorical(y_train)
model = keras.models.Sequential()
model.add(
keras.layers.Dense(
NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'))
model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax'))
model.compile(
loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
# Start an arbitrary process that should run during model
# training and be terminated after training has completed.
e = threading.Event()
def target():
e.wait()
t = threading.Thread(target=target)
t.start()
cleanup_callback = keras.callbacks.LambdaCallback(
on_train_end=lambda logs: e.set())
cbks = [cleanup_callback]
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=5,
verbose=0)
t.join()
assert not t.is_alive()
def test_RemoteMonitorWithJsonPayload(self):
if requests is None:
self.skipTest('`requests` required to run this test')
with self.cached_session():
(x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(
train_samples=TRAIN_SAMPLES,
test_samples=TEST_SAMPLES,
input_shape=(INPUT_DIM,),
num_classes=NUM_CLASSES)
y_test = keras.utils.np_utils.to_categorical(y_test)
y_train = keras.utils.np_utils.to_categorical(y_train)
model = keras.models.Sequential()
model.add(
keras.layers.Dense(
NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'))
model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax'))
model.compile(
loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
cbks = [keras.callbacks.RemoteMonitor(send_as_json=True)]
with test.mock.patch.object(requests, 'post'):
model.fit(
x_train,
y_train,
batch_size=BATCH_SIZE,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=1)
# A summary that was emitted during a test. Fields:
# logdir: str. The logdir of the FileWriter to which the summary was
# written.
# tag: str. The name of the summary.
_ObservedSummary = collections.namedtuple('_ObservedSummary', ('logdir', 'tag'))
class _MockSummaryFile(object):
"""Record summary tag names and the files to which they're written.
Fields `scalars`, `images`, and `histograms` are sets containing
`_ObservedSummary` values.
"""
def __init__(self):
self.scalars = set()
self.images = set()
self.histograms = set()
@tf_contextlib.contextmanager
def _mock_summary_api():
summary_file = _MockSummaryFile()
# Keep track of the logdir associated with each created writer.
# (There doesn't seem to be an easy way to get this information after
# the fact.)
writer_logdirs = {}
real_create_file_writer = summary_ops_v2.create_file_writer
def mock_create_file_writer(logdir, *args, **kwargs):
writer = real_create_file_writer(logdir, *args, **kwargs)
assert writer is not None
assert writer not in writer_logdirs, (writer, writer_logdirs)
writer_logdirs[writer] = logdir
return writer
def make_mock_summary(summary_set):
def mock_summary(tag, *args, **kwargs):
del args # unused
del kwargs # unused
logdir = writer_logdirs[context.context().summary_writer]
summary_set.add(_ObservedSummary(logdir=logdir, tag=tag))
return mock_summary
patches = {
'create_file_writer': mock_create_file_writer,
'scalar': make_mock_summary(summary_file.scalars),
'histogram': make_mock_summary(summary_file.histograms),
'image': make_mock_summary(summary_file.images),
}
with test.mock.patch.multiple(summary_ops_v2, **patches):
yield summary_file
@keras_parameterized.run_with_all_model_types
@keras_parameterized.run_all_keras_modes(always_skip_v1=True)
class TestTensorBoardV2(keras_parameterized.TestCase):
def setUp(self):
super(TestTensorBoardV2, self).setUp()
self.logdir = os.path.join(self.get_temp_dir(), 'tb')
self.train_dir = os.path.join(self.logdir, 'train')
self.validation_dir = os.path.join(self.logdir, 'validation')
def _get_model(self):
layers = [
keras.layers.Conv2D(8, (3, 3)),
keras.layers.Flatten(),
keras.layers.Dense(1)
]
model = testing_utils.get_model_from_layers(layers, input_shape=(10, 10, 1))
model.compile('sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly())
return model
def test_TensorBoard_basic(self):
model = self._get_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(self.logdir)
with _mock_summary_api() as summary_file:
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
self.assertEqual(
summary_file.scalars, {
_ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),
_ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),
})
def test_TensorBoard_batch_metrics(self):
model = self._get_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(self.logdir, update_freq=1)
with _mock_summary_api() as summary_file:
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
self.assertEqual(
summary_file.scalars,
{
_ObservedSummary(logdir=self.train_dir, tag='batch_loss'),
_ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),
_ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),
},
)
def test_TensorBoard_weight_histograms(self):
model = self._get_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(self.logdir, histogram_freq=1)
with _mock_summary_api() as summary_file:
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
self.assertEqual(
summary_file.scalars,
{
_ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),
_ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),
},
)
self.assertEqual(
self._strip_layer_names(summary_file.histograms),
{
_ObservedSummary(logdir=self.train_dir, tag='bias_0'),
_ObservedSummary(logdir=self.train_dir, tag='kernel_0'),
},
)
def test_TensorBoard_weight_images(self):
model = self._get_model()
x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))
tb_cbk = keras.callbacks.TensorBoard(
self.logdir, histogram_freq=1, write_images=True)
with _mock_summary_api() as summary_file:
model.fit(
x,
y,
batch_size=2,
epochs=2,
validation_data=(x, y),
callbacks=[tb_cbk])
self.assertEqual(
summary_file.scalars,
{
_ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),
_ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),
},
)
self.assertEqual(
self._strip_layer_names(summary_file.histograms),
{
_ObservedSummary(logdir=self.train_dir, tag='bias_0'),
_ObservedSummary(logdir=self.train_dir, tag='kernel_0'),
},
)
self.assertEqual(
self._strip_layer_names(summary_file.images),
{
_ObservedSummary(logdir=self.train_dir, tag='bias_0'),
_ObservedSummary(logdir=self.train_dir, tag='kernel_0'),
},
)
def _strip_layer_names(self, summaries):
"""Deduplicate summary names modulo layer suffix.
Args:
summaries: A `set` of `_ObservedSummary` values.
Returns:
A new `set` of `_ObservedSummary` values with layer suffixes
removed.
"""
return {s._replace(tag=s.tag[s.tag.rfind('/') + 1:]) for s in summaries}
def test_TensorBoard_invalid_argument(self):
with self.assertRaisesRegexp(ValueError, 'Unrecognized arguments'):
keras.callbacks.TensorBoard(wwrite_images=True)
if __name__ == '__main__':
test.main()
|
1.py | import tkinter.ttk as ttk
from tkinter import *
from tkinter import filedialog
from pystray import MenuItem as item
import pystray
from PIL import Image
import tkinter as tk
from multiprocessing import Process
from CheckFilesFrame import DocFree, Create
class Frame():
def __init__(self):
self.image = Image.open("image.jpg")
def kkk(self):
self.menu = pystray.Menu(pystray.MenuItem(("Show"), lambda: self.RunInspection), pystray.MenuItem(("Exit"), lambda: self.exit))
#menu = (item('upload', action), item('exit', exit)) # 아이콘 클릭시 보여줄 값들 (action,exit는 위쪽 함수의 동작을 가져옴)
self.icon = pystray.Icon("name", image, "DocuFree", menu)
th2 = Process(target=self.icon.run())
th2.start()
th2.join()
def exit(self):
self.icon.stop()
def RunInspection(self):
th1 = Process(target = Create)
th1.start()
th1.join()
def action(self): # 화면 다시 켜짐
self.RunInspection()
self.icon.stop()
# 같은 폴터 안에 image.jpg파일이 있어야함
A = Frame()
A.kkk()
|
custom.py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=too-few-public-methods,no-self-use,too-many-locals,line-too-long,unused-argument
import errno
try:
import msvcrt
except ImportError:
# Not supported for Linux machines.
pass
import platform
import select
import shlex
import signal
import sys
import threading
import time
try:
import termios
import tty
except ImportError:
# Not supported for Windows machines.
pass
import websocket
import yaml
from knack.log import get_logger
from knack.prompting import prompt_pass, prompt, NoTTYException
from knack.util import CLIError
from azure.mgmt.containerinstance.models import (AzureFileVolume, Container, ContainerGroup, ContainerGroupNetworkProtocol,
ContainerPort, ImageRegistryCredential, IpAddress, Port, ResourceRequests,
ResourceRequirements, Volume, VolumeMount, ContainerExecRequestTerminalSize,
GitRepoVolume, LogAnalytics, ContainerGroupDiagnostics, ContainerGroupNetworkProfile,
ContainerGroupIpAddressType, ResourceIdentityType, ContainerGroupIdentity)
from azure.cli.core.util import sdk_no_wait
from ._client_factory import (cf_container_groups, cf_container, cf_log_analytics, cf_resource, cf_network)
logger = get_logger(__name__)
WINDOWS_NAME = 'Windows'
SERVER_DELIMITER = '.'
ACR_SERVER_DELIMITER = '.azurecr.io'
AZURE_FILE_VOLUME_NAME = 'azurefile'
SECRETS_VOLUME_NAME = 'secrets'
GITREPO_VOLUME_NAME = 'gitrepo'
MSI_LOCAL_ID = '[system]'
def list_containers(client, resource_group_name=None):
"""List all container groups in a resource group. """
if resource_group_name is None:
return client.list()
return client.list_by_resource_group(resource_group_name)
def get_container(client, resource_group_name, name):
"""Show details of a container group. """
return client.get(resource_group_name, name)
def delete_container(client, resource_group_name, name, **kwargs):
"""Delete a container group. """
return client.delete(resource_group_name, name)
# pylint: disable=too-many-statements
def create_container(cmd,
resource_group_name,
name=None,
image=None,
location=None,
cpu=1,
memory=1.5,
restart_policy='Always',
ports=None,
protocol=None,
os_type='Linux',
ip_address=None,
dns_name_label=None,
command_line=None,
environment_variables=None,
secure_environment_variables=None,
registry_login_server=None,
registry_username=None,
registry_password=None,
azure_file_volume_share_name=None,
azure_file_volume_account_name=None,
azure_file_volume_account_key=None,
azure_file_volume_mount_path=None,
log_analytics_workspace=None,
log_analytics_workspace_key=None,
vnet=None,
vnet_name=None,
vnet_address_prefix='10.0.0.0/16',
subnet=None,
subnet_address_prefix='10.0.0.0/24',
network_profile=None,
gitrepo_url=None,
gitrepo_dir='.',
gitrepo_revision=None,
gitrepo_mount_path=None,
secrets=None,
secrets_mount_path=None,
file=None,
assign_identity=None,
identity_scope=None,
identity_role='Contributor',
no_wait=False):
"""Create a container group. """
if file:
return _create_update_from_file(cmd.cli_ctx, resource_group_name, name, location, file, no_wait)
if not name:
raise CLIError("error: the --name/-n argument is required unless specified with a passed in file.")
if not image:
raise CLIError("error: the --image argument is required unless specified with a passed in file.")
ports = ports or [80]
protocol = protocol or ContainerGroupNetworkProtocol.tcp
container_resource_requirements = _create_resource_requirements(cpu=cpu, memory=memory)
image_registry_credentials = _create_image_registry_credentials(registry_login_server=registry_login_server,
registry_username=registry_username,
registry_password=registry_password,
image=image)
command = shlex.split(command_line) if command_line else None
volumes = []
mounts = []
azure_file_volume = _create_azure_file_volume(azure_file_volume_share_name=azure_file_volume_share_name,
azure_file_volume_account_name=azure_file_volume_account_name,
azure_file_volume_account_key=azure_file_volume_account_key)
azure_file_volume_mount = _create_azure_file_volume_mount(azure_file_volume=azure_file_volume,
azure_file_volume_mount_path=azure_file_volume_mount_path)
if azure_file_volume:
volumes.append(azure_file_volume)
mounts.append(azure_file_volume_mount)
secrets_volume = _create_secrets_volume(secrets)
secrets_volume_mount = _create_secrets_volume_mount(secrets_volume=secrets_volume,
secrets_mount_path=secrets_mount_path)
if secrets_volume:
volumes.append(secrets_volume)
mounts.append(secrets_volume_mount)
diagnostics = None
tags = {}
if log_analytics_workspace and log_analytics_workspace_key:
log_analytics = LogAnalytics(
workspace_id=log_analytics_workspace, workspace_key=log_analytics_workspace_key)
diagnostics = ContainerGroupDiagnostics(
log_analytics=log_analytics
)
elif log_analytics_workspace and not log_analytics_workspace_key:
diagnostics, tags = _get_diagnostics_from_workspace(
cmd.cli_ctx, log_analytics_workspace)
if not diagnostics:
raise CLIError('Log Analytics workspace "' + log_analytics_workspace + '" not found.')
elif not log_analytics_workspace and log_analytics_workspace_key:
raise CLIError('"--log-analytics-workspace-key" requires "--log-analytics-workspace".')
gitrepo_volume = _create_gitrepo_volume(gitrepo_url=gitrepo_url, gitrepo_dir=gitrepo_dir, gitrepo_revision=gitrepo_revision)
gitrepo_volume_mount = _create_gitrepo_volume_mount(gitrepo_volume=gitrepo_volume, gitrepo_mount_path=gitrepo_mount_path)
if gitrepo_volume:
volumes.append(gitrepo_volume)
mounts.append(gitrepo_volume_mount)
# Concatenate secure and standard environment variables
if environment_variables and secure_environment_variables:
environment_variables = environment_variables + secure_environment_variables
else:
environment_variables = environment_variables or secure_environment_variables
identity = None
if assign_identity is not None:
identity = _build_identities_info(assign_identity)
# Set up VNET, subnet and network profile if needed
if subnet and not network_profile:
network_profile = _get_vnet_network_profile(cmd, location, resource_group_name, vnet, vnet_address_prefix, subnet, subnet_address_prefix)
cg_network_profile = None
if network_profile:
cg_network_profile = ContainerGroupNetworkProfile(id=network_profile)
cgroup_ip_address = _create_ip_address(ip_address, ports, protocol, dns_name_label, network_profile)
container = Container(name=name,
image=image,
resources=container_resource_requirements,
command=command,
ports=[ContainerPort(
port=p, protocol=protocol) for p in ports] if cgroup_ip_address else None,
environment_variables=environment_variables,
volume_mounts=mounts or None)
cgroup = ContainerGroup(location=location,
identity=identity,
containers=[container],
os_type=os_type,
restart_policy=restart_policy,
ip_address=cgroup_ip_address,
image_registry_credentials=image_registry_credentials,
volumes=volumes or None,
network_profile=cg_network_profile,
diagnostics=diagnostics,
tags=tags)
container_group_client = cf_container_groups(cmd.cli_ctx)
lro = sdk_no_wait(no_wait, container_group_client.create_or_update, resource_group_name,
name, cgroup)
if assign_identity is not None and identity_scope:
from azure.cli.core.commands.arm import assign_identity
cg = container_group_client.get(resource_group_name, name)
assign_identity(cmd.cli_ctx, lambda: cg, lambda cg: cg, identity_role, identity_scope)
return lro
def _build_identities_info(identities):
identities = identities or []
identity_type = ResourceIdentityType.none
if not identities or MSI_LOCAL_ID in identities:
identity_type = ResourceIdentityType.system_assigned
external_identities = [x for x in identities if x != MSI_LOCAL_ID]
if external_identities and identity_type == ResourceIdentityType.system_assigned:
identity_type = ResourceIdentityType.system_assigned_user_assigned
elif external_identities:
identity_type = ResourceIdentityType.user_assigned
identity = ContainerGroupIdentity(type=identity_type)
if external_identities:
identity.user_assigned_identities = {e: {} for e in external_identities}
return identity
def _get_resource(client, resource_group_name, *subresources):
from msrestazure.azure_exceptions import CloudError
try:
resource = client.get(resource_group_name, *subresources)
return resource
except CloudError as ex:
if ex.error.error == "NotFound" or ex.error.error == "ResourceNotFound":
return None
raise
def _get_vnet_network_profile(cmd, location, resource_group_name, vnet, vnet_address_prefix, subnet, subnet_address_prefix):
from azure.cli.core.profiles import ResourceType
from msrestazure.tools import parse_resource_id, is_valid_resource_id
aci_delegation_service_name = "Microsoft.ContainerInstance/containerGroups"
Delegation = cmd.get_models('Delegation', resource_type=ResourceType.MGMT_NETWORK)
aci_delegation = Delegation(
name=aci_delegation_service_name,
service_name=aci_delegation_service_name
)
ncf = cf_network(cmd.cli_ctx)
vnet_name = vnet
subnet_name = subnet
if is_valid_resource_id(subnet):
parsed_subnet_id = parse_resource_id(subnet)
subnet_name = parsed_subnet_id['resource_name']
vnet_name = parsed_subnet_id['name']
resource_group_name = parsed_subnet_id['resource_group']
elif is_valid_resource_id(vnet):
parsed_vnet_id = parse_resource_id(vnet)
vnet_name = parsed_vnet_id['resource_name']
resource_group_name = parsed_vnet_id['resource_group']
default_network_profile_name = "aci-network-profile-{}-{}".format(vnet_name, subnet_name)
subnet = _get_resource(ncf.subnets, resource_group_name, vnet_name, subnet_name)
# For an existing subnet, validate and add delegation if needed
if subnet:
logger.info('Using existing subnet "%s" in resource group "%s"', subnet.name, resource_group_name)
for sal in (subnet.service_association_links or []):
if sal.linked_resource_type != aci_delegation_service_name:
raise CLIError("Can not use subnet with existing service association links other than {}.".format(aci_delegation_service_name))
if not subnet.delegations:
logger.info('Adding ACI delegation to the existing subnet.')
subnet.delegations = [aci_delegation]
subnet = ncf.subnets.create_or_update(resource_group_name, vnet_name, subnet_name, subnet).result()
else:
for delegation in subnet.delegations:
if delegation.service_name != aci_delegation_service_name:
raise CLIError("Can not use subnet with existing delegations other than {}".format(aci_delegation_service_name))
network_profile = _get_resource(ncf.network_profiles, resource_group_name, default_network_profile_name)
if network_profile:
logger.info('Using existing network profile "%s"', default_network_profile_name)
return network_profile.id
# Create new subnet and Vnet if not exists
else:
Subnet, VirtualNetwork, AddressSpace = cmd.get_models('Subnet', 'VirtualNetwork',
'AddressSpace', resource_type=ResourceType.MGMT_NETWORK)
vnet = _get_resource(ncf.virtual_networks, resource_group_name, vnet_name)
if not vnet:
logger.info('Creating new vnet "%s" in resource group "%s"', vnet_name, resource_group_name)
ncf.virtual_networks.create_or_update(resource_group_name,
vnet_name,
VirtualNetwork(name=vnet_name,
location=location,
address_space=AddressSpace(address_prefixes=[vnet_address_prefix])))
subnet = Subnet(
name=subnet_name,
location=location,
address_prefix=subnet_address_prefix,
delegations=[aci_delegation])
logger.info('Creating new subnet "%s" in resource group "%s"', subnet_name, resource_group_name)
subnet = ncf.subnets.create_or_update(resource_group_name, vnet_name, subnet_name, subnet).result()
NetworkProfile, ContainerNetworkInterfaceConfiguration, IPConfigurationProfile = cmd.get_models('NetworkProfile',
'ContainerNetworkInterfaceConfiguration',
'IPConfigurationProfile',
resource_type=ResourceType.MGMT_NETWORK)
# In all cases, create the network profile with aci NIC
network_profile = NetworkProfile(
name=default_network_profile_name,
location=location,
container_network_interface_configurations=[ContainerNetworkInterfaceConfiguration(
name="eth0",
ip_configurations=[IPConfigurationProfile(
name="ipconfigprofile",
subnet=subnet
)]
)]
)
logger.info('Creating network profile "%s" in resource group "%s"', default_network_profile_name, resource_group_name)
network_profile = ncf.network_profiles.create_or_update(resource_group_name, default_network_profile_name, network_profile).result()
return network_profile.id
def _get_diagnostics_from_workspace(cli_ctx, log_analytics_workspace):
from msrestazure.tools import parse_resource_id
log_analytics_client = cf_log_analytics(cli_ctx)
for workspace in log_analytics_client.list():
if log_analytics_workspace in (workspace.name, workspace.customer_id):
keys = log_analytics_client.get_shared_keys(
parse_resource_id(workspace.id)['resource_group'], workspace.name)
log_analytics = LogAnalytics(
workspace_id=workspace.customer_id, workspace_key=keys.primary_shared_key)
diagnostics = ContainerGroupDiagnostics(
log_analytics=log_analytics)
return (diagnostics, {'oms-resource-link': workspace.id})
return None, {}
def _create_update_from_file(cli_ctx, resource_group_name, name, location, file, no_wait):
resource_client = cf_resource(cli_ctx)
container_group_client = cf_container_groups(cli_ctx)
cg_defintion = None
try:
with open(file, 'r') as f:
cg_defintion = yaml.safe_load(f)
except OSError: # FileNotFoundError introduced in Python 3
raise CLIError("No such file or directory: " + file)
except yaml.YAMLError as e:
raise CLIError("Error while parsing yaml file:\n\n" + str(e))
# Validate names match if both are provided
if name and cg_defintion.get('name', None):
if name != cg_defintion.get('name', None):
raise CLIError("The name parameter and name from yaml definition must match.")
else:
# Validate at least one name is provided
name = name or cg_defintion.get('name', None)
if cg_defintion.get('name', None) is None and not name:
raise CLIError("The name of the container group is required")
cg_defintion['name'] = name
location = location or cg_defintion.get('location', None)
if not location:
location = resource_client.resource_groups.get(resource_group_name).location
cg_defintion['location'] = location
api_version = cg_defintion.get('apiVersion', None) or container_group_client.api_version
return sdk_no_wait(no_wait,
resource_client.resources.create_or_update,
resource_group_name,
"Microsoft.ContainerInstance",
'',
"containerGroups",
name,
api_version,
cg_defintion)
# pylint: disable=inconsistent-return-statements
def _create_resource_requirements(cpu, memory):
"""Create resource requirements. """
if cpu or memory:
container_resource_requests = ResourceRequests(memory_in_gb=memory, cpu=cpu)
return ResourceRequirements(requests=container_resource_requests)
def _create_image_registry_credentials(registry_login_server, registry_username, registry_password, image):
"""Create image registry credentials. """
image_registry_credentials = None
if registry_login_server:
if not registry_username:
raise CLIError('Please specify --registry-username in order to use custom image registry.')
if not registry_password:
try:
registry_password = prompt_pass(msg='Image registry password: ')
except NoTTYException:
raise CLIError('Please specify --registry-password in order to use custom image registry.')
image_registry_credentials = [ImageRegistryCredential(server=registry_login_server,
username=registry_username,
password=registry_password)]
elif ACR_SERVER_DELIMITER in image.split("/")[0]:
if not registry_username:
try:
registry_username = prompt(msg='Image registry username: ')
except NoTTYException:
raise CLIError('Please specify --registry-username in order to use Azure Container Registry.')
if not registry_password:
try:
registry_password = prompt_pass(msg='Image registry password: ')
except NoTTYException:
raise CLIError('Please specify --registry-password in order to use Azure Container Registry.')
acr_server = image.split("/")[0] if image.split("/") else None
if acr_server:
image_registry_credentials = [ImageRegistryCredential(server=acr_server,
username=registry_username,
password=registry_password)]
elif registry_username and registry_password and SERVER_DELIMITER in image.split("/")[0]:
login_server = image.split("/")[0] if image.split("/") else None
if login_server:
image_registry_credentials = [ImageRegistryCredential(server=login_server,
username=registry_username,
password=registry_password)]
else:
raise CLIError('Failed to parse login server from image name; please explicitly specify --registry-server.')
return image_registry_credentials
def _create_azure_file_volume(azure_file_volume_share_name, azure_file_volume_account_name, azure_file_volume_account_key):
"""Create Azure File volume. """
azure_file_volume = None
if azure_file_volume_share_name:
if not azure_file_volume_account_name:
raise CLIError('Please specify --azure-file-volume-account-name in order to use Azure File volume.')
if not azure_file_volume_account_key:
try:
azure_file_volume_account_key = prompt_pass(msg='Azure File storage account key: ')
except NoTTYException:
raise CLIError('Please specify --azure-file-volume-account-key in order to use Azure File volume.')
azure_file_volume = AzureFileVolume(share_name=azure_file_volume_share_name,
storage_account_name=azure_file_volume_account_name,
storage_account_key=azure_file_volume_account_key)
return Volume(name=AZURE_FILE_VOLUME_NAME, azure_file=azure_file_volume) if azure_file_volume else None
def _create_secrets_volume(secrets):
"""Create secrets volume. """
return Volume(name=SECRETS_VOLUME_NAME, secret=secrets) if secrets else None
def _create_gitrepo_volume(gitrepo_url, gitrepo_dir, gitrepo_revision):
"""Create Git Repo volume. """
gitrepo_volume = GitRepoVolume(repository=gitrepo_url, directory=gitrepo_dir, revision=gitrepo_revision)
return Volume(name=GITREPO_VOLUME_NAME, git_repo=gitrepo_volume) if gitrepo_url else None
# pylint: disable=inconsistent-return-statements
def _create_azure_file_volume_mount(azure_file_volume, azure_file_volume_mount_path):
"""Create Azure File volume mount. """
if azure_file_volume_mount_path:
if not azure_file_volume:
raise CLIError('Please specify --azure-file-volume-share-name --azure-file-volume-account-name --azure-file-volume-account-key '
'to enable Azure File volume mount.')
return VolumeMount(name=AZURE_FILE_VOLUME_NAME, mount_path=azure_file_volume_mount_path)
def _create_secrets_volume_mount(secrets_volume, secrets_mount_path):
"""Create secrets volume mount. """
if secrets_volume:
if not secrets_mount_path:
raise CLIError('Please specify --secrets --secrets-mount-path '
'to enable secrets volume mount.')
return VolumeMount(name=SECRETS_VOLUME_NAME, mount_path=secrets_mount_path)
def _create_gitrepo_volume_mount(gitrepo_volume, gitrepo_mount_path):
"""Create Git Repo volume mount. """
if gitrepo_mount_path:
if not gitrepo_volume:
raise CLIError('Please specify --gitrepo-url (--gitrepo-dir --gitrepo-revision) '
'to enable Git Repo volume mount.')
return VolumeMount(name=GITREPO_VOLUME_NAME, mount_path=gitrepo_mount_path)
# pylint: disable=inconsistent-return-statements
def _create_ip_address(ip_address, ports, protocol, dns_name_label, network_profile):
"""Create IP address. """
if (ip_address and ip_address.lower() == 'public') or dns_name_label:
return IpAddress(ports=[Port(protocol=protocol, port=p) for p in ports],
dns_name_label=dns_name_label, type=ContainerGroupIpAddressType.public)
if network_profile:
return IpAddress(ports=[Port(protocol=protocol, port=p) for p in ports],
type=ContainerGroupIpAddressType.private)
# pylint: disable=inconsistent-return-statements
def container_logs(cmd, resource_group_name, name, container_name=None, follow=False):
"""Tail a container instance log. """
container_client = cf_container(cmd.cli_ctx)
container_group_client = cf_container_groups(cmd.cli_ctx)
container_group = container_group_client.get(resource_group_name, name)
# If container name is not present, use the first container.
if container_name is None:
container_name = container_group.containers[0].name
if not follow:
log = container_client.list_logs(resource_group_name, name, container_name)
print(log.content)
else:
_start_streaming(
terminate_condition=_is_container_terminated,
terminate_condition_args=(container_group_client, resource_group_name, name, container_name),
shupdown_grace_period=5,
stream_target=_stream_logs,
stream_args=(container_client, resource_group_name, name, container_name, container_group.restart_policy))
def container_export(cmd, resource_group_name, name, file):
resource_client = cf_resource(cmd.cli_ctx)
container_group_client = cf_container_groups(cmd.cli_ctx)
resource = resource_client.resources.get(resource_group_name,
"Microsoft.ContainerInstance",
'',
"containerGroups",
name,
container_group_client.api_version,
False).__dict__
# Remove unwanted properites
resource['properties'].pop('instanceView', None)
resource.pop('sku', None)
resource.pop('id', None)
resource.pop('plan', None)
resource.pop('kind', None)
resource.pop('managed_by', None)
resource['properties'].pop('provisioningState', None)
# Correctly export the identity
try:
identity = resource['identity'].type
if identity != ResourceIdentityType.none:
resource['identity'] = resource['identity'].__dict__
identity_entry = {'type': resource['identity']['type'].value}
if resource['identity']['user_assigned_identities']:
identity_entry['user_assigned_identities'] = {k: {} for k in resource['identity']['user_assigned_identities']}
resource['identity'] = identity_entry
except (KeyError, AttributeError):
resource.pop('indentity', None)
# Remove container instance views
for i in range(len(resource['properties']['containers'])):
resource['properties']['containers'][i]['properties'].pop('instanceView', None)
# Add the api version
resource['apiVersion'] = container_group_client.api_version
with open(file, 'w+') as f:
yaml.safe_dump(resource, f, default_flow_style=False)
def container_exec(cmd, resource_group_name, name, exec_command, container_name=None, terminal_row_size=20, terminal_col_size=80):
"""Start exec for a container. """
container_client = cf_container(cmd.cli_ctx)
container_group_client = cf_container_groups(cmd.cli_ctx)
container_group = container_group_client.get(resource_group_name, name)
if container_name or container_name is None and len(container_group.containers) == 1:
# If only one container in container group, use that container.
if container_name is None:
container_name = container_group.containers[0].name
terminal_size = ContainerExecRequestTerminalSize(rows=terminal_row_size, cols=terminal_col_size)
execContainerResponse = container_client.execute_command(resource_group_name, name, container_name, exec_command, terminal_size)
if platform.system() is WINDOWS_NAME:
_start_exec_pipe_win(execContainerResponse.web_socket_uri, execContainerResponse.password)
else:
_start_exec_pipe(execContainerResponse.web_socket_uri, execContainerResponse.password)
else:
raise CLIError('--container-name required when container group has more than one container.')
def _start_exec_pipe_win(web_socket_uri, password):
def _on_ws_open(ws):
ws.send(password)
t = threading.Thread(target=_capture_stdin, args=[ws])
t.daemon = True
t.start()
ws = websocket.WebSocketApp(web_socket_uri, on_open=_on_ws_open, on_message=_on_ws_msg)
ws.run_forever()
def _on_ws_msg(ws, msg):
sys.stdout.write(msg)
sys.stdout.flush()
def _capture_stdin(ws):
while True:
if msvcrt.kbhit:
x = msvcrt.getch()
ws.send(x)
def _start_exec_pipe(web_socket_uri, password):
ws = websocket.create_connection(web_socket_uri)
oldtty = termios.tcgetattr(sys.stdin)
old_handler = signal.getsignal(signal.SIGWINCH)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
ws.send(password)
while True:
try:
if not _cycle_exec_pipe(ws):
break
except (select.error, IOError) as e:
if e.args and e.args[0] == errno.EINTR:
pass
else:
raise
except websocket.WebSocketException:
pass
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
signal.signal(signal.SIGWINCH, old_handler)
def _cycle_exec_pipe(ws):
r, _, _ = select.select([ws.sock, sys.stdin], [], [])
if ws.sock in r:
data = ws.recv()
if not data:
return False
sys.stdout.write(data)
sys.stdout.flush()
if sys.stdin in r:
x = sys.stdin.read(1)
if not x:
return True
ws.send(x)
return True
def attach_to_container(cmd, resource_group_name, name, container_name=None):
"""Attach to a container. """
container_client = cf_container(cmd.cli_ctx)
container_group_client = cf_container_groups(cmd.cli_ctx)
container_group = container_group_client.get(resource_group_name, name)
# If container name is not present, use the first container.
if container_name is None:
container_name = container_group.containers[0].name
_start_streaming(
terminate_condition=_is_container_terminated,
terminate_condition_args=(container_group_client, resource_group_name, name, container_name),
shupdown_grace_period=5,
stream_target=_stream_container_events_and_logs,
stream_args=(container_group_client, container_client, resource_group_name, name, container_name))
def _start_streaming(terminate_condition, terminate_condition_args, shupdown_grace_period, stream_target, stream_args):
"""Start streaming for the stream target. """
import colorama
colorama.init()
try:
t = threading.Thread(target=stream_target, args=stream_args)
t.daemon = True
t.start()
while not terminate_condition(*terminate_condition_args) and t.is_alive():
time.sleep(10)
time.sleep(shupdown_grace_period)
finally:
colorama.deinit()
def _stream_logs(client, resource_group_name, name, container_name, restart_policy):
"""Stream logs for a container. """
lastOutputLines = 0
while True:
log = client.list_logs(resource_group_name, name, container_name)
lines = log.content.split('\n')
currentOutputLines = len(lines)
# Should only happen when the container restarts.
if currentOutputLines < lastOutputLines and restart_policy != 'Never':
print("Warning: you're having '--restart-policy={}'; the container '{}' was just restarted; the tail of the current log might be missing. Exiting...".format(restart_policy, container_name))
break
_move_console_cursor_up(lastOutputLines)
print(log.content)
lastOutputLines = currentOutputLines
time.sleep(2)
def _stream_container_events_and_logs(container_group_client, container_client, resource_group_name, name, container_name):
"""Stream container events and logs. """
lastOutputLines = 0
lastContainerState = None
while True:
container_group, container = _find_container(container_group_client, resource_group_name, name, container_name)
container_state = 'Unknown'
if container.instance_view and container.instance_view.current_state and container.instance_view.current_state.state:
container_state = container.instance_view.current_state.state
_move_console_cursor_up(lastOutputLines)
if container_state != lastContainerState:
print("Container '{}' is in state '{}'...".format(container_name, container_state))
currentOutputLines = 0
if container.instance_view and container.instance_view.events:
for event in sorted(container.instance_view.events, key=lambda e: e.last_timestamp):
print('(count: {}) (last timestamp: {}) {}'.format(event.count, event.last_timestamp, event.message))
currentOutputLines += 1
lastOutputLines = currentOutputLines
lastContainerState = container_state
if container_state == 'Running':
print('\nStart streaming logs:')
break
time.sleep(2)
_stream_logs(container_client, resource_group_name, name, container_name, container_group.restart_policy)
def _is_container_terminated(client, resource_group_name, name, container_name):
"""Check if a container should be considered terminated. """
container_group, container = _find_container(client, resource_group_name, name, container_name)
# If a container group is terminated, assume the container is also terminated.
if container_group.instance_view and container_group.instance_view.state:
if container_group.instance_view.state == 'Succeeded' or container_group.instance_view.state == 'Failed':
return True
# If the restart policy is Always, assume the container will be restarted.
if container_group.restart_policy:
if container_group.restart_policy == 'Always':
return False
# Only assume the container is terminated if its state is Terminated.
if container.instance_view and container.instance_view.current_state and container.instance_view.current_state.state == 'Terminated':
return True
return False
def _find_container(client, resource_group_name, name, container_name):
"""Find a container in a container group. """
container_group = client.get(resource_group_name, name)
containers = [c for c in container_group.containers if c.name == container_name]
if len(containers) != 1:
raise CLIError("Found 0 or more than 1 container with name '{}'".format(container_name))
return container_group, containers[0]
def _move_console_cursor_up(lines):
"""Move console cursor up. """
if lines > 0:
# Use stdout.write to support Python 2
sys.stdout.write('\033[{}A\033[K\033[J'.format(lines))
def _gen_guid():
import uuid
return uuid.uuid4()
|
client.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 15 12:36:25 2019
@author: liuhaowen
"""
import socket
import threading
import json # json.dumps(some)打包 json.loads(some)解包
import tkinter
import tkinter.messagebox
from tkinter.scrolledtext import ScrolledText # 导入多行文本框用到的包
import time
import requests
from tkinter import filedialog
import os
import sys
from time import sleep
import pyscreenshot as ImageGrab
from tkinter import messagebox
IP = ''
PORT = ''
user = ''
listbox1 = '' # 用于显示在线用户的列表框
ii = 0 # 用于判断是开还是关闭列表框
users = [] # 在线用户列表
chat = '------Group chat-------' # 聊天对象, 默认为群聊
# 登陆窗口
root1 = tkinter.Tk()
root1.title('Log in')
root1['height'] = 110
root1['width'] = 270
root1.resizable(0, 0) # 限制窗口大小
IP1 = tkinter.StringVar()
IP1.set('127.0.0.1:50007') # 默认显示的ip和端口
User = tkinter.StringVar()
User.set('')
# 服务器标签
labelIP = tkinter.Label(root1, text='Server address')
labelIP.place(x=20, y=10, width=100, height=20)
entryIP = tkinter.Entry(root1, width=80, textvariable=IP1)
entryIP.place(x=120, y=10, width=130, height=20)
# 用户名标签
labelUser = tkinter.Label(root1, text='Username')
labelUser.place(x=30, y=40, width=80, height=20)
entryUser = tkinter.Entry(root1, width=80, textvariable=User)
entryUser.place(x=120, y=40, width=130, height=20)
# 登录按钮
def login(*args):
global IP, PORT, user
IP, PORT = entryIP.get().split(':') # 获取IP和端口号
PORT = int(PORT) # 端口号需要为int类型
user = entryUser.get()
if not user:
tkinter.messagebox.showerror('Name type error', message='Username Empty!')
else:
root1.destroy() # 关闭窗口
root1.bind('<Return>', login) # 回车绑定登录功能
but = tkinter.Button(root1, text='Log in', command=login)
but.place(x=100, y=70, width=70, height=30)
root1.mainloop()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
if user:
s.send(user.encode()) # 发送用户名
else:
s.send('no'.encode()) # 没有输入用户名则标记no
# 如果没有用户名则将ip和端口号设置为用户名
addr = s.getsockname() # 获取客户端ip和端口号
addr = addr[0] + ':' + str(addr[1])
if user == '':
user = addr
# 聊天窗口
# 创建图形界面
root = tkinter.Tk()
root.title(user) # 窗口命名为用户名
root['height'] = 400
root['width'] = 580
root.resizable(0, 0) # 限制窗口大小
# 创建多行文本框
listbox = ScrolledText(root)
listbox.place(x=5, y=0, width=570, height=320)
# 文本框使用的字体颜色
listbox.tag_config('red', foreground='red')
listbox.tag_config('blue', foreground='blue')
listbox.tag_config('green', foreground='green')
listbox.tag_config('pink', foreground='pink')
listbox.insert(tkinter.END, 'Welcome to the chat room!', 'blue')
# 表情功能代码部分
# 四个按钮, 使用全局变量, 方便创建和销毁
b1 = ''
b2 = ''
b3 = ''
b4 = ''
# 将图片打开存入变量中
p1 = tkinter.PhotoImage(file='./emoji/facepalm.png')
p2 = tkinter.PhotoImage(file='./emoji/smirk.png')
p3 = tkinter.PhotoImage(file='./emoji/concerned.png')
p4 = tkinter.PhotoImage(file='./emoji/smart.png')
# 用字典将标记与表情图片一一对应, 用于后面接收标记判断表情贴图
dic = {'aa**': p1, 'bb**': p2, 'cc**': p3, 'dd**': p4}
ee = 0 # 判断表情面板开关的标志
# 发送表情图标记的函数, 在按钮点击事件中调用
def mark(exp): # 参数是发的表情图标记, 发送后将按钮销毁
global ee
mes = exp + ':;' + user + ':;' + chat
s.send(mes.encode())
b1.destroy()
b2.destroy()
b3.destroy()
b4.destroy()
ee = 0
# 四个对应的函数
def bb1():
mark('aa**')
def bb2():
mark('bb**')
def bb3():
mark('cc**')
def bb4():
mark('dd**')
def express():
global b1, b2, b3, b4, ee
if ee == 0:
ee = 1
b1 = tkinter.Button(root, command=bb1, image=p1,
relief=tkinter.FLAT, bd=0)
b2 = tkinter.Button(root, command=bb2, image=p2,
relief=tkinter.FLAT, bd=0)
b3 = tkinter.Button(root, command=bb3, image=p3,
relief=tkinter.FLAT, bd=0)
b4 = tkinter.Button(root, command=bb4, image=p4,
relief=tkinter.FLAT, bd=0)
b1.place(x=5, y=248)
b2.place(x=75, y=248)
b3.place(x=145, y=248)
b4.place(x=215, y=248)
else:
ee = 0
b1.destroy()
b2.destroy()
b3.destroy()
b4.destroy()
# 创建表情按钮
eBut = tkinter.Button(root, text='emoji', command=express)
eBut.place(x=5, y=320, width=60, height=30)
# 开始截图
def buttonCaptureClick():
filename = 'temp.png'
# grab()方法默认对全屏幕进行截图
im = ImageGrab.grab()
im.save(filename)
im.close()
# 创建截屏按钮
sBut = tkinter.Button(root, text='Capture', command=buttonCaptureClick)
sBut.place(x=95, y=320, width=60, height=30)
# 文件功能代码部分
# 将在文件功能窗口用到的组件名都列出来, 方便重新打开时会对面板进行更新
list2 = '' # 列表框
label = '' # 显示路径的标签
upload = '' # 上传按钮
close = '' # 关闭按钮
def fileClient():
PORT2 = PORT + 1 # 聊天室的端口为chatport+1
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT2))
# 修改root窗口大小显示文件管理的组件
root['height'] = 390
root['width'] = 760
# 创建列表框
list2 = tkinter.Listbox(root)
list2.place(x=580, y=25, width=175, height=325)
# 将接收到的目录文件列表打印出来(dir), 显示在列表框中, 在pwd函数中调用
def recvList(enter, lu):
s.send(enter.encode())
data = s.recv(4096)
data = json.loads(data.decode())
list2.delete(0, tkinter.END) # 清空列表框
lu = lu.split('\\')
if len(lu) != 1:
list2.insert(tkinter.END, 'Return to the previous dir')
list2.itemconfig(0, fg='green')
for i in range(len(data)):
list2.insert(tkinter.END, ('' + data[i]))
if '.' not in data[i]:
list2.itemconfig(tkinter.END, fg='orange')
else:
list2.itemconfig(tkinter.END, fg='blue')
# 创建标签显示服务端工作目录
def lab():
global label
data = s.recv(1024) # 接收目录
lu = data.decode()
try:
label.destroy()
label = tkinter.Label(root, text=lu)
label.place(x=580, y=0, )
except:
label = tkinter.Label(root, text=lu)
label.place(x=580, y=0, )
recvList('dir', lu)
# 进入指定目录(cd)
def cd(message):
s.send(message.encode())
# 刚连接上服务端时进行一次面板刷新
cd('cd same')
lab()
# 接收下载文件(get)
def get(message):
# print(message)
name = message.split(' ')
# print(name)
name = name[1] # 获取命令的第二个参数(文件名)
# 选择对话框, 选择文件的保存路径
fileName = tkinter.filedialog.asksaveasfilename(title='Save file to', initialfile=name)
# 如果文件名非空才进行下载
if fileName:
s.send(message.encode())
with open(fileName, 'wb') as f:
while True:
data = s.recv(1024)
if data == 'EOF'.encode():
tkinter.messagebox.showinfo(title='Message',
message='Download completed!')
break
f.write(data)
# 创建用于绑定在列表框上的函数
def run(*args):
indexs = list2.curselection()
index = indexs[0]
content = list2.get(index)
# 如果有一个 . 则为文件
if '.' in content:
content = 'get ' + content
get(content)
cd('cd same')
elif content == 'Return to the previous dir':
content = 'cd ..'
cd(content)
else:
content = 'cd ' + content
cd(content)
lab() # 刷新显示页面
# 在列表框上设置绑定事件
list2.bind('<ButtonRelease-1>', run)
# 上传客户端所在文件夹中指定的文件到服务端, 在函数中获取文件名, 不用传参数
def put():
# 选择对话框
fileName = tkinter.filedialog.askopenfilename(title='Select upload file')
# 如果有选择文件才继续执行
if fileName:
name = fileName.split('/')[-1]
message = 'put ' + name
s.send(message.encode())
with open(fileName, 'rb') as f:
while True:
a = f.read(1024)
if not a:
break
s.send(a)
time.sleep(5) # 延时确保文件发送完整
s.send('EOF'.encode())
tkinter.messagebox.showinfo(title='Message',
message='Upload completed!')
cd('cd same')
lab() # 上传成功后刷新显示页面
# 创建上传按钮, 并绑定上传文件功能
upload = tkinter.Button(root, text='Upload file', command=put)
upload.place(x=600, y=353, height=30, width=80)
# 关闭文件管理器, 待完善
def closeFile():
root['height'] = 390
root['width'] = 580
# 关闭连接
s.send('quit'.encode())
s.close()
# 创建关闭按钮
close = tkinter.Button(root, text='Close', command=closeFile)
close.place(x=685, y=353, height=30, width=70)
# 创建文件按钮
fBut = tkinter.Button(root, text='File', command=fileClient)
fBut.place(x=185, y=320, width=60, height=30)
# 创建多行文本框, 显示在线用户
listbox1 = tkinter.Listbox(root)
listbox1.place(x=445, y=0, width=130, height=320)
def users():
global listbox1, ii
if ii == 1:
listbox1.place(x=445, y=0, width=130, height=320)
ii = 0
else:
listbox1.place_forget() # 隐藏控件
ii = 1
# 查看在线用户按钮
button1 = tkinter.Button(root, text='Users online', command=users)
button1.place(x=485, y=320, width=90, height=30)
# 创建输入文本框和关联变量
a = tkinter.StringVar()
a.set('')
entry = tkinter.Entry(root, width=120, textvariable=a)
entry.place(x=5, y=350, width=570, height=40)
def send(*args):
# 没有添加的话发送信息时会提示没有聊天对象
users.append('------Group chat-------')
#users.append('Robot')
print(chat)
if chat not in users:
tkinter.messagebox.showerror('Send error', message='There is nobody to talk to!')
return
if chat == user:
tkinter.messagebox.showerror('Send error', message='Cannot talk with yourself in private!')
return
mes = entry.get() + ':;' + user + ':;' + chat # 添加聊天对象标记
s.send(mes.encode())
a.set('') # 发送后清空文本框
# 创建发送按钮
button = tkinter.Button(root, text='Send', command=send)
button.place(x=515, y=353, width=60, height=30)
root.bind('<Return>', send) # 绑定回车发送信息
# 私聊功能
def private(*args):
global chat
# 获取点击的索引然后得到内容(用户名)
indexs = listbox1.curselection()
index = indexs[0]
if index > 0:
chat = listbox1.get(index)
# 修改客户端名称
if chat == '------Group chat-------':
root.title(user)
return
ti = user + ' --> ' + chat
root.title(ti)
# 在显示用户列表框上设置绑定事件
listbox1.bind('<ButtonRelease-1>', private)
# 用于时刻接收服务端发送的信息并打印
def recv():
global users
while True:
try:
data = s.recv(1024)
data = data.decode()
# 没有捕获到异常则表示接收到的是在线用户列表
try:
data = json.loads(data)
users = data
listbox1.delete(0, tkinter.END) # 清空列表框
number = (' Users online: ' + str(len(data)))
listbox1.insert(tkinter.END, number)
listbox1.itemconfig(tkinter.END, fg='green', bg="#f0f0ff")
listbox1.insert(tkinter.END, '------Group chat-------')
listbox1.itemconfig(tkinter.END, fg='green')
for i in range(len(data)):
listbox1.insert(tkinter.END, (data[i]))
listbox1.itemconfig(tkinter.END, fg='green')
except:
data = data.split(':;')
data1 = data[0].strip() # 消息
data2 = data[1] # 发送信息的用户名
data3 = data[2] # 聊天对象
markk = data1.split(':')[1]
if (markk in dic):
data4 = '\n' + data2 + ':' # 例:名字-> \n名字:
if data3 == '------Group chat-------':
if data2 == user: # 如果是自己则将则字体变为蓝色
listbox.insert(tkinter.END, data4, 'blue')
else:
listbox.insert(tkinter.END, data4, 'green') # END将信息加在最后一行
listbox.image_create(tkinter.END, image=dic[markk])
elif data2 == user or data3 == user: # 显示私聊
listbox.insert(tkinter.END, data4, 'red') # END将信息加在最后一行
listbox.image_create(tkinter.END, image=dic[markk])
else:
data1 = '\n' + data1
if data3 == '------Group chat-------':
if data2 == user: # 如果是自己则将则字体变为蓝色
listbox.insert(tkinter.END, data1, 'blue')
else:
listbox.insert(tkinter.END, data1, 'green') # END将信息加在最后一行
if len(data) == 4:
listbox.insert(tkinter.END, '\n' + data[3], 'pink')
elif data2 == user or data3 == user: # 显示私聊
listbox.insert(tkinter.END, data1, 'red') # END将信息加在最后一行
listbox.see(tkinter.END) # 显示在最后
except:
pass
def reflash():
global s, IP, PORT, user
if messagebox.askokcancel("reflash", "Do you want to reflash the connection?"):
s.close()
print('reflashing...\n')
time.sleep(1)
m = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
m.connect((IP, PORT))
m.send(user.encode()) # 发送用户名
s = m
print('reflash done\n')
rebu = tkinter.Button(root, text='reflash', command=reflash)
rebu.place(x=325, y=320, width=60, height=30)
def on_closing():
global s
if messagebox.askokcancel("Quit", "Do you want to quit?"):
s.close()
root.destroy()
print('log out!')
root.protocol("WM_DELETE_WINDOW", on_closing)
r = threading.Thread(target=recv)
r.start() # 开始线程接收信息
root.mainloop()
|
query_load.py | from urlparse import urlparse
import httplib, sys, multiprocessing
num_processes = int(sys.argv[1])
series_name = sys.argv[2]
print num_processes
headers = {"Content-type": "application/json", "X-Auth-Token": "HPAuth10_dfd2a6394b90b13c77cc06c68064ca5763b58ba7e05399d9ffe23d2df2524838" }
ourl = 'http://localhost:8086/db/testmetrics/series'
def doProcess():
try:
url = urlparse(ourl)
conn = httplib.HTTPConnection(url.netloc)
conn.request("POST", url.path, "", headers)
res = conn.getresponse()
if res.status != 200:
raise Exception(res.status)
return res.status, ourl
except Exception as ex:
print ex
return "error", ourl
if __name__ == '__main__':
jobs = []
for i in range(num_processes):
p = multiprocessing.Process(target=doProcess)
jobs.append(p)
p.start()
p.join()
|
followMarkerWithMotor.py | #Move marker towards marker center with stepper motors
from videoUtils import CaptureVideo
from motor import MotorNema
from control import generateCommands, Kp
#import firstOrderSystem
#import zeroOrderSystem
import threading
import time
import numpy as np
import cv2
import cv2.aruco as aruco
import markerUtil
import threading
captureVideo = CaptureVideo()
motors = MotorNema()
width = captureVideo.cap.get(cv2.CAP_PROP_FRAME_WIDTH) # float `width`
height = captureVideo.cap.get(cv2.CAP_PROP_FRAME_HEIGHT) # float `height`
centerX = width/2
centerY = height/2
cameraCenterX = centerX
cameraCenterY = centerY
minForceX = 0
maxForceX = Kp*width/2
minForceY = 0
maxForceY = Kp*height/2
print("width: ", width, ", height: ", height)
radius = 41 #must be an odd number, or else GaussianBlur will fail
circleColor = (0, 0, 255) #BGR
circleThickness = 15
threading.Thread(target = captureVideo.get_frame, args = []).start()
threading.Thread(target = motors.moveMotorX, args = []).start()
threading.Thread(target = motors.moveMotorY, args = []).start()
time.sleep(2) #wait for camera frame to stabilize (initial frame is black)
try:
while True:
image = captureVideo.frame.copy()
[arucoMarkerDetected, xArucoMarkerCenter, yArucoMarkerCenter] = markerUtil.findArucoMarker(image)
if arucoMarkerDetected:
#Generate commands to move camera center towards marker center
[forceX, forceY, errorStr] = generateCommands([xArucoMarkerCenter, yArucoMarkerCenter], [cameraCenterX, cameraCenterY], captureVideo.timeStep_s)
#[cameraCenterX, cameraCenterY] = firstOrderSystem.calcState([forceX, forceY], [cameraCenterX, cameraCenterY], captureVideo.timeStep_s)
#[cameraCenterX, cameraCenterY] = zeroOrderSystem.calcState([xArucoMarkerCenter, yArucoMarkerCenter], [cameraCenterX, cameraCenterY], captureVideo.timeStep_s)
forceXMag = abs(forceX)
forceYMag = abs(forceY)
forceXMag_clipped = np.clip(forceXMag, minForceX, maxForceX)
forceYMag_clipped = np.clip(forceYMag, minForceY, maxForceY)
forceFractionX = (forceXMag_clipped - minForceX) / (maxForceX - minForceX)
forceFractionY = (forceYMag_clipped - minForceY) / (maxForceY - minForceY)
#DEBUG
minSteps = 1
maxSteps = 2*200
stepsX = minSteps + round((maxSteps-minSteps)*forceFractionX)
print("forceX:",forceX, "forceFractionX:",forceFractionX, "stepsX:", stepsX)
#\DEBUG
motors.setForce(forceX, forceFractionX, forceY, forceFractionY)
image = captureVideo.frame.copy()
image = cv2.putText(image, errorStr, (0,100), cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, color=(255, 255, 255), thickness=2, lineType=cv2.LINE_AA)
cv2.circle(image, (xArucoMarkerCenter, yArucoMarkerCenter), radius, circleColor, circleThickness)
else:
motors.setForce(0, 0, 0, 0) #temporarily stop motors
cv2.drawMarker(image, (int(cameraCenterX), int(cameraCenterY)), (255,0,0), markerType=cv2.MARKER_CROSS, markerSize=20, thickness=4, line_type=cv2.LINE_AA)
cv2.imshow("Robust", image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except KeyboardInterrupt:
print('CTRL+C pressed.')
finally:
motors.stop()
motors.GPIOCleanup()
captureVideo.stop()
cv2.destroyAllWindows()
print("Main thread ended.")
|
I2TCP_client.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: i2cy(i2cy@outlook.com)
# Filename: I2TCP_client
# Created on: 2021/1/10
import socket
import threading
import sys
import time
import uuid
from hashlib import md5
VERSION = "1.1"
class logger: # Logger
def __init__(self, filename=None, line_end="lf",
date_format="%Y-%m-%d %H:%M:%S", level="DEBUG", echo=True):
self.level = 1
self.echo = echo
if level == "DEBUG":
self.level = 0
elif level == "INFO":
self.level = 1
elif level == "WARNING":
self.level = 2
elif level == "ERROR":
self.level = 3
elif level == "CRITICAL":
self.level = 4
else:
raise Exception("logger level: DEBUG, INFO, WARNING, ERROR, CRITICAL")
try:
temp = time.strftime(date_format)
del temp
except Exception as err:
raise Exception("Failed to set date formant, result: " + str(err))
self.date_format = date_format
if line_end == "lf":
self.line_end = "\n"
elif line_end == "crlf":
self.line_end = "\r\n"
else:
raise Exception("Unknow line end character(s): \"" + line_end + "\"")
self.filename = filename
if filename == None:
return
try:
log_file = open(filename, "w")
log_file.close()
except Exception as err:
raise Exception("Can't open file: \"" + filename + "\", result: " + str(err))
def DEBUG(self, msg):
if self.level > 0:
return
infos = "[" + time.strftime(self.date_format) + "] [DBUG] " + msg + self.line_end
if self.echo:
sys.stdout.write(infos)
sys.stdout.flush()
if self.filename == None:
return
log_file = open(self.filename, "a")
log_file.write(infos)
log_file.close()
return infos
def INFO(self, msg):
if self.level > 1:
return
infos = "[" + time.strftime(self.date_format) + "] [INFO] " + msg + self.line_end
if self.echo:
sys.stdout.write(infos)
sys.stdout.flush()
if self.filename == None:
return
log_file = open(self.filename, "a")
log_file.write(infos)
log_file.close()
return infos
def WARNING(self, msg):
if self.level > 2:
return
infos = "[" + time.strftime(self.date_format) + "] [WARN] " + msg + self.line_end
if self.echo:
sys.stdout.write(infos)
sys.stdout.flush()
if self.filename == None:
return
log_file = open(self.filename, "a")
log_file.write(infos)
log_file.close()
return infos
def ERROR(self, msg):
if self.level > 3:
return
infos = "[" + time.strftime(self.date_format) + "] [EROR] " + msg + self.line_end
if self.echo:
sys.stdout.write(infos)
sys.stdout.flush()
if self.filename == None:
return
log_file = open(self.filename, "a")
log_file.write(infos)
log_file.close()
return infos
def CRITICAL(self, msg):
infos = "[" + time.strftime(self.date_format) + "] [CRIT] " + msg + self.line_end
if self.echo:
sys.stdout.write(infos)
sys.stdout.flush()
if self.filename == None:
return
log_file = open(self.filename, "a")
log_file.write(infos)
log_file.close()
return infos
class dynKey: # 64-Bits dynamic key generator/matcher
def __init__(self, key, flush_times=1, multiplier=0.01):
if isinstance(key, str):
key = key.encode()
elif isinstance(key, bytes):
pass
else:
raise Exception("private key must be String or Bytes")
self.key = key
self.multiplier = multiplier
if flush_times <= 0:
flush_times = 1
self.flush_time = flush_times
def keygen(self, offset=0): # 64-Bits dynamic key generator
time_unit = int(time.time() * self.multiplier) + int(offset)
time_unit = str(time_unit).encode()
time_unit = md5(time_unit).digest()
key_unit = md5(self.key).digest()
sub_key_unit = time_unit + key_unit
for i in range(self.flush_time):
sub_key_unit = md5(sub_key_unit).digest()[::-1]
conv_core = [int((num + 1 * self.multiplier) % 255 + 1) for num in sub_key_unit[:3]]
conv_res = []
for i2, ele in enumerate(sub_key_unit[3:-2]):
conv_res_temp = 0
for c in range(3):
conv_res_temp += sub_key_unit[3 + i2 + c] * conv_core[c]
conv_res.append(int(conv_res_temp % 256))
sub_key_unit = md5(sub_key_unit[:3] + bytes(conv_core)).digest()[::-1]
sub_key_unit += md5(sub_key_unit + bytes(conv_res)).digest()
sub_key_unit += md5(bytes(conv_res)).digest()
sub_key_unit += md5(bytes(conv_res) + self.key).digest()
sub_key_unit += key_unit
conv_cores = [[time_unit[i2] for i2 in range(4 * i, 4 * i + 4)]
for i in range(4)]
for i, ele in enumerate(conv_cores):
ele.insert(2,
1 * self.multiplier + (key_unit[i] + key_unit[i + 4] + key_unit[i + 8] + key_unit[i + 12]) // 4)
final_key = sub_key_unit
for i in range(4):
conv_core = conv_cores[i]
conv_res = []
for i2, ele in enumerate(final_key[:-4]):
conv_res_temp = 0
for c in range(5):
conv_res_temp += final_key[i2 + c] * conv_core[c]
conv_res.append(int(conv_res_temp % 256))
final_key = bytes(conv_res)
return final_key
def keymatch(self, key): # Live key matcher
lock_1 = self.keygen(-1)
lock_2 = self.keygen(0)
lock_3 = self.keygen(1)
lock = [lock_1, lock_2, lock_3]
if key in lock:
return True
else:
return False
class I2TCPclient:
def __init__(self, hostname, port=27631, key=b"basic",
watchdog_timeout=15, logger=logger()):
"""
I2TCPclient Class
:param hostname: str, server address
:param port: int, server port
:param key: bytes, dynamic key for authentication
:param watchdog_timeout: int, watchdog timeout
:param logger: Logger, client log output object
"""
self.address = (hostname, port)
self.clt = None
self.keygen = dynKey(key)
self.live = False
self.log_header = "[I2TCP]"
self.logger = logger
self.version = VERSION.encode()
self.busy = False
self.mac_id = uuid.UUID(int=uuid.getnode()).bytes[-6:]
self.watchdog_waitting = 0
self.watchdog_timeout = watchdog_timeout * 2
self.threads = {"heartbeat": False,
"watchdog": False}
self.connected = False
def _packager(self, data):
"""
pack data with I2TCP format
:param data: bytes
:return: List(bytes), packed data
"""
offset = 0
paks = []
length = len(data)
left = length
header_unit = self.version + self.keygen.key
while left > 0:
pak = b"A" + left.to_bytes(length=3, byteorder='big', signed=False)
if left < 60000:
left = 0
else:
left -= 60000
pak_length = length - left - offset
pak += pak_length.to_bytes(length=2, byteorder='big', signed=False)
pak += md5(pak + header_unit).digest()[:3]
pak += data[offset:length - left]
offset = length - left
paks.append(pak)
return paks
def _depacker(self, pak_data):
"""
depack packed data to normal data format
:param pak_data: bytes, packed data
:return: bytes, data
"""
pak_type = pak_data[0]
header_unit = self.version + self.keygen.key
if pak_type == ord("H"):
ret = None
elif pak_type == ord("A"):
ret = {"total_length": int.from_bytes(pak_data[1:4], byteorder='big', signed=False),
"package_length": int.from_bytes(pak_data[4:6], byteorder='big', signed=False),
"header_md5": pak_data[6:9],
"data": pak_data[9:]}
header_md5 = md5(pak_data[0:6] + header_unit).digest()[:3]
if header_md5 != ret["header_md5"]:
ret = None
else:
ret = None
return ret
def _heartbeat_thread(self):
"""
watchdog heartbeat service, this keeps connection alive
:return: None
"""
self.threads.update({"heartbeat": True})
local_header = "[heartbeat]"
self.logger.DEBUG("{} {} thread started".format(self.log_header, local_header))
try:
tick = 0
while self.live:
if tick >= 4:
tick = 0
if self.watchdog_waitting > (self.watchdog_timeout // 2):
try:
self.clt.sendall(
b"Heartbeat"
)
self.logger.DEBUG("{} {} heartbeat sent".format(self.log_header, local_header))
self._feed_watchdog()
except Exception as err:
self.logger.WARNING("{} {} failed to send heartbeat, {}".format(self.log_header,
local_header,
err))
time.sleep(0.5)
tick += 1
except Exception as err:
self.logger.ERROR("{} {} heartbeat error, {}".format(self.log_header, local_header, err))
self.logger.DEBUG("{} {} thread stopped".format(self.log_header, local_header))
self.threads.update({"heartbeat": False})
def _watchdog_thread(self):
"""
watchdog service, keeps connection available
:return: None
"""
self.threads.update({"watchdog": True})
local_header = "[watchdog]"
self.logger.DEBUG("{} {} thread started".format(self.log_header, local_header))
try:
tick = 0
while self.live:
if tick >= 4:
tick = 0
if self.watchdog_waitting > self.watchdog_timeout:
self.logger.ERROR("{} {} server seems not responding, disconnecting...".format(self.log_header,
local_header))
self.reset()
if self.clt is None or not self.connected:
self.logger.INFO("{} {} connection lost".format(self.log_header, local_header))
self.reset()
break
time.sleep(0.5)
tick += 1
self.watchdog_waitting += 1
except Exception as err:
self.logger.ERROR("{} {} watchdog error, {}".format(self.log_header, local_header, err))
self.logger.DEBUG("{} {} thread stopped".format(self.log_header, local_header))
self.threads.update({"watchdog": False})
def _feed_watchdog(self):
"""
reset the timer of watchdog to keep watchdog from timeout
:return: None
"""
self.watchdog_waitting = 0
def _start(self):
"""
start watchdog service and heartbeat service
:return: None
"""
if not self.threads["heartbeat"]:
heartbeat_thr = threading.Thread(target=self._heartbeat_thread)
heartbeat_thr.start()
if not self.threads["watchdog"]:
watchdog_thr = threading.Thread(target=self._watchdog_thread)
watchdog_thr.start()
def reset(self):
"""
reset connection status (close the connection)
:return: None
"""
self.live = False
try:
self.clt.close()
except:
pass
self.clt = None
self.connected = False
def connect(self, timeout=10):
"""
connect to server
:return: bool, connection status
"""
if self.connected:
self.logger.ERROR("{} server has already connected".format(self.log_header))
return self.connected
clt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clt.settimeout(timeout)
try:
clt.connect(self.address)
except Exception as err:
self.logger.ERROR("{} failed to connect to server, {}".format(self.log_header, err))
return self.connected
try:
dynamic_key = self.keygen.keygen()
clt.sendall(dynamic_key)
feedback = clt.recv(65536)
if feedback != b"OK":
raise Exception("invalid key or invalid server")
self.clt = clt
self.live = True
self.connected = True
self._start()
except Exception as err:
self.logger.ERROR("{} failed to auth, {}".format(self.log_header, err))
return self.connected
self.logger.INFO("{} server {}:{} connected".format(self.log_header,
self.address[0],
self.address[1]))
return self.connected
def send(self, data):
"""
send data to connected server
:param data: bytes
:return: int, total data length (include headers)
"""
if self.clt is None or not self.connected:
raise Exception("no connection built yet")
paks = self._packager(data)
sent = 0
while self.busy:
time.sleep(0.005)
self.busy = True
try:
for i in paks:
ret = self.clt.sendall(i)
sent += len(i)
self._feed_watchdog()
except Exception as err:
self.logger.ERROR("{} failed to send message, {}".format(self.log_header, err))
self.busy = False
return sent
def recv(self, exception=True):
"""
receive a package from server
:return: bytes, depacked data
"""
if self.clt is None or not self.connected:
raise Exception("no connection built yet")
all_data = None
try:
ret = None
while ret is None:
pak = self.clt.recv(9)
if pak == b"":
self.logger.INFO("{} connection lost".format(self.log_header))
self.reset()
raise Exception("no connection built yet")
ret = self._depacker(pak)
total_length = ret["total_length"]
self.logger.DEBUG("{} receiving data of total length {}".format(self.log_header, total_length))
data = b""
length = 0
while length != ret["package_length"]:
length = len(data)
data += self.clt.recv(ret["package_length"] - length)
all_data = data
while len(all_data) < total_length:
pak = self.clt.recv(9)
ret = self._depacker(pak)
if ret is None:
raise Exception("broken package")
data = b""
length = 0
while length != ret["package_length"]:
length = len(data)
data += self.clt.recv(ret["package_length"] - length)
all_data += data
except Exception as err:
if exception:
self.logger.ERROR("{} failed to receive message, {}".format(self.log_header, err))
all_data = None
return all_data
def init():
pass
def receive_loop_test(clt):
while clt.live:
try:
data = clt.recv()
print("## -test- ## data received: {}".format(data))
except:
continue
time.sleep(0.5)
def test():
test_hostname = "i2cy.tech"
clt = I2TCPclient(test_hostname, logger=logger(filename="client_testrun.log"))
if not clt.connect():
print("trying to connect to local test server")
clt.reset()
clt = I2TCPclient("localhost", logger=logger(filename="client_testrun.log"))
clt.connect()
gtc = ""
for i in range(3):
pic_data = open("test_pic.png", "rb").read()
clt.send(pic_data)
data = clt.recv()
print("## -test- ## pic test result: {}".format(pic_data == data))
pic_data = open("I2TCP_server.py", "rb").read()
clt.send(pic_data)
data = clt.recv()
print("## -test- ## file test result: {}".format(pic_data == data))
pic_data = open("I2TCP_server.py", "rb").read()
clt.send(pic_data)
clt.send(pic_data)
clt.send(pic_data)
data1 = clt.recv()
data2 = clt.recv()
data3 = clt.recv()
res = pic_data == data1 and pic_data == data2 and pic_data == data3
print("## -test- ## quick send file test result: {}".format(res))
listener = threading.Thread(target=receive_loop_test, args=(clt,))
listener.start()
while not gtc in ("q", "quit", "exit"):
try:
gtc = input("input data to send (q to exit): ")
clt.send(gtc.encode())
except KeyboardInterrupt:
break
clt.reset()
if __name__ == '__main__':
init()
test()
else:
init()
|
pretty_progress.py | # coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
try:
from Queue import Empty # for python 2
except ImportError:
from queue import Empty # for python 3
from multiprocessing import Process, Queue
from os import environ
from os.path import join
from re import sub
from sys import stderr, stdout
from time import sleep
from timeit import default_timer as timer
from ansible.constants import COLOR_ERROR, COLOR_OK, COLOR_SKIP
from ansible.playbook import Playbook
from ansible.playbook.play import Play
from ansible.playbook.task import Task
from ansible.plugins.callback import CallbackBase
from backports.shutil_get_terminal_size import get_terminal_size
RUNNING_PREFIX = 'RUNNING'
SUCCESS_PREFIX = 'SUCCESS'
FAILURE_PREFIX = 'FAILURE'
IGNORED_PREFIX = 'IGNORED'
ERRORED_PREFIX = 'ERRORED'
SKIPPED_PREFIX = 'SKIPPED'
# poll at 20 Hz
POLL_DURATION = 0.05
# we need a reasonable amount of width but we do not
# want to take up more than the width of a single line
# a line will look like:
# PREFIX | IDENT [DETAILS DETAILS ...] ------ [TIMESTAMP]
OUTPUT_WIDTH = min(get_terminal_size().columns, 150)
prefix_width = 7 # e.g. `SUCCESS`
prefix_separator_width = 3 # e.g. ` | `
name_padding_width = 1 # e.g. ` ` after name
time_padding_width = 2 # `- ` before time
time_width = 11 # e.g. `[00:00.000]`
IDENTIFIER_WIDTH = OUTPUT_WIDTH - \
prefix_width - prefix_separator_width - \
name_padding_width - \
time_padding_width - time_width
# TODO: determine if there is a better way
MOVE_UP_ONE_LINE = b'\033[F'
CLEAR_LINE = b'\033[K'
def display_workload(queue):
"""
Async worker to display the workloads as fed
by the queue. Will attempt to fetch new data
from the queue at 20Hz, but failing that, it
will re-render and display the last seen data
to keep the refresh rate at or above 20Hz.
:param queue: queue to consume data from
"""
last_workload = []
last_num_lines = 0
while True:
try:
workload = queue.get(timeout=POLL_DURATION)
except Empty:
workload = last_workload
# navigate to the top to over-write the last output
for i in range(last_num_lines):
try: # for python3
stdout.buffer.write(MOVE_UP_ONE_LINE)
except AttributeError: # for python2
stdout.write(MOVE_UP_ONE_LINE)
if i < last_num_lines - len(workload):
# if there are lines in the old output which
# we may not overwrite, just clear them
try: # for python3
stdout.buffer.write(CLEAR_LINE)
except AttributeError: # for python2
stdout.write(CLEAR_LINE)
# re-render and print the new output
last_num_lines = 0
for item in workload:
last_num_lines += item.render()
last_workload = workload
class CallbackModule(CallbackBase):
"""
This module allows for CLI-based Ansible invocations
to have nicely formatted output that cleanly indicates
to the users what their CLI call is doing and how far
along it is in the process.
"""
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
CALLBACK_NAME = 'pretty_progress'
def __init__(self, *args, **kwargs):
# a container for the workloads we are tracking
self._workloads = []
# set up for the async worker we use to update
# the screen at a rate more frequent than that
# which we get callbacks at
self._queue = Queue()
self._worker = Process(target=display_workload, args=(self._queue, ))
# ensure that the worker thread is reaped if
# the main thread dies by marking the thread
# as a daemon
self._worker.daemon = True
self._worker.start()
super(CallbackModule, self).__init__(*args, **kwargs)
def update_last_workload(self, status):
"""
Update the last workload to complete and send
the updated list of workloads to the consumer.
:param status: status to update to
"""
self._workloads[-1].complete(status)
def finalize_last_play(self, status):
"""
Update the last play to be complete and remove
any trace of the tasks that were displayed for it
while it was running if it succeeded.
:param status: status to update to
"""
last_play_index = -1
for i, workload in reversed(list(enumerate(self._workloads))):
if 'PLAY [' in workload.identifier:
last_play_index = i
break
if last_play_index != -1:
# we are called on play start, as there is no
# callback hook for play end, so if we are called
# on the start of the first play, there will be
# no previous play to update
if status == SUCCESS_PREFIX:
# if we succeeded, nobody cares what tasks ran,
# so we can hide them; otherwise, we want the
# users to see the failed tasks
self._workloads = self._workloads[:last_play_index + 1]
self._workloads[last_play_index].complete(status)
def finalize_playbook(self, status):
"""
Update the playbook and last play status to
reflect the end of execution.
:param status: status we want to update to
"""
self.finalize_last_play(status)
# we only ever run one playbook before we
# reset the internal state, so we can assume
# that there is only one playbook in the
# list of workloads, and that it is the first
# item in the list
self._workloads[0].complete(status)
def v2_playbook_on_start(self, playbook):
"""
Implementation of the callback endpoint to be
fired when execution of a new playbook begins.
We know that we will only ever run one playbook
at a time, so we take some liberties with this:
- we don't attempt to update the current
workload state as we assume it is empty
:param playbook: playbook that just started
"""
self._workloads.append(Workload(playbook))
def v2_playbook_on_play_start(self, play):
"""
Implementation of the callback endpoint to be
fired when execution of a new play begins. We
need to clean up the last play before we add
the new one to the workloads.
:param play: play that just started
"""
self.finalize_last_play(SUCCESS_PREFIX)
self._workloads.append(Workload(play))
def v2_playbook_on_task_start(self, task, is_conditional):
"""
Implementation of the callback endpoint to be
fired when execution of a new task begins. We
only keep track of the last running task, so
if there is already a task displayed for the
current play we over-write it.
:param task: task that just started
:param is_conditional: if the task is conditional
"""
if 'TASK' in self._workloads[-1].identifier:
self._workloads[-1] = Workload(task)
else:
self._workloads.append(Workload(task))
def v2_runner_on_ok(self, result):
"""
Implementation of the callback endpoint to be
fired when a task finishes executing successfully.
We assume that the last workload is the last task.
:param result: result of the last task
"""
self.update_last_workload(SUCCESS_PREFIX)
def v2_runner_on_failed(self, result, ignore_errors=False):
"""
Implementation of the callback endpoint to be
fired when a task fails to execute successfully.
If we are not ignoring errors, we will not only
show the task as failed, but also add the error
information to the output stream.
:param result: result of the last task
:param ignore_errors: if we should consider this a failure
"""
status = IGNORED_PREFIX if ignore_errors else FAILURE_PREFIX
self.update_last_workload(status)
if not ignore_errors:
self._workloads.append(Failure(result))
def v2_runner_on_unreachable(self, result):
"""
Implementation of the callback endpoint to be
fired when a task can't reach it's target host.
We will show the task as errored and append the
error information to the output stream.
:param result: result of the last task
"""
self.update_last_workload(ERRORED_PREFIX)
self._workloads.append(Failure(result))
def v2_runner_on_skipped(self, result):
"""
Implementation of the callback endpoint to be
fired when task execution is skipped.
:param result: result of the last task
"""
self.update_last_workload(SKIPPED_PREFIX)
def v2_on_any(self, *args, **kwargs):
"""
Implementation of the callback endpoint to be
fired *after* any other callback is fired. We
know that if a callback happened, it could have
changed the state of the workloads we track,
so we send the updated state to the consumer
thread after any callback. If the callback did
not change the internal state, the consumer
will just refresh faster than normal, which is
not an problem. We also will trigger after the
`v2_playbook_on_stats` endpoint, after which
we will not have anyone listening to the other
end of the queue, but we will also be cleaning
up and exiting soon anyway, so again it is not
an issue.
:param args: arguments [ignored]
:param kwargs: keyword arguments [ignored]
"""
self._queue.put(self._workloads)
def v2_playbook_on_stats(self, stats):
"""
Implementation of the callback endpoint to be
fired when a playbook is finished. As we are
only running one playbook at a time, we can
again make some assumptions about what to do
here. Specifically:
- we can assume the last playbook that ran is
the first item in our workload queue
- we can clean up the worker thread as there
will be no more tasks running after this
:param stats:
"""
# there isn't a good API for determining failures,
# so we need to search for them ourselves
status = SUCCESS_PREFIX
# task failures are recorded per host per type of
# failure, so we need to check that any hosts in
# these sections have occurrences of the failure
# recorded
for host in stats.dark:
if stats.dark[host] > 0:
# tasks failed to reach their host
status = FAILURE_PREFIX
break
for host in stats.failures:
if stats.failures[host] > 0:
# tasks failed to execute
status = FAILURE_PREFIX
break
self.finalize_playbook(status)
# we need to manually trigger this queue update
self._queue.put(self._workloads)
# wait for consumer to post everything we have
while not self._queue.empty():
sleep(POLL_DURATION)
# we are using the multiprocessing queue, which
# does not implement join() and task_done(), so
# we cannot reliably know that the consumer has
# worked on the last element when we see that the
# queue is empty on our end. No implementation
# exists with a peek(), either, so we just have
# to wait for one timeout iteration here and
# hope for the best.
sleep(POLL_DURATION)
self._worker.terminate()
self._worker.join()
def format_identifier(workload):
"""
Determine an identifier for the workload.
:param workload: workload to identify
:return: identifier for the workload
"""
if isinstance(workload, Playbook):
# unfortunately there is no nice way to self-
# identify for a playbook, so we must access
# a protected member. Furthermore, we do not
# necessarily need the full path to the play-
# book and we can live with the relative path
# from the origin-ci-tool root.
# TODO: do this with os.path?
return 'PLAYBOOK [{}]'.format('origin-ci-tool{}'.format(sub('^.*origin-ci-tool', '', workload._file_name)))
elif isinstance(workload, Play):
return 'PLAY [{}]'.format(workload.get_name())
elif isinstance(workload, Task):
return 'TASK [{}]'.format(workload.get_name())
else:
return 'UNKNOWN'
def format_status(status):
"""
Format the status of a workload, with
colors where appropriate.
:param status: status prefix
:return: formatted status
"""
color = 'normal'
if status == SUCCESS_PREFIX:
color = COLOR_OK
elif status == FAILURE_PREFIX or status == ERRORED_PREFIX:
color = COLOR_ERROR
elif status == IGNORED_PREFIX or status == SKIPPED_PREFIX:
color = COLOR_SKIP
return colorize(status, color=color)
class Workload(object):
"""
A wrapper for an Ansible workload like a play,
playbook, task, etc. that knows how to display
information about the workload in a pretty way.
"""
def __init__(self, workload):
"""
Create a Workload wrapper for an Ansible workload.
:param workload: a play, playbook, task, etc.
"""
self.identifier = format_identifier(workload)
self.status = RUNNING_PREFIX
self.start_time = timer()
# to be set when we finish this workload
self.elapsed_time = None
def __str__(self):
return self.format()
def complete(self, status):
"""
Mark the workload as having been completed.
:param status: new status to update to
"""
self.status = format_status(status)
self.elapsed_time = self.format_runtime()
def render(self):
"""
Render a representation of this workload onto
the screen using stdout.
:return: number of lines written
"""
stdout.write(self.format())
return 1
def format(self):
"""
Format a string containing:
PREFIX | NAME -------------------- [TIME]
Where PREFIX is one of the above constants,
NAME is an identifier for the Ansible play
or playbook being run, and time is a time-
stamp with format MM:SS.SSS.
We will truncate the name so that everything
fits in the allotted width. If the name is
not going to fit, we will append an ellipsis.
:return: formatted self-representation
"""
if len(self.identifier) > IDENTIFIER_WIDTH:
self.identifier = '{}...'.format(self.identifier[:IDENTIFIER_WIDTH - 3])
fill_width = IDENTIFIER_WIDTH - len(self.identifier)
return '{} | {} -{} [{}]\n'.format(
self.status,
self.identifier,
'-' * fill_width,
self.format_runtime(),
)
def format_runtime(self):
"""
Format the current running time of this
Workload as a nice string like MM:SS.SSS.
:return: formatted time
"""
if self.elapsed_time:
return self.elapsed_time
else:
return '{:02.0f}:{:06.3f}'.format(*divmod(timer() - self.start_time, 60))
def format_result(result):
"""
Attempt to extract and format information
about an Ansible workload result.
:param result: result to inspect
:return: message
"""
full_message = format_failure_message(result)
full_message += format_item_failures(result)
full_message += format_terminal_output(result)
# detect internal module failures
full_message += format_terminal_output(result, stdout_key='module_stdout', stderr_key='module_stderr')
# detect internal stacktrace crashes
full_message += format_internal_exception_output(result)
full_message += format_parsing_error(result)
# filter out empty lines and lines of only whitespace
full_message = [line for line in full_message.splitlines() if line and line.strip()]
return "\n".join(full_message) + "\n"
def format_failure_message(result):
"""
Output a formatted version of the failure
message, if the result contains one.
:param result: result to inspect
:return: message
"""
if 'msg' in result:
# this is most likely a module failure
if isinstance(result['msg'], list):
error_message = '\n'.join(result['msg'])
else:
error_message = result['msg']
return '{}\n'.format(error_message)
return ''
def format_item_failures(result):
"""
Output a formatted version of the item
failures, if the result contains any.
:param result: result to inspect
:return: message
"""
if 'results' in result:
# this is most likely a failure from with_items
item_preamble = 'The following error messages came from items:'
item_messages = []
for item_result in result['results']:
# the item could possibly contain any
# valid result output, as any Ansible
# workload can be looped over
item_messages.append(format_result(item_result))
item_messages = [message for message in item_messages if len(message) > 0]
if len(item_messages) > 0:
return '{}\n{}'.format(item_preamble, '\n'.join(item_messages))
return ''
def format_terminal_output(result, stdout_key='stdout', stderr_key='stderr'):
"""
Output a formatted version of the terminal
output (std{out,err}), if the result contains
either.
:param stdout_key: where stdout is recorded
:param stderr_key: where stderr is recorded
:param result: result to inspect
:return: formatted output message
"""
output_message = ''
if stdout_key in result:
# this is most likely a shell/command/raw failure
if len(result[stdout_key]) > 0:
output_message += '{}\n{}\n'.format('Output to stdout:', result[stdout_key])
if stderr_key in result:
if len(result[stderr_key]) > 0:
output_message += '{}\n{}\n'.format(colorize('Output to stderr:', color=COLOR_ERROR), result[stderr_key])
if stdout_key in result and len(result[stdout_key]) == 0 and stderr_key in result and len(result[stderr_key]) == 0:
output_message = colorize('No output was written to stdout or stderr!', color=COLOR_ERROR)
return output_message
def format_internal_exception_output(result):
"""
Output a formatted version of any internal
errors that Ansible runs into when executing,
if any are present.
:param result: result to inspect
:return: formatted output message
"""
if 'exception' in result:
return 'An internal exception occurred:\n{}'.format(result['exception'])
return ''
def format_parsing_error(result):
"""
Output a formatted version of any parsing
errors that Ansible runs into when looking
at a playbook, if any are present.
:param result: result to inspect
:return: formatted output message
"""
if 'reason' in result:
return 'Parsing the playbook failed:\n{}'.format(result['reason'])
return ''
class Failure(object):
"""
Holds information about a failure that happened
and can render itself onto the screen.
"""
def __init__(self, result):
self.identifier = 'FAILURE'
self.result = result._result
self.host = result._host
def __str__(self):
return self.format()
def render(self):
"""
Render a representation of this failure
onto the terminal screen.
:return: number of lines written
"""
full_message = self.format()
stderr.write(full_message)
return full_message.count('\n')
def format(self):
"""
Format the failure result nicely.
:return: the formatted error
"""
full_message = colorize('A task failed on host `{}`!\n'.format(self.host), color=COLOR_ERROR)
result = format_result(self.result)
if len(result.splitlines()) == 0:
# we have not been able to get any use-able
# messages from the result, so we should
# tell the user to look at the logs
# TODO: better OS-agnostic filesystem code for this
log_location = join(environ.get('ANSIBLE_LOG_ROOT_PATH', join('tmp', 'ansible', 'log')), '/', '{}'.format(self.host))
full_message += 'No useful error messages could be extracted, see full output at {}\n'.format(log_location)
else:
full_message += result
return full_message
# --- begin "pretty"
#
# pretty - A miniature library that provides a Python print and stdout
# wrapper that makes colored terminal text easier to use (e.g. without
# having to mess around with ANSI escape sequences). This code is public
# domain - there is no license except that you must leave this header.
#
# Copyright (C) 2008 Brian Nez <thedude at bri1 dot com>
#
# http://nezzen.net/2008/06/23/colored-text-in-python-using-ansi-escape-sequences/
codeCodes = {
'black': '0;30',
'bright gray': '0;37',
'blue': '0;34',
'white': '1;37',
'green': '0;32',
'bright blue': '1;34',
'cyan': '0;36',
'bright green': '1;32',
'red': '0;31',
'bright cyan': '1;36',
'purple': '0;35',
'bright red': '1;31',
'yellow': '0;33',
'bright purple': '1;35',
'dark gray': '1;30',
'bright yellow': '1;33',
'magenta': '0;35',
'bright magenta': '1;35',
'normal': '0',
}
def colorize(text, color):
"""String in color."""
return u"\033[%sm%s\033[0m" % (codeCodes[color], text)
# --- end "pretty"
|
learner.py | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Learner module cover the training process within the RL problems.
"""
import os
import threading
from time import time
from copy import deepcopy
import numpy as np
from absl import logging
from collections import deque
from xt.util.logger import Logger, StatsRecorder
from xt.util.profile_stats import PredictStats
from xt.framework.trainer import build_alg_with_trainer
from xt.benchmark.tools.evaluate_xt import (
make_workspace_if_not_exist,
parse_benchmark_args,
)
from xt.benchmark.visualize import BenchmarkBoard
from xt.framework.comm.message import message, get_msg_data, set_msg_info, set_msg_data, get_msg_info
from xt.util.common import bytes_to_str
from xt.util.hw_cloud_helper import mox_makedir_if_not_existed, sync_data_to_s3
class Learner(object):
def __init__(
self,
alg_para,
env_para,
agent_para,
test_master=None,
data_url=None,
benchmark_info=None,
):
self.alg_para = deepcopy(alg_para)
self.process_num = self.alg_para.get("process_num", 1)
self.test_master = test_master
self.train_worker = None
self.send_train = None
self.send_predict = None
self.send_broker = None
self.stats_deliver = None
self.train_lock = threading.Lock()
self.alg = None
self.trainer = None
self.shared_buff = None
self.bm_args = parse_benchmark_args(
env_para, alg_para, agent_para, benchmark_info
)
_model_dir = ["models", "benchmark"]
self._workspace, _archive, _job = make_workspace_if_not_exist(
self.bm_args, _model_dir
)
self.bm_board = BenchmarkBoard(_archive, _job)
self.model_path = os.path.join(self._workspace, _model_dir[0])
logging.info(
"{} \nworkspace: \n\t{} \n"
"model will save under path: \n\t{} \n"
"".format("*" * 10, self._workspace, self.model_path)
)
self.max_step = agent_para.get("agent_config", {}).get("complete_step")
# For Cloud
self.s3_path = None
if data_url is not None:
self.s3_path = os.path.join(data_url, _model_dir[0])
mox_makedir_if_not_existed(self.s3_path)
def async_predict(self):
""" create predict thread """
predict = [
PredictThread(
i,
self.alg,
self.send_predict,
self.send_broker,
self.stats_deliver,
self.train_lock,
)
for i in range(2)
]
predict_thread = [threading.Thread(target=t.predict) for t in predict]
for t in predict_thread:
t.setDaemon(True)
t.start()
def setup_stats_recorder(self):
"""setup an independent thread to record profiling information."""
stats_thread = StatsRecorder(
msg_deliver=self.stats_deliver,
bm_args=self.bm_args,
workspace=self._workspace,
bm_board=self.bm_board,
)
stats_thread.setDaemon(True)
stats_thread.start()
def init_async_train(self):
""" create train worker """
self.train_worker = TrainWorker(
self.send_train,
self.alg,
self.train_lock,
self.model_path,
self.send_broker,
self.s3_path,
self.max_step,
self.stats_deliver,
self.test_master,
)
def submit_algorithm(self, alg_instance, trainer_obj, shared_buff):
"""submit an algorithm, to update algorithm instance description."""
self.alg = alg_instance
self.trainer = trainer_obj
self.shared_buff = shared_buff
def start(self):
""" start all system """
alg, trainer_obj, shared_list = build_alg_with_trainer(
deepcopy(self.alg_para), self.send_broker, self.model_path, self.process_num
)
self.submit_algorithm(alg, trainer_obj, shared_list)
self.async_predict()
self.init_async_train()
self.setup_stats_recorder()
def main_loop(self):
self.train_worker.train()
def __del__(self):
if self.bm_board:
self.bm_board.close()
class TrainWorker(object):
def __init__(
self,
train_q,
alg,
lock,
model_path,
model_q,
s3_path,
max_step,
stats_deliver,
test_master=None,
):
self.train_q = train_q
self.alg = alg
self.lock = lock
self.model_path = model_path
self.model_q = model_q
self.actor_reward = dict()
self.rewards = []
self.s3_path = s3_path
self.max_step = max_step
self.actual_step = 0
self.won_in_episodes = deque(maxlen=256)
self.train_count = 0
self.stats_deliver = stats_deliver
self.test_master = test_master
self.logger = Logger(os.path.dirname(model_path))
def _dist_model(self, dist_model_name=("none", "none"), save_index=-1):
"""dist model tool"""
ctr_info = self.alg.dist_model_policy.get_dist_info(save_index)
# Not do distribute model with empty list
if isinstance(ctr_info, list):
for _ctr in ctr_info:
to_send_data = message(dist_model_name, cmd="dist_model", **_ctr)
self.model_q.send(to_send_data)
else:
to_send_data = message(dist_model_name, cmd="dist_model", **ctr_info)
self.model_q.send(to_send_data)
def train(self):
""" train model """
total_count = 0 # if on the off policy, total count > train count
save_count = 0
default_train_per_checkpoint = self.alg.train_per_checkpoint
if not self.alg.async_flag:
_model = self.alg.save(self.model_path, 0)
full_model_name = [os.path.join(self.model_path, i) for i in _model]
self._dist_model(dist_model_name=full_model_name)
while True:
# print("self.alg.prepare_data_times", self.alg.prepare_data_times)
if self.alg.prepare_data_times == -1:
prepare_data_times = max(1, self.train_q.len())
prepare_data_times = min(10, prepare_data_times)
# print("before len", self.train_q.len(), prepare_data_times)
else:
prepare_data_times = self.alg.prepare_data_times
for _tf_val in range(prepare_data_times):
logging.debug("wait data for preparing-{}...".format(_tf_val))
with self.logger.wait_sample_timer:
data = self.train_q.recv()
with self.logger.prepare_data_timer:
data = bytes_to_str(data)
self.record_reward(data)
self.alg.prepare_data(data["data"], ctr_info=data["ctr_info"])
logging.debug("finished prepare data-{}.".format(_tf_val))
# print("after len", self.train_q.len())
# support sync model before
if self.max_step and self.actual_step >= self.max_step:
break
total_count += 1
if not self.alg.train_ready(total_count, dist_dummy_model=self._dist_model):
continue
with self.lock, self.logger.train_timer:
logging.debug("start train process-{}.".format(self.train_count))
loss = self.alg.train(episode_num=total_count)
if type(loss) in (float, np.float64, np.float32, np.float16, np.float):
self.logger.record(train_loss=loss)
self.train_count += 1
# if self.train_count < 132:
# self.alg.train_per_checkpoint = 132
# else:
# self.alg.train_per_checkpoint = default_train_per_checkpoint
if self.alg.checkpoint_ready(self.train_count):
with self.lock:
if not self.alg.sync_weights:
_model = self.alg.save(self.model_path, save_count)
# fixme: weights to eval
full_model_name = [os.path.join(self.model_path, i) for i in _model]
else:
full_model_name = self.alg.get_weights()
if not self.alg.async_flag:
# logging.debug("put full_model_name: {}".format(full_model_name))
self._dist_model(dist_model_name=full_model_name, save_index=save_count)
# For Cloud
if self.s3_path is not None:
for name in full_model_name:
_model_name = os.path.split(name)[-1]
logging.debug(
"sync model:{} to s3:{}".format(_model_name, self.s3_path)
)
sync_data_to_s3(name, os.path.join(self.s3_path, _model_name))
save_count += 1
# we only eval saved model
# fixme: move evaluate logic inside the evaluator
if self.test_master:
self.test_master.call_if_eval(
full_model_name[0],
self.train_count,
self.actual_step,
self.logger.elapsed_time,
self.logger.train_reward,
loss,
)
eval_ret = self.test_master.fetch_eval_result()
if eval_ret:
logging.debug("eval stats: {}".format(eval_ret))
self.stats_deliver.send(
{"data": eval_ret, "is_bm": True}, block=True
)
if save_count % 1 == 0:
logging.debug("train count: {}".format(self.train_count))
self.stats_deliver.send(self.logger.get_new_info(), block=True)
def record_reward(self, train_data):
""" record reward in train """
broker_id = get_msg_info(train_data, 'broker_id')
explorer_id = get_msg_info(train_data, 'explorer_id')
agent_id = get_msg_info(train_data, 'agent_id')
key = (broker_id, explorer_id, agent_id)
self.alg.dist_model_policy.add_processed_ctr_info(key)
data_dict = get_msg_data(train_data)
# update multi agent train reward without done flag
if self.alg.alg_name in ("ppo_share_weights",):
self.actual_step += len(data_dict["done"])
self.logger.record(
step=self.actual_step,
train_reward=np.sum(data_dict["reward"]),
train_count=self.train_count,
)
return
elif self.alg.alg_name in ("QMixAlg", ): # fixme: unify the record op
self.actual_step += np.sum(data_dict["filled"])
self.won_in_episodes.append(data_dict.pop("battle_won"))
self.logger.update(explore_won_rate=np.nanmean(self.won_in_episodes))
self.logger.record(
step=self.actual_step,
train_reward=np.sum(data_dict["reward"]),
train_count=self.train_count,
)
return
if key not in self.actor_reward.keys():
self.actor_reward[key] = 0.0
data_length = len(data_dict["done"]) # fetch the train data length
for data_index in range(data_length):
reward = data_dict["reward"][data_index]
done = data_dict["done"][data_index]
info = data_dict["info"][data_index]
self.actual_step += 1
if isinstance(info, dict):
self.actor_reward[key] += info.get("eval_reward", reward)
done = info.get("real_done", done)
if done:
self.logger.record(
step=self.actual_step,
train_count=self.train_count,
train_reward=self.actor_reward[key],
)
self.actor_reward[key] = 0.0
class PredictThread(object):
def __init__(self, thread_id, alg, request_q, reply_q, stats_deliver, lock):
self.alg = alg
self.thread_id = thread_id
self.request_q = request_q
self.reply_q = reply_q
self.lock = lock
self.stats_deliver = stats_deliver
self._report_period = 200
self._stats = PredictStats()
def predict(self):
""" predict action """
while True:
start_t0 = time()
data = self.request_q.recv()
state = get_msg_data(data)
self._stats.obs_wait_time += time() - start_t0
start_t1 = time()
with self.lock:
action = self.alg.predict(state)
self._stats.inference_time += time() - start_t1
set_msg_info(data, cmd="predict_reply")
set_msg_data(data, action)
self.reply_q.send(data)
self._stats.iters += 1
if self._stats.iters > self._report_period:
_report = self._stats.get()
self.stats_deliver.send(_report, block=True)
def patch_alg_within_config(config):
"""combine the algorithm parameters"""
alg_para = config["alg_para"].copy()
agent_para = config["agent_para"]
model_info = config["model_para"]
node_config = config["node_config"]
# for quickly run 2s_vs_1sc map
env_attr = {
"state_shape": 27,
# obs_shape with been extend with action&agent id in algorithm!
"obs_shape": 17,
"n_actions": 7,
"n_agents": 2,
"episode_limit": 300,
"api_type": "standalone",
"agent_ids": [0],
}
if "alg_config" not in alg_para:
alg_para["alg_config"] = dict()
alg_para["alg_config"].update(
{
"instance_num": config["env_num"] * len(node_config),
"agent_num": agent_para.get("agent_num", 1),
"env_attr": env_attr,
}
)
config.update({"alg_para": alg_para})
# update env attr into model info
if "model_config" not in model_info["actor"].keys():
model_info["actor"].update({"model_config": dict()})
model_info["actor"]["model_config"].update(env_attr)
alg_para["model_info"] = model_info
return config
def setup_learner(config, test_master, data_url=None):
""" start learner """
env_para = config["env_para"]
agent_para = config["agent_para"]
alg_para = deepcopy(config["alg_para"])
model_info = alg_para["model_info"]
# set actor.type as learner
model_info["actor"].update({"type": "learner"})
# add benchmark id
bm_info = config.get("benchmark")
learner = Learner(
alg_para,
env_para,
agent_para,
test_master=test_master,
data_url=data_url,
benchmark_info=bm_info,
)
learner.config_info = config
return learner
|
Markdown-Image-Clipboard.py | # gui for starting and stopping the websocket client
# by oran collins
# github.com/wisehackermonkey
# oranbusiness@gmail.com
# 20210215
import os
import json
import time
import requests
import websocket
import pyperclip
from dotenv import load_dotenv
load_dotenv()
PUSHBULLET_API_KEY = os.getenv("PUSHBULLETAPI")
if not PUSHBULLET_API_KEY:
print("ERROR: please add PUSHBULLETAPI=<API KEY HERE> to your path")
exit()
# endpoint to check if a user has done anything, if so do a action "on_message(ws, message):"
pushbullet_websocket_api_url = f"wss://stream.pushbullet.com/websocket/{PUSHBULLET_API_KEY}"
# endpoint used to grab the image from the user
pushbullet_pushes_api_url = f"https://api.pushbullet.com/v2/pushes"
# api key is passed as a header for this endpoint
# headers = {"Access-Token": PUSHBULLET_API_KEY}
headers = {"Access-Token": PUSHBULLET_API_KEY,
"active":"true",
"limit": "1",
"modified_after":"0.0"}
last_push_timestap = 0.0# used for getting the most recent push
print(pushbullet_websocket_api_url)
# [python - How do you create a Tkinter GUI stop button to break an infinite loop? - Stack Overflow](https://stackoverflow.com/questions/27050492/how-do-you-create-a-tkinter-gui-stop-button-to-break-an-infinite-loop)
from tkinter import *
from threading import Thread
def scanning():
websocket.enableTrace(True)
global ws
ws = websocket.WebSocketApp(pushbullet_websocket_api_url,
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
def start_thread():
# Assign global variable and initialize value
global stop
stop = 0
# Create and launch a thread
t = Thread (target = scanning)
t.start()
def stop():
# Assign global variable and set value to stop
global stop
stop = 1
ws.close()
root = Tk()
root.title("Markdown-Image-Clipboard")
root.geometry("400x100")
app = Frame(root)
app.grid()
start = Button(app, text="Start Scan",command=start_thread)
stop = Button(app, text="Stop",command=stop)
start.grid()
stop.grid()
try:
import thread
except ImportError:
import _thread as thread
import time
def on_message(ws, message):
json_message = dict(json.loads(message))
print(f"Message: {message}")
if "subtype" in json_message:
# if json_message["subtype"] == "push":
print("grabbing pushed data")
latest_pushes = requests.get(pushbullet_pushes_api_url,headers=headers).json()
# # grab time stamp object
# pushes, *_ = latest_pushes
# created, *_ = pushes[0]
# [Pushbullet API](https://docs.pushbullet.com/v16/#pushes)
time_stamp = latest_pushes["pushes"][0]["created"]
image_url = latest_pushes["pushes"][0]["file_url"]
last_push_timestap = time_stamp
print(f"{time_stamp}, {last_push_timestap}, {image_url}")
print(latest_pushes)
mardown_formated_image = f""
pyperclip.copy(mardown_formated_image)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
def run(*args):
while True:
if stop == 1:
break
time.sleep(1)
# ws.send("Hello %d" % i)
print("waiting..")
time.sleep(1)
ws.close()
print("thread terminating...")
thread.start_new_thread(run, ())
app.mainloop()
# def start_websocket_client():
# if __name__ == "__main__":
# import tkinter as tk
# import threading
# import sys
# import os
# class App(threading.Thread):
# def __init__(self):
# threading.Thread.__init__(self)
# self.start()
# def close_window(self):
# self.root.quit()
# def play_tts(self):
# print("Playing")
# def restart(self):
# """Restarts the current program.
# Note: this function does not return. Any cleanup action (like
# saving data) must be done before calling this function."""
# print("Stopping")
# python = sys.executable
# os.execl(python, python, * sys.argv)
# def run(self):
# self.root = tk.Tk()
# # start application minimized
# self.root.iconify()
# # set window name
# self.root.title("Markdown Image Clipboard (pushbullet)")
# #set minimum window size
# self.root.minsize(400,100)
# # setup quit callback on windows close
# self.root.protocol("WM_DELETE_WINDOW", self.close_window)
# # Title text
# label = tk.Label(self.root, text="Markdown Image Clipboard (pushbullet)")
# label.pack()
# # TODO add pause button
# # Stop button
# button = tk.Button(self.root, justify="center", text="Stop", command=self.restart)
# button.pack()
# # Update app button
# self.menubar = tk.Menu(self.root)
# self.filemenu = tk.Menu(self.root,tearoff=0)
# self.filemenu.add_command(label="Update", command=check_for_update)
# self.filemenu.add_command(label="Exit", command=self.close_window)
# self.menubar.add_cascade(label="Options", menu=self.filemenu)
# # display the menu
# self.root.config(menu=self.menubar)
# # Quit button
# self.quit = tk.Button(self.root, text="Quit", command=self.root.quit)
# self.quit.pack(side="bottom")
# # Start of threaded main tkinter loop
# self.root.mainloop() |
p1.py | from multiprocessing import Process
numbers = [3, 4, 5, 6, 7, 8]
def cube(x):
for x in numbers:
print('%s cube is %s' % (x, x**3))
if __name__ == '__main__':
p1 = Process(target=cube, args=('x',))
p1.start()
p1.join()
print ("Exiting main") |
Test.py | import tkinter as tk
import threading
class App():
def __init__(self, master):
self.isrecording = False
self.button = tk.Button(main, text='rec')
self.button.bind("<Button-1>", self.startrecording)
self.button.bind("<ButtonRelease-1>", self.stoprecording)
self.button.pack()
def startrecording(self, event):
self.isrecording = True
t = threading.Thread(target=self._record)
t.start()
def stoprecording(self, event):
self.isrecording = False
def _record(self):
while self.isrecording:
print ("Recording")
main = tk.Tk()
app = App(main)
main.mainloop()
|
native.py | from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
nstr = str
str = type('')
import io
import os
import mmap
import errno
import struct
import warnings
from time import sleep
from threading import Thread, Event, Lock
from collections import Counter
from . import Pin, PINS_CLEANUP
from .data import pi_info
from ..exc import (
PinInvalidPull,
PinInvalidEdges,
PinInvalidFunction,
PinFixedPull,
PinSetInput,
PinNonPhysical,
PinNoPins,
)
class GPIOMemory(object):
GPIO_BASE_OFFSET = 0x200000
PERI_BASE_OFFSET = {
'BCM2708': 0x20000000,
'BCM2835': 0x20000000,
'BCM2709': 0x3f000000,
'BCM2836': 0x3f000000,
}
# From BCM2835 data-sheet, p.91
GPFSEL_OFFSET = 0x00 >> 2
GPSET_OFFSET = 0x1c >> 2
GPCLR_OFFSET = 0x28 >> 2
GPLEV_OFFSET = 0x34 >> 2
GPEDS_OFFSET = 0x40 >> 2
GPREN_OFFSET = 0x4c >> 2
GPFEN_OFFSET = 0x58 >> 2
GPHEN_OFFSET = 0x64 >> 2
GPLEN_OFFSET = 0x70 >> 2
GPAREN_OFFSET = 0x7c >> 2
GPAFEN_OFFSET = 0x88 >> 2
GPPUD_OFFSET = 0x94 >> 2
GPPUDCLK_OFFSET = 0x98 >> 2
def __init__(self):
try:
self.fd = os.open('/dev/gpiomem', os.O_RDWR | os.O_SYNC)
except OSError:
try:
self.fd = os.open('/dev/mem', os.O_RDWR | os.O_SYNC)
except OSError:
raise IOError(
'unable to open /dev/gpiomem or /dev/mem; '
'upgrade your kernel or run as root')
else:
offset = self.peripheral_base() + self.GPIO_BASE_OFFSET
else:
offset = 0
self.mem = mmap.mmap(self.fd, 4096, offset=offset)
def close(self):
self.mem.close()
os.close(self.fd)
def peripheral_base(self):
try:
with io.open('/proc/device-tree/soc/ranges', 'rb') as f:
f.seek(4)
return struct.unpack(nstr('>L'), f.read(4))[0]
except IOError:
with io.open('/proc/cpuinfo', 'r') as f:
for line in f:
if line.startswith('Hardware'):
try:
return self.PERI_BASE_OFFSET[line.split(':')[1].strip()]
except KeyError:
raise IOError('unable to determine RPi revision')
raise IOError('unable to determine peripheral base')
def __getitem__(self, index):
return struct.unpack_from(nstr('<L'), self.mem, index * 4)[0]
def __setitem__(self, index, value):
struct.pack_into(nstr('<L'), self.mem, index * 4, value)
class GPIOFS(object):
GPIO_PATH = '/sys/class/gpio'
def __init__(self):
self._lock = Lock()
self._pin_refs = Counter()
def path(self, name):
return os.path.join(self.GPIO_PATH, name)
def export(self, pin):
with self._lock:
if self._pin_refs[pin] == 0:
# Set the count to 1 to indicate the GPIO is already exported
# (we'll correct this if we find it isn't, but this enables us
# to "leave the system in the state we found it")
self._pin_refs[pin] = 1
result = None
# Dirty hack to wait for udev to set permissions on
# gpioN/direction; there's no other way around this as there's
# no synchronous mechanism for setting permissions on sysfs
for i in range(10):
try:
result = io.open(self.path('gpio%d/value' % pin), 'w+b', buffering=0)
except IOError as e:
if e.errno == errno.ENOENT:
with io.open(self.path('export'), 'wb') as f:
f.write(str(pin).encode('ascii'))
# Pin wasn't exported, so correct the ref-count
self._pin_refs[pin] = 0
elif e.errno == errno.EACCES:
sleep(i / 100)
else:
raise
else:
break
if not result:
raise RuntimeError('failed to export pin %d' % pin)
else:
result = io.open(self.path('gpio%d/value' % pin), 'w+b', buffering=0)
self._pin_refs[pin] += 1
return result
def unexport(self, pin):
with self._lock:
self._pin_refs[pin] -= 1
if self._pin_refs[pin] == 0:
with io.open(self.path('unexport'), 'wb') as f:
f.write(str(pin).encode('ascii'))
class NativePin(Pin):
"""
Uses a built-in pure Python implementation to interface to the Pi's GPIO
pins. This is the default pin implementation if no third-party libraries
are discovered.
.. warning::
This implementation does *not* currently support PWM. Attempting to
use any class which requests PWM will raise an exception. This
implementation is also experimental; we make no guarantees it will
not eat your Pi for breakfast!
You can construct native pin instances manually like so::
from gpiozero.pins.native import NativePin
from gpiozero import LED
led = LED(NativePin(12))
"""
_MEM = None
_PINS = {}
GPIO_FUNCTIONS = {
'input': 0b000,
'output': 0b001,
'alt0': 0b100,
'alt1': 0b101,
'alt2': 0b110,
'alt3': 0b111,
'alt4': 0b011,
'alt5': 0b010,
}
GPIO_PULL_UPS = {
'up': 0b10,
'down': 0b01,
'floating': 0b00,
'reserved': 0b11,
}
GPIO_EDGES = {
'both': (True, True),
'rising': (True, False),
'falling': (False, True),
'none': (False, False),
}
GPIO_FUNCTION_NAMES = {v: k for (k, v) in GPIO_FUNCTIONS.items()}
GPIO_PULL_UP_NAMES = {v: k for (k, v) in GPIO_PULL_UPS.items()}
GPIO_EDGES_NAMES = {v: k for (k, v) in GPIO_EDGES.items()}
PI_INFO = None
def __new__(cls, number):
if not cls._PINS:
cls._MEM = GPIOMemory()
PINS_CLEANUP.append(cls._MEM.close)
if cls.PI_INFO is None:
cls.PI_INFO = pi_info()
if not (0 <= number < 54):
raise ValueError('invalid pin %d specified (must be 0..53)' % number)
try:
return cls._PINS[number]
except KeyError:
self = super(NativePin, cls).__new__(cls)
try:
cls.PI_INFO.physical_pin('GPIO%d' % number)
except PinNoPins:
warnings.warn(
PinNonPhysical(
'no physical pins exist for GPIO%d' % number))
self._number = number
self._func_offset = self._MEM.GPFSEL_OFFSET + (number // 10)
self._func_shift = (number % 10) * 3
self._set_offset = self._MEM.GPSET_OFFSET + (number // 32)
self._set_shift = number % 32
self._clear_offset = self._MEM.GPCLR_OFFSET + (number // 32)
self._clear_shift = number % 32
self._level_offset = self._MEM.GPLEV_OFFSET + (number // 32)
self._level_shift = number % 32
self._pull_offset = self._MEM.GPPUDCLK_OFFSET + (number // 32)
self._pull_shift = number % 32
self._edge_offset = self._MEM.GPEDS_OFFSET + (number // 32)
self._edge_shift = number % 32
self._rising_offset = self._MEM.GPREN_OFFSET + (number // 32)
self._rising_shift = number % 32
self._falling_offset = self._MEM.GPFEN_OFFSET + (number // 32)
self._falling_shift = number % 32
self._when_changed = None
self._change_thread = None
self._change_event = Event()
self.function = 'input'
self.pull = 'up' if cls.PI_INFO.pulled_up('GPIO%d' % number) else 'floating'
self.bounce = None
self.edges = 'both'
cls._PINS[number] = self
return self
def __repr__(self):
return "GPIO%d" % self._number
@property
def number(self):
return self._number
def close(self):
self.when_changed = None
self.function = 'input'
self.pull = 'up' if self.PI_INFO.pulled_up('GPIO%d' % self.number) else 'floating'
def _get_function(self):
return self.GPIO_FUNCTION_NAMES[(self._MEM[self._func_offset] >> self._func_shift) & 7]
def _set_function(self, value):
try:
value = self.GPIO_FUNCTIONS[value]
except KeyError:
raise PinInvalidFunction('invalid function "%s" for pin %r' % (value, self))
self._MEM[self._func_offset] = (
self._MEM[self._func_offset]
& ~(7 << self._func_shift)
| (value << self._func_shift)
)
def _get_state(self):
return bool(self._MEM[self._level_offset] & (1 << self._level_shift))
def _set_state(self, value):
if self.function == 'input':
raise PinSetInput('cannot set state of pin %r' % self)
if value:
self._MEM[self._set_offset] = 1 << self._set_shift
else:
self._MEM[self._clear_offset] = 1 << self._clear_shift
def _get_pull(self):
return self.GPIO_PULL_UP_NAMES[self._pull]
def _set_pull(self, value):
if self.function != 'input':
raise PinFixedPull('cannot set pull on non-input pin %r' % self)
if value != 'up' and self.PI_INFO.pulled_up('GPIO%d' % self.number):
raise PinFixedPull('%r has a physical pull-up resistor' % self)
try:
value = self.GPIO_PULL_UPS[value]
except KeyError:
raise PinInvalidPull('invalid pull direction "%s" for pin %r' % (value, self))
self._MEM[self._MEM.GPPUD_OFFSET] = value
sleep(0.000000214)
self._MEM[self._pull_offset] = 1 << self._pull_shift
sleep(0.000000214)
self._MEM[self._MEM.GPPUD_OFFSET] = 0
self._MEM[self._pull_offset] = 0
self._pull = value
def _get_edges(self):
rising = bool(self._MEM[self._rising_offset] & (1 << self._rising_shift))
falling = bool(self._MEM[self._falling_offset] & (1 << self._falling_shift))
return self.GPIO_EDGES_NAMES[(rising, falling)]
def _set_edges(self, value):
try:
rising, falling = self.GPIO_EDGES[value]
except KeyError:
raise PinInvalidEdges('invalid edge specification "%s" for pin %r' % self)
f = self.when_changed
self.when_changed = None
try:
self._MEM[self._rising_offset] = (
self._MEM[self._rising_offset]
& ~(1 << self._rising_shift)
| (rising << self._rising_shift)
)
self._MEM[self._falling_offset] = (
self._MEM[self._falling_offset]
& ~(1 << self._falling_shift)
| (falling << self._falling_shift)
)
finally:
self.when_changed = f
def _get_when_changed(self):
return self._when_changed
def _set_when_changed(self, value):
if self._when_changed is None and value is not None:
self._when_changed = value
self._change_thread = Thread(target=self._change_watch)
self._change_thread.daemon = True
self._change_event.clear()
self._change_thread.start()
elif self._when_changed is not None and value is None:
self._change_event.set()
self._change_thread.join()
self._change_thread = None
self._when_changed = None
else:
self._when_changed = value
def _change_watch(self):
offset = self._edge_offset
mask = 1 << self._edge_shift
self._MEM[offset] = mask # clear any existing detection bit
while not self._change_event.wait(0.001):
if self._MEM[offset] & mask:
self._MEM[offset] = mask
self._when_changed()
|
test_threadlocal.py | # coding: utf-8
import threading, logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)-8s %(filename)s:%(lineno)-4d: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
local_school = threading.local()
def process_student():
# 获取当前线程关联的student
std = local_school.student
print('Hello, %s (in %s)' % (std, threading.current_thread().name))
def process_thread(name):
# 绑定ThreadLocal的student:
local_school.student = name
process_student()
# t1 = threading.Thread(target=process_thread, args=('Alice',), name='Thread-A')
# t2 = threading.Thread(target=process_thread, args=('Bob',), name='Thread-B')
# t1.start()
# t2.start()
# t1.join()
# t2.join()
student = dict()
def process_thread2(name):
student[threading.current_thread()] = name
process_student2()
def process_student2():
name = student[threading.current_thread()]
print('Hello, %s (in %s)' % (name, threading.current_thread().name))
t1 = threading.Thread(target=process_thread2, args=('Alice',), name='Thread-A')
t2 = threading.Thread(target=process_thread2, args=('Bob',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()
|
heleus.py | #!/usr/bin/env python3
import argparse
import asyncio
import bz2
import datetime
import logging
import os
import platform
import sys
import threading
import time
import uuid
from concurrent.futures import TimeoutError, ThreadPoolExecutor
from hashlib import sha256
import aredis
import dill
import discord
from discord import utils as dutils
from discord.ext import commands
from utils.storage import RedisCollection
class NoResponse:
def __repr__(self):
return '<NoResponse>'
def __eq__(self, other):
if isinstance(other, NoResponse):
return True
else:
return False
def create_bot(auto_shard: bool):
cls = commands.AutoShardedBot if auto_shard else commands.Bot
class Heleus(cls):
def __init__(self, *args, **kwargs):
self.redis = kwargs.pop('redis', None)
self.name = kwargs.pop('name', 'Heleus')
if self.redis is None:
raise AssertionError('No redis instance specified')
self.test = kwargs.pop('test', False)
self.args = kwargs.pop('cargs', None)
self.boot_time = time.time() # for uptime tracking, we'll use this later
# used for keeping track of *this* instance over reboots
self.instance_id = sha256(
f'{platform.node()}_{os.getcwd()}_{self.args.shard_id}_{self.args.shard_count}'.encode()).hexdigest()
self.logger = logging.getLogger('heleus')
self.logger.info('Heleus is booting, please wait...')
self.settings = RedisCollection(self.redis, 'settings')
self.owner = [] # this gets updated in on_ready
self.invite_url = None # this too
self.team = None # and this
self.send_cmd_help = send_cmd_help
self.send_command_help = send_cmd_help # seems more like a method name discord.py would choose
self.self_bot = kwargs.get('self_bot', False)
db = str(self.redis.connection_pool.connection_kwargs['db'])
self.pubsub_id = f'heleus.{db}.pubsub.code'
self._pubsub_futures = {} # futures temporarily stored here
self._pubsub_broadcast_cache = {}
self._pubsub_pool = ThreadPoolExecutor(max_workers=1)
self.t1 = threading.Thread(name='pubsub cache', target=self._pubsub_cache_loop, daemon=True)
if load_cogs is not None:
self.autoload = load_cogs.split(',')
else:
self.autoload = None
super().__init__(*args, **kwargs)
self.ready = False # we expect the loader to set this once ready
async def init(self):
"""Initializes the bot."""
# pubsub
self.t1.start()
# self.loop.create_task(self._pubsub_loop())
# load the core cog
default = 'cogs.core'
loader = await self.settings.get('loader', default)
self.load_extension(loader)
if loader != default:
self.logger.warning(f'Using third-party loader and core cog, {loader}.')
def _process_pubsub_event(self, event):
_id = self.pubsub_id
if event['type'] != 'message':
return
try:
_data = dill.loads(event['data'])
target = _data.get('target')
broadcast = target == 'all'
if not isinstance(_data, dict):
return
# get type, if this is a broken dict just ignore it
if _data.get('type') is None:
return
# ping response
if target == self.shard_id or broadcast:
if _data['type'] == 'ping':
self.redis.publish(_id, dill.dumps({'type': 'response', 'id': _data.get('id'),
'response': 'Pong.'}))
if _data['type'] == 'coderequest':
func = _data.get('function') # get the function, discard if None
if func is None:
return
resp = {'type': 'response', 'id': _data.get('id'), 'response': None}
if broadcast:
resp['from'] = self.shard_id
args = _data.get('args', ())
kwargs = _data.get('kwargs', {})
try:
# noinspection PyCallingNonCallable
resp['response'] = func(self, *args, **kwargs) # this gets run in a thread so whatever
except Exception as e:
resp['response'] = e
try:
self.redis.publish(_id, dill.dumps(resp))
except dill.PicklingError: # if the response fails to dill, return None instead
resp = {'type': 'response', 'id': _data.get('id')}
if broadcast:
resp['from'] = self.shard_id
self.redis.publish(_id, dill.dumps(resp))
if _data['type'] == 'response':
__id = _data.get('id')
_from = _data.get('from')
if __id is None:
return
if __id not in self._pubsub_futures:
return
if __id not in self._pubsub_broadcast_cache and _from is not None:
return
if _from is None:
self._pubsub_futures[__id].set_result(_data.get('response'))
del self._pubsub_futures[__id]
else:
self._pubsub_broadcast_cache[__id][_from] = _data.get('response')
except dill.UnpicklingError:
return
async def _pubsub_loop(self):
pubsub = self.redis.pubsub()
_id = self.pubsub_id
pubsub.subscribe(_id)
async for event in pubsub.listen():
self._pubsub_pool.submit(self._process_pubsub_event, event)
def _pubsub_cache_loop(self):
while True:
for k, v in dict(self._pubsub_broadcast_cache).items():
contents = [v[x] for x in v if x != 'expires']
if v['expires'] < time.monotonic() or NoResponse() not in contents:
del v['expires']
self._pubsub_futures[k].set_result(v)
del self._pubsub_futures[k]
del self._pubsub_broadcast_cache[k]
time.sleep(0.01) # be nice to the host
def request(self, target, broadcast_timeout=1, **kwargs):
_id = str(uuid.uuid4())
self._pubsub_futures[_id] = fut = asyncio.Future()
request = {'id': _id, 'target': target}
request.update(kwargs)
if target == 'all':
cache = {k: NoResponse() for k in range(0, self.shard_count)} # prepare the cache
cache['expires'] = time.monotonic() + broadcast_timeout
self._pubsub_broadcast_cache[_id] = cache
self.redis.publish(self.pubsub_id, dill.dumps(request))
return fut
async def run_on_shard(self, shard, func, *args, **kwargs):
return await self.request(shard, type='coderequest', function=func, args=args, kwargs=kwargs)
async def ping_shard(self, shard, timeout=1):
try:
await asyncio.wait_for(self.request(shard, type='ping'), timeout=timeout)
return True
except TimeoutError:
return False
async def on_ready(self):
await self.redis.set('__info__',
f'This database is used by the Heleus Discord bot, logged in as user {self.user}.')
self.logger.info('Heleus is connected!')
self.logger.info(f'Logged in as {self.user}.')
if self.shard_id is not None:
self.logger.info(f'Shard {self.shard_id + 1} of {self.shard_count}.')
if self.user.bot:
app_info = await self.application_info()
self.invite_url = dutils.oauth_url(app_info.id)
self.logger.info(f'Invite URL: {self.invite_url}')
self.team = app_info.team
if self.team:
for member in self.team.members:
if member.membership_state == discord.TeamMembershipState.accepted:
self.owner.append(member)
else:
self.owner = [app_info.owner]
elif self.self_bot:
self.owner = [self.user]
else:
self.owner = [self.get_user(self.args.userbot)]
if self.test:
self.logger.info('Test complete, logging out...')
await self.logout()
exit(0) # jenkins' little helper
async def on_message(self, message):
pass
def __repr__(self):
return '<Heleus username={} shard_id={} shard_count={}>'.format(
*[repr(x) for x in [self.user.name, self.shard_id, self.shard_count]])
return Heleus
async def send_cmd_help(ctx):
ctx.invoked_with = 'help'
if ctx.invoked_subcommand:
await ctx.send_help(ctx.invoked_subcommand)
else:
await ctx.send_help(ctx.command)
if __name__ == '__main__':
# Get defaults for argparse
help_description = os.environ.get('HELEUS_HELP', 'Heleus, an open-source Discord bot maintained by DerpyChap, '
'forked from Liara by Pandentia and contributors\n'
'https://github.com/nerdcubed/Heleus')
runtime_name = os.environ.get('HELEUS_NAME', 'Heleus')
token = os.environ.get('HELEUS_TOKEN', None)
redis_host = os.environ.get('HELEUS_REDIS_HOST', 'localhost')
redis_pass = os.environ.get('HELEUS_REDIS_PASSWORD', None)
try:
redis_port = int(os.environ.get('HELEUS_REDIS_PORT', 6379))
redis_db = int(os.environ.get('HELEUS_REDIS_DB', 0))
except ValueError:
print('Error parsing environment variables HELEUS_REDIS_PORT or HELEUS_REDIS_DB\n'
'Please check that these can be converted to integers')
exit(4)
shard_id = os.environ.get('HELEUS_SHARD_ID', None)
shard_count = os.environ.get('HELEUS_SHARD_COUNT', None)
try:
if shard_id is not None:
shard_id = int(shard_id)
if shard_count is not None:
shard_count = int(shard_count)
except ValueError:
print('Error parsing environment variables HELEUS_SHARD_ID or HELEUS_SHARD_COUNT\n'
'Please check that these can be converted to integers')
exit(4)
message_cache = os.environ.get('HELEUS_MESSAGE_CACHE_COUNT', 5000)
try:
if message_cache is not None:
message_cache = int(message_cache)
except ValueError:
print('Error parsing environment variable HELEUS_MESSAGE_CACHE_COUNT\n'
'Please check that this can be converted to an integer')
exit(4)
load_cogs = os.environ.get('HELEUS_LOAD_COGS', None)
intents = os.environ.get('HELEUS_INTENTS', 'all')
# Parse command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--description', type=str, help='modify the bot description shown in the help command',
default=help_description)
parser.add_argument('--name', type=str, help='allows for white labeling Heleus', default=runtime_name)
parser.add_argument('--selfbot', help='enables selfbot mode', action='store_true')
parser.add_argument('--userbot', help='enables userbot mode, with the specified owner ID', type=int, default=None)
parser.add_argument('--debug', help=argparse.SUPPRESS, action='store_true')
parser.add_argument('--test', help=argparse.SUPPRESS, action='store_true')
parser.add_argument('--message_cache_count', help='sets the maximum amount of messages to cache in Heleus.messages',
default=message_cache, type=int)
parser.add_argument('--uvloop', help='enables uvloop mode', action='store_true')
parser.add_argument('--stateless', help='disables file storage', action='store_true')
parser.add_argument('--cogs', help='a comma separated list of cogs to automatically load on startup',
default=load_cogs)
parser.add_argument('--intents', help='a comma separated list of Gateway Intents to enable', default=intents)
parser.add_argument('token', type=str, help='sets the token', default=token, nargs='?')
shard_grp = parser.add_argument_group('sharding')
# noinspection PyUnboundLocalVariable
shard_grp.add_argument('--shard_id', type=int, help='the shard ID the bot should run on', default=shard_id)
# noinspection PyUnboundLocalVariable
shard_grp.add_argument('--shard_count', type=int, help='the total number of shards you are planning to run',
default=shard_count)
redis_grp = parser.add_argument_group('redis')
redis_grp.add_argument('--host', type=str, help='the Redis host', default=redis_host)
# noinspection PyUnboundLocalVariable
redis_grp.add_argument('--port', type=int, help='the Redis port', default=redis_port)
# noinspection PyUnboundLocalVariable
redis_grp.add_argument('--db', type=int, help='the Redis database', default=redis_db)
redis_grp.add_argument('--password', type=str, help='the Redis password', default=redis_pass)
cargs = parser.parse_args()
if cargs.token is None:
exit(parser.print_usage())
if cargs.userbot is None:
userbot = False
else:
userbot = True
if cargs.selfbot and userbot:
exit(parser.print_usage())
if cargs.uvloop:
try:
# noinspection PyUnresolvedReferences
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
print('uvloop is not installed!')
exit(1)
if not cargs.stateless:
# Logging starts here
# Create directory for logs if it doesn't exist
if not os.path.exists('logs'):
os.mkdir('logs')
# Compress logfiles that were left over from the last run
os.chdir('logs')
if not os.path.exists('old'):
os.mkdir('old')
for item in os.listdir('.'):
if item.endswith('.log'):
with bz2.open(item + '.bz2', 'w') as f:
f.write(open(item, 'rb').read())
os.remove(item)
for item in os.listdir('.'):
if item.endswith('.gz') or item.endswith('.bz2'):
os.rename(item, 'old/' + item)
os.chdir('..')
# Define a format
now = str(datetime.datetime.now()).replace(' ', '_').replace(':', '-').split('.')[0]
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
# Setting up loggers
logger = logging.getLogger('heleus')
if cargs.debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
if not cargs.stateless:
handler = logging.FileHandler(f'logs/heleus_{now}.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)
discord_logger = logging.getLogger('discord')
if cargs.debug:
discord_logger.setLevel(logging.DEBUG)
else:
discord_logger.setLevel(logging.INFO)
if not cargs.stateless:
handler = logging.FileHandler(f'logs/discord_{now}.log')
handler.setFormatter(formatter)
discord_logger.addHandler(handler)
if cargs.intents:
intents_list = cargs.intents.split(',')
if 'all' in intents_list:
intents = discord.Intents.all()
else:
if 'default' in intents_list:
intents = discord.Intents.default()
intents_list.remove('default')
else:
try:
intents_list.remove('none')
except ValueError:
pass
intents = discord.Intents.none()
for i in intents_list:
if not hasattr(intents, i):
logger.warning(f'{i} is not a valid Gateway Intent.')
else:
setattr(intents, i, True)
else:
intents = discord.Intents.none()
if not intents.guilds:
logger.warning('Running without the guilds intent is not recommend and is not officially supported. '
'You have been warned!')
def is_docker():
path = '/proc/self/cgroup'
return os.path.exists('/.dockerenv') or os.path.isfile(path) and any('docker' in line for line in open(path))
if not is_docker():
logger.warning(
'Running outside of a Docker container, while should work with the right setup, is not officially '
'supported. DO NOT expect any support if things go wrong. You\'ve been warned!')
if cargs.shard_id is not None: # usability
cargs.shard_id -= 1
# Redis connection attempt
redis_conn = aredis.StrictRedis(host=cargs.host, port=cargs.port, db=cargs.db, password=cargs.password)
# sharding logic
unsharded = True
if cargs.shard_id is not None:
unsharded = False
if cargs.userbot:
unsharded = False
if cargs.selfbot:
unsharded = False
heleus_cls = create_bot(unsharded)
# if we want to make an auto-reboot loop now, it would be a hell of a lot easier now
# noinspection PyUnboundLocalVariable
heleus = heleus_cls('!', load_cogs=cargs.cogs, intents=intents, shard_id=cargs.shard_id,
shard_count=cargs.shard_count, description=cargs.description, self_bot=cargs.selfbot,
pm_help=None, max_messages=message_cache, redis=redis_conn, cargs=cargs,
test=cargs.test, name=cargs.name) # heleus-specific args
async def run_bot():
await heleus.redis.ping()
await heleus.init()
await heleus.login(cargs.token, bot=not (cargs.selfbot or userbot))
await heleus.connect()
# noinspection PyBroadException
def run_app():
loop = asyncio.get_event_loop()
exit_code = 0
try:
loop.run_until_complete(run_bot())
except KeyboardInterrupt:
logger.info('Shutting down threads and quitting. Thank you for using Heleus.')
loop.run_until_complete(heleus.logout())
except aredis.ConnectionError:
exit_code = 2
logger.critical('Unable to connect to Redis.')
except discord.LoginFailure:
exit_code = 3
logger.critical('Discord token is not valid.')
except Exception:
exit_code = 1
logger.exception('Exception while running Heleus.')
loop.run_until_complete(heleus.logout())
finally:
loop.close()
return exit_code
exit(run_app())
|
test__threading_monkey_in_thread.py | # We can monkey-patch in a thread, but things don't work as expected.
from __future__ import print_function
import threading
from gevent import monkey
import gevent.testing as greentest
class Test(greentest.TestCase):
@greentest.ignores_leakcheck # can't be run multiple times
def test_patch_in_thread(self):
all_warnings = []
try:
get_ident = threading.get_ident
except AttributeError:
get_ident = threading._get_ident
def process_warnings(warnings):
all_warnings.extend(warnings)
monkey._process_warnings = process_warnings
current = threading.current_thread()
current_id = get_ident()
def target():
tcurrent = threading.current_thread()
monkey.patch_all() # pragma: testrunner-no-monkey-combine
tcurrent2 = threading.current_thread()
self.assertIsNot(tcurrent, current)
# We get a dummy thread now
self.assertIsNot(tcurrent, tcurrent2)
thread = threading.Thread(target=target)
thread.start()
try:
thread.join()
except: # pylint:disable=bare-except
# XXX: This can raise LoopExit in some cases.
greentest.reraiseFlakyTestRaceCondition()
self.assertNotIsInstance(current, threading._DummyThread)
self.assertIsInstance(current, monkey.get_original('threading', 'Thread'))
# We generated some warnings
if greentest.PY3:
self.assertEqual(all_warnings,
['Monkey-patching outside the main native thread. Some APIs will not be '
'available. Expect a KeyError to be printed at shutdown.',
'Monkey-patching not on the main thread; threading.main_thread().join() '
'will hang from a greenlet'])
else:
self.assertEqual(all_warnings,
['Monkey-patching outside the main native thread. Some APIs will not be '
'available. Expect a KeyError to be printed at shutdown.'])
# Manual clean up so we don't get a KeyError
del threading._active[current_id]
threading._active[(getattr(threading, 'get_ident', None) or threading._get_ident)()] = current
if __name__ == '__main__':
greentest.main()
|
list_generator.py | #!/bin/python3
# executing this script will generate a lot of errors, ignore them
# errors in threads only close the thread that got the error
from dns import resolver
from threading import Thread
from ipaddress import ip_address
from urllib.request import urlretrieve as download
res = resolver.Resolver(configure=False)
res.nameservers = [
'1.1.1.1', '1.0.0.1', '2606:4700:4700::1111', '2606:4700:4700::1001', #Cloudflare
'8.8.8.8', '8.8.4.4', '2001:4860:4860::8888', '2001:4860:4860::8844', #Google Public DNS
'208.67.222.222', '208.67.220.220', '2620:0:ccc::2', '2620:0:ccd::2', #OpenDNS
'209.244.0.3', '209.244.0.4', #Level 3
'64.6.64.6', '64.6.65.6', '2620:74:1b::1:1', '2620:74:1c::2:2', #Verisign
'9.9.9.9', '149.112.112.112', '2620:fe::fe', '2620:fe::9', #Quad9
'8.26.56.26', '8.20.247.20', #Comodo Secure DNS
'84.200.69.80', '84.200.70.40', '2001:1608:10:25::1c04:b12f', '2001:1608:10:25::9249:d69b', #DNS.WATCH
'199.85.126.10', '199.85.127.10', #Norton ConnectSafe
'81.218.119.11', '209.88.198.133', #GreenTeamDNS
'195.46.39.39', '195.46.39.40', #SafeDNS
'185.121.177.177', '169.239.202.202', '2a05:dfc7:5::53', '2a05:dfc7:5353::53', #OpenNIC
'208.76.50.50', '208.76.51.51', #SmartViper
'80.80.80.80', '80.80.81.81', #Freenom World
'216.146.35.35', '216.146.36.36', #Dyn
'37.235.1.174', '37.235.1.177', #FreeDNS
'198.101.242.72', '23.253.163.53', #Alternate DNS
'77.88.8.8', '77.88.8.1', '2a02:6b8::feed:0ff', '2a02:6b8:0:1::feed:0ff', #Yandex.DNS
'91.239.100.100', '89.233.43.71', '2001:67c:28a4::', '2a01:3a0:53:53::', #UncensoredDNS
'74.82.42.42', '2001:470:20::2', #Hurricane Electric
'109.69.8.51', '2a00:1508:0:4::9', #puntCAT
'156.154.70.1', '156.154.71.1', '2610:a1:1018::1', '2610:a1:1019::1', #Neustar
'1.2.4.8', '210.2.4.8', #CNNIC SDNS
'240c::6666', '240c::6644', #CFIEC IPv6 Public DNS
'223.5.5.5', '223.6.6.6', #AliDNS
'180.76.76.76', '2400:da00::6666', #Baidu Public DNS
'119.29.29.29', '119.28.28.28', #DNSPod Public DNS+
'114.114.114.114', '114.114.115.115', #114DNS
'117.50.11.11', '117.50.22.22', #OneDNS
'101.226.4.6', '218.30.118.6', #DNSpai
# '94.140.14.14', '94.140.15.15', '2a10:50c0::ad1:ff', '2a10:50c0::ad2:ff', #AdGuard DNS Default
# '94.140.14.15', '94.140.15.16', '2a10:50c0::bad1:ff', '2a10:50c0::bad2:ff', #AdGuard DNS Family protection
'94.140.14.140', '94.140.14.141', '2a10:50c0::1:ff', '2a10:50c0::2:ff', #AdGuard DNS Non-filtering
'45.90.28.167', '45.90.30.167', '2a07:a8c0::82:86df', '2a07:a8c1::82:86df' #NextDNS
]
# make a list of ips
ipv4List = []
ipv6List = []
# make a list of Threads
taskList = []
def fetch_ip(URL, Query, List):
# get ips
ips = res.resolve(URL, Query)
ips = [str(i) for i in ips]
# print ips format 'example.com IN A [192.0.2.1, ...]'
print(URL, 'IN', Query, ips)
# append the ips for listing
List += ips
# download youtubeparsed
download('https://raw.githubusercontent.com/nickspaargaren/no-google/master/categories/youtubeparsed', 'youtubeparsed')
# keep previous ips
with open('ipv4_list.txt', mode = 'r', encoding = 'utf-8') as f:
for ip in f.readlines():
ip = ip.strip()
try:
ip = str( ip_address( ip ) )
ipv4List.append( ip )
except ValueError:
if ip != '':
print('%s is not a valid IPv4 address!' % ip)
with open('ipv6_list.txt', mode = 'r', encoding = 'utf-8') as f:
for ip in f.readlines():
ip = ip.strip()
try:
ip = str( ip_address( ip ) )
ipv6List.append( ip )
except ValueError:
if ip != '':
print('%s is not a valid IPv6 address!' % ip)
# de-duplicate list entries
ipv4List = list( set( ipv4List ) )
ipv6List = list( set( ipv6List ) )
# count and remember the number of previous entries
previousIpv4s = len(ipv4List)
previousIpv6s = len(ipv6List)
# open the youtubeparsed file
with open('youtubeparsed', mode = 'r', encoding = 'utf-8') as f:
# for each url in the file
for url in f.readlines():
# strip whitespaces and '.'
url = url.strip()
# ignore empty lines
if url == '':
continue
# ignore if the line starts with '#'
if url.startswith('#'):
continue
# make a thread for each fetch_ip call
taskList.append(Thread(target=fetch_ip, args=(url, 'A', ipv4List)))
taskList.append(Thread(target=fetch_ip, args=(url, 'AAAA', ipv6List)))
"""
# start the tasks in threads
threads = 16
taskNumber = len(taskList)
for i in range(0, taskNumber, threads):
for j in range(i, min(i + threads, taskNumber)):
taskList[j].start()
for j in range(i, min(i + threads, taskNumber)):
taskList[j].join()
"""
# start the tasks all at once
for t in taskList:
t.start()
# and wait for them to finish
for t in taskList:
t.join()
# de-duplicate list entries
ipv4List = list( set( ipv4List ) )
ipv6List = list( set( ipv6List ) )
# calculate and print changes
print('Read', previousIpv4s, 'ipv4\'s from ipv4_list.txt')
print('Number of new ipv4 addresses found:', len(ipv4List) - previousIpv4s)
print('Read', previousIpv6s, 'ipv6\'s from ipv6_list.txt')
print('Number of new ipv6 addresses found:', len(ipv6List) - previousIpv6s)
# read the files again. usefull for running the script in background.
with open('ipv4_list.txt', mode = 'r', encoding = 'utf-8') as f:
for ip in f.readlines():
ip = ip.strip()
try:
ip = str( ip_address( ip ) )
ipv4List.append( ip )
except ValueError:
if ip != '':
print('%s is not a valid IPv4 address!' % ip)
with open('ipv6_list.txt', mode = 'r', encoding = 'utf-8') as f:
for ip in f.readlines():
ip = ip.strip()
try:
ip = str( ip_address( ip ) )
ipv6List.append( ip )
except ValueError:
if ip != '':
print('%s is not a valid IPv6 address!' % ip)
# de-duplicate list entries and sort them
ipv4List = list( set( ipv4List ) )
ipv6List = list( set( ipv6List ) )
ipv4List.sort(key=ip_address)
ipv6List.sort(key=ip_address)
# now write the ips in files
with open('ipv4_list.txt', mode = 'w', encoding = 'utf-8') as f:
f.write('\n'.join(ipv4List) + '\n')
with open('ipv6_list.txt', mode = 'w', encoding = 'utf-8') as f:
f.write('\n'.join(ipv6List) + '\n')
|
wallet_multiwallet.py | #!/usr/bin/env python3
# Copyright (c) 2017-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test multiwallet.
Verify that a bsvcoind node can load multiple wallet files
"""
from decimal import Decimal
from threading import Thread
import os
import shutil
import stat
import time
from test_framework.authproxy import JSONRPCException
from test_framework.test_framework import BsvcoinTestFramework
from test_framework.test_node import ErrorMatch
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
get_rpc_proxy,
)
got_loading_error = False
def test_load_unload(node, name):
global got_loading_error
while True:
if got_loading_error:
return
try:
node.loadwallet(name)
node.unloadwallet(name)
except JSONRPCException as e:
if e.error['code'] == -4 and 'Wallet already loading' in e.error['message']:
got_loading_error = True
return
class MultiWalletTest(BsvcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
self.rpc_timeout = 120
self.extra_args = [["-nowallet"], []]
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def add_options(self, parser):
parser.add_argument(
'--data_wallets_dir',
default=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/wallets/'),
help='Test data with wallet directories (default: %(default)s)',
)
def run_test(self):
node = self.nodes[0]
data_dir = lambda *p: os.path.join(node.datadir, self.chain, *p)
wallet_dir = lambda *p: data_dir('wallets', *p)
wallet = lambda name: node.get_wallet_rpc(name)
def wallet_file(name):
if name == self.default_wallet_name:
return wallet_dir(self.default_wallet_name, self.wallet_data_filename)
if os.path.isdir(wallet_dir(name)):
return wallet_dir(name, "wallet.dat")
return wallet_dir(name)
assert_equal(self.nodes[0].listwalletdir(), {'wallets': [{'name': self.default_wallet_name}]})
# check wallet.dat is created
self.stop_nodes()
assert_equal(os.path.isfile(wallet_dir(self.default_wallet_name, self.wallet_data_filename)), True)
# create symlink to verify wallet directory path can be referenced
# through symlink
os.mkdir(wallet_dir('w7'))
os.symlink('w7', wallet_dir('w7_symlink'))
os.symlink('..', wallet_dir('recursive_dir_symlink'))
os.mkdir(wallet_dir('self_walletdat_symlink'))
os.symlink('wallet.dat', wallet_dir('self_walletdat_symlink/wallet.dat'))
# rename wallet.dat to make sure plain wallet file paths (as opposed to
# directory paths) can be loaded
# create another dummy wallet for use in testing backups later
self.start_node(0)
node.createwallet("empty")
node.createwallet("plain")
node.createwallet("created")
self.stop_nodes()
empty_wallet = os.path.join(self.options.tmpdir, 'empty.dat')
os.rename(wallet_file("empty"), empty_wallet)
shutil.rmtree(wallet_dir("empty"))
empty_created_wallet = os.path.join(self.options.tmpdir, 'empty.created.dat')
os.rename(wallet_dir("created", self.wallet_data_filename), empty_created_wallet)
shutil.rmtree(wallet_dir("created"))
os.rename(wallet_file("plain"), wallet_dir("w8"))
shutil.rmtree(wallet_dir("plain"))
# restart node with a mix of wallet names:
# w1, w2, w3 - to verify new wallets created when non-existing paths specified
# w - to verify wallet name matching works when one wallet path is prefix of another
# sub/w5 - to verify relative wallet path is created correctly
# extern/w6 - to verify absolute wallet path is created correctly
# w7_symlink - to verify symlinked wallet path is initialized correctly
# w8 - to verify existing wallet file is loaded correctly. Not tested for SQLite wallets as this is a deprecated BDB behavior.
# '' - to verify default wallet file is created correctly
to_create = ['w1', 'w2', 'w3', 'w', 'sub/w5', 'w7_symlink']
in_wallet_dir = [w.replace('/', os.path.sep) for w in to_create] # Wallets in the wallet dir
in_wallet_dir.append('w7') # w7 is not loaded or created, but will be listed by listwalletdir because w7_symlink
to_create.append(os.path.join(self.options.tmpdir, 'extern/w6')) # External, not in the wallet dir, so we need to avoid adding it to in_wallet_dir
to_load = [self.default_wallet_name]
if not self.options.descriptors:
to_load.append('w8')
wallet_names = to_create + to_load # Wallet names loaded in the wallet
in_wallet_dir += to_load # The loaded wallets are also in the wallet dir
self.start_node(0)
for wallet_name in to_create:
self.nodes[0].createwallet(wallet_name)
for wallet_name in to_load:
self.nodes[0].loadwallet(wallet_name)
os.mkdir(wallet_dir('no_access'))
os.chmod(wallet_dir('no_access'), 0)
try:
with self.nodes[0].assert_debug_log(expected_msgs=['Error scanning']):
walletlist = self.nodes[0].listwalletdir()['wallets']
finally:
# Need to ensure access is restored for cleanup
os.chmod(wallet_dir('no_access'), stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
assert_equal(sorted(map(lambda w: w['name'], walletlist)), sorted(in_wallet_dir))
assert_equal(set(node.listwallets()), set(wallet_names))
# should raise rpc error if wallet path can't be created
err_code = -4 if self.options.descriptors else -1
assert_raises_rpc_error(err_code, "boost::filesystem::create_directory:", self.nodes[0].createwallet, "w8/bad")
# check that all requested wallets were created
self.stop_node(0)
for wallet_name in wallet_names:
assert_equal(os.path.isfile(wallet_file(wallet_name)), True)
self.nodes[0].assert_start_raises_init_error(['-walletdir=wallets'], 'Error: Specified -walletdir "wallets" does not exist')
self.nodes[0].assert_start_raises_init_error(['-walletdir=wallets'], 'Error: Specified -walletdir "wallets" is a relative path', cwd=data_dir())
self.nodes[0].assert_start_raises_init_error(['-walletdir=debug.log'], 'Error: Specified -walletdir "debug.log" is not a directory', cwd=data_dir())
self.start_node(0, ['-wallet=w1', '-wallet=w1'])
self.stop_node(0, 'Warning: Ignoring duplicate -wallet w1.')
if not self.options.descriptors:
# Only BDB doesn't open duplicate wallet files. SQLite does not have this limitation. While this may be desired in the future, it is not necessary
# should not initialize if one wallet is a copy of another
shutil.copyfile(wallet_dir('w8'), wallet_dir('w8_copy'))
in_wallet_dir.append('w8_copy')
exp_stderr = r"BerkeleyDatabase: Can't open database w8_copy \(duplicates fileid \w+ from w8\)"
self.nodes[0].assert_start_raises_init_error(['-wallet=w8', '-wallet=w8_copy'], exp_stderr, match=ErrorMatch.PARTIAL_REGEX)
# should not initialize if wallet file is a symlink
os.symlink('w8', wallet_dir('w8_symlink'))
self.nodes[0].assert_start_raises_init_error(['-wallet=w8_symlink'], r'Error: Invalid -wallet path \'w8_symlink\'\. .*', match=ErrorMatch.FULL_REGEX)
# should not initialize if the specified walletdir does not exist
self.nodes[0].assert_start_raises_init_error(['-walletdir=bad'], 'Error: Specified -walletdir "bad" does not exist')
# should not initialize if the specified walletdir is not a directory
not_a_dir = wallet_dir('notadir')
open(not_a_dir, 'a', encoding="utf8").close()
self.nodes[0].assert_start_raises_init_error(['-walletdir=' + not_a_dir], 'Error: Specified -walletdir "' + not_a_dir + '" is not a directory')
self.log.info("Do not allow -upgradewallet with multiwallet")
self.nodes[0].assert_start_raises_init_error(['-upgradewallet'], "Error: Error parsing command line arguments: Invalid parameter -upgradewallet")
# if wallets/ doesn't exist, datadir should be the default wallet dir
wallet_dir2 = data_dir('walletdir')
os.rename(wallet_dir(), wallet_dir2)
self.start_node(0)
self.nodes[0].createwallet("w4")
self.nodes[0].createwallet("w5")
assert_equal(set(node.listwallets()), {"w4", "w5"})
w5 = wallet("w5")
node.generatetoaddress(nblocks=1, address=w5.getnewaddress())
# now if wallets/ exists again, but the rootdir is specified as the walletdir, w4 and w5 should still be loaded
os.rename(wallet_dir2, wallet_dir())
self.restart_node(0, ['-nowallet', '-walletdir=' + data_dir()])
self.nodes[0].loadwallet("w4")
self.nodes[0].loadwallet("w5")
assert_equal(set(node.listwallets()), {"w4", "w5"})
w5 = wallet("w5")
w5_info = w5.getwalletinfo()
assert_equal(w5_info['immature_balance'], 50)
competing_wallet_dir = os.path.join(self.options.tmpdir, 'competing_walletdir')
os.mkdir(competing_wallet_dir)
self.restart_node(0, ['-nowallet', '-walletdir=' + competing_wallet_dir])
self.nodes[0].createwallet(self.default_wallet_name)
if self.options.descriptors:
exp_stderr = r"Error: SQLiteDatabase: Unable to obtain an exclusive lock on the database, is it being used by another bsvcoind?"
else:
exp_stderr = r"Error: Error initializing wallet database environment \"\S+competing_walletdir\S*\"!"
self.nodes[1].assert_start_raises_init_error(['-walletdir=' + competing_wallet_dir], exp_stderr, match=ErrorMatch.PARTIAL_REGEX)
self.restart_node(0)
for wallet_name in wallet_names:
self.nodes[0].loadwallet(wallet_name)
assert_equal(sorted(map(lambda w: w['name'], self.nodes[0].listwalletdir()['wallets'])), sorted(in_wallet_dir))
wallets = [wallet(w) for w in wallet_names]
wallet_bad = wallet("bad")
# check wallet names and balances
node.generatetoaddress(nblocks=1, address=wallets[0].getnewaddress())
for wallet_name, wallet in zip(wallet_names, wallets):
info = wallet.getwalletinfo()
assert_equal(info['immature_balance'], 50 if wallet is wallets[0] else 0)
assert_equal(info['walletname'], wallet_name)
# accessing invalid wallet fails
assert_raises_rpc_error(-18, "Requested wallet does not exist or is not loaded", wallet_bad.getwalletinfo)
# accessing wallet RPC without using wallet endpoint fails
assert_raises_rpc_error(-19, "Wallet file not specified", node.getwalletinfo)
w1, w2, w3, w4, *_ = wallets
node.generatetoaddress(nblocks=101, address=w1.getnewaddress())
assert_equal(w1.getbalance(), 100)
assert_equal(w2.getbalance(), 0)
assert_equal(w3.getbalance(), 0)
assert_equal(w4.getbalance(), 0)
w1.sendtoaddress(w2.getnewaddress(), 1)
w1.sendtoaddress(w3.getnewaddress(), 2)
w1.sendtoaddress(w4.getnewaddress(), 3)
node.generatetoaddress(nblocks=1, address=w1.getnewaddress())
assert_equal(w2.getbalance(), 1)
assert_equal(w3.getbalance(), 2)
assert_equal(w4.getbalance(), 3)
batch = w1.batch([w1.getblockchaininfo.get_request(), w1.getwalletinfo.get_request()])
assert_equal(batch[0]["result"]["chain"], self.chain)
assert_equal(batch[1]["result"]["walletname"], "w1")
self.log.info('Check for per-wallet settxfee call')
assert_equal(w1.getwalletinfo()['paytxfee'], 0)
assert_equal(w2.getwalletinfo()['paytxfee'], 0)
w2.settxfee(0.001)
assert_equal(w1.getwalletinfo()['paytxfee'], 0)
assert_equal(w2.getwalletinfo()['paytxfee'], Decimal('0.00100000'))
self.log.info("Test dynamic wallet loading")
self.restart_node(0, ['-nowallet'])
assert_equal(node.listwallets(), [])
assert_raises_rpc_error(-18, "No wallet is loaded. Load a wallet using loadwallet or create a new one with createwallet. (Note: A default wallet is no longer automatically created)", node.getwalletinfo)
self.log.info("Load first wallet")
loadwallet_name = node.loadwallet(wallet_names[0])
assert_equal(loadwallet_name['name'], wallet_names[0])
assert_equal(node.listwallets(), wallet_names[0:1])
node.getwalletinfo()
w1 = node.get_wallet_rpc(wallet_names[0])
w1.getwalletinfo()
self.log.info("Load second wallet")
loadwallet_name = node.loadwallet(wallet_names[1])
assert_equal(loadwallet_name['name'], wallet_names[1])
assert_equal(node.listwallets(), wallet_names[0:2])
assert_raises_rpc_error(-19, "Wallet file not specified", node.getwalletinfo)
w2 = node.get_wallet_rpc(wallet_names[1])
w2.getwalletinfo()
self.log.info("Concurrent wallet loading")
threads = []
for _ in range(3):
n = node.cli if self.options.usecli else get_rpc_proxy(node.url, 1, timeout=600, coveragedir=node.coverage_dir)
t = Thread(target=test_load_unload, args=(n, wallet_names[2]))
t.start()
threads.append(t)
for t in threads:
t.join()
global got_loading_error
assert_equal(got_loading_error, True)
self.log.info("Load remaining wallets")
for wallet_name in wallet_names[2:]:
loadwallet_name = self.nodes[0].loadwallet(wallet_name)
assert_equal(loadwallet_name['name'], wallet_name)
assert_equal(set(self.nodes[0].listwallets()), set(wallet_names))
# Fail to load if wallet doesn't exist
path = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets", "wallets")
assert_raises_rpc_error(-18, "Wallet file verification failed. Failed to load database path '{}'. Path does not exist.".format(path), self.nodes[0].loadwallet, 'wallets')
# Fail to load duplicate wallets
path = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets", "w1", "wallet.dat")
if self.options.descriptors:
assert_raises_rpc_error(-4, "Wallet file verification failed. SQLiteDatabase: Unable to obtain an exclusive lock on the database, is it being used by another bsvcoind?", self.nodes[0].loadwallet, wallet_names[0])
else:
assert_raises_rpc_error(-35, "Wallet file verification failed. Refusing to load database. Data file '{}' is already loaded.".format(path), self.nodes[0].loadwallet, wallet_names[0])
# This tests the default wallet that BDB makes, so SQLite wallet doesn't need to test this
# Fail to load duplicate wallets by different ways (directory and filepath)
path = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets", "wallet.dat")
assert_raises_rpc_error(-35, "Wallet file verification failed. Refusing to load database. Data file '{}' is already loaded.".format(path), self.nodes[0].loadwallet, 'wallet.dat')
# Only BDB doesn't open duplicate wallet files. SQLite does not have this limitation. While this may be desired in the future, it is not necessary
# Fail to load if one wallet is a copy of another
assert_raises_rpc_error(-4, "BerkeleyDatabase: Can't open database w8_copy (duplicates fileid", self.nodes[0].loadwallet, 'w8_copy')
# Fail to load if one wallet is a copy of another, test this twice to make sure that we don't re-introduce #14304
assert_raises_rpc_error(-4, "BerkeleyDatabase: Can't open database w8_copy (duplicates fileid", self.nodes[0].loadwallet, 'w8_copy')
# Fail to load if wallet file is a symlink
assert_raises_rpc_error(-4, "Wallet file verification failed. Invalid -wallet path 'w8_symlink'", self.nodes[0].loadwallet, 'w8_symlink')
# Fail to load if a directory is specified that doesn't contain a wallet
os.mkdir(wallet_dir('empty_wallet_dir'))
path = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets", "empty_wallet_dir")
assert_raises_rpc_error(-18, "Wallet file verification failed. Failed to load database path '{}'. Data is not in recognized format.".format(path), self.nodes[0].loadwallet, 'empty_wallet_dir')
self.log.info("Test dynamic wallet creation.")
# Fail to create a wallet if it already exists.
path = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets", "w2")
assert_raises_rpc_error(-4, "Failed to create database path '{}'. Database already exists.".format(path), self.nodes[0].createwallet, 'w2')
# Successfully create a wallet with a new name
loadwallet_name = self.nodes[0].createwallet('w9')
in_wallet_dir.append('w9')
assert_equal(loadwallet_name['name'], 'w9')
w9 = node.get_wallet_rpc('w9')
assert_equal(w9.getwalletinfo()['walletname'], 'w9')
assert 'w9' in self.nodes[0].listwallets()
# Successfully create a wallet using a full path
new_wallet_dir = os.path.join(self.options.tmpdir, 'new_walletdir')
new_wallet_name = os.path.join(new_wallet_dir, 'w10')
loadwallet_name = self.nodes[0].createwallet(new_wallet_name)
assert_equal(loadwallet_name['name'], new_wallet_name)
w10 = node.get_wallet_rpc(new_wallet_name)
assert_equal(w10.getwalletinfo()['walletname'], new_wallet_name)
assert new_wallet_name in self.nodes[0].listwallets()
self.log.info("Test dynamic wallet unloading")
# Test `unloadwallet` errors
assert_raises_rpc_error(-1, "JSON value is not a string as expected", self.nodes[0].unloadwallet)
assert_raises_rpc_error(-18, "Requested wallet does not exist or is not loaded", self.nodes[0].unloadwallet, "dummy")
assert_raises_rpc_error(-18, "Requested wallet does not exist or is not loaded", node.get_wallet_rpc("dummy").unloadwallet)
assert_raises_rpc_error(-8, "RPC endpoint wallet and wallet_name parameter specify different wallets", w1.unloadwallet, "w2"),
# Successfully unload the specified wallet name
self.nodes[0].unloadwallet("w1")
assert 'w1' not in self.nodes[0].listwallets()
# Unload w1 again, this time providing the wallet name twice
self.nodes[0].loadwallet("w1")
assert 'w1' in self.nodes[0].listwallets()
w1.unloadwallet("w1")
assert 'w1' not in self.nodes[0].listwallets()
# Successfully unload the wallet referenced by the request endpoint
# Also ensure unload works during walletpassphrase timeout
w2.encryptwallet('test')
w2.walletpassphrase('test', 1)
w2.unloadwallet()
time.sleep(1.1)
assert 'w2' not in self.nodes[0].listwallets()
# Successfully unload all wallets
for wallet_name in self.nodes[0].listwallets():
self.nodes[0].unloadwallet(wallet_name)
assert_equal(self.nodes[0].listwallets(), [])
assert_raises_rpc_error(-18, "No wallet is loaded. Load a wallet using loadwallet or create a new one with createwallet. (Note: A default wallet is no longer automatically created)", self.nodes[0].getwalletinfo)
# Successfully load a previously unloaded wallet
self.nodes[0].loadwallet('w1')
assert_equal(self.nodes[0].listwallets(), ['w1'])
assert_equal(w1.getwalletinfo()['walletname'], 'w1')
assert_equal(sorted(map(lambda w: w['name'], self.nodes[0].listwalletdir()['wallets'])), sorted(in_wallet_dir))
# Test backing up and restoring wallets
self.log.info("Test wallet backup")
self.restart_node(0, ['-nowallet'])
for wallet_name in wallet_names:
self.nodes[0].loadwallet(wallet_name)
for wallet_name in wallet_names:
rpc = self.nodes[0].get_wallet_rpc(wallet_name)
addr = rpc.getnewaddress()
backup = os.path.join(self.options.tmpdir, 'backup.dat')
if os.path.exists(backup):
os.unlink(backup)
rpc.backupwallet(backup)
self.nodes[0].unloadwallet(wallet_name)
shutil.copyfile(empty_created_wallet if wallet_name == self.default_wallet_name else empty_wallet, wallet_file(wallet_name))
self.nodes[0].loadwallet(wallet_name)
assert_equal(rpc.getaddressinfo(addr)['ismine'], False)
self.nodes[0].unloadwallet(wallet_name)
shutil.copyfile(backup, wallet_file(wallet_name))
self.nodes[0].loadwallet(wallet_name)
assert_equal(rpc.getaddressinfo(addr)['ismine'], True)
# Test .walletlock file is closed
self.start_node(1)
wallet = os.path.join(self.options.tmpdir, 'my_wallet')
self.nodes[0].createwallet(wallet)
if self.options.descriptors:
assert_raises_rpc_error(-4, "Unable to obtain an exclusive lock", self.nodes[1].loadwallet, wallet)
else:
assert_raises_rpc_error(-4, "Error initializing wallet database environment", self.nodes[1].loadwallet, wallet)
self.nodes[0].unloadwallet(wallet)
self.nodes[1].loadwallet(wallet)
if __name__ == '__main__':
MultiWalletTest().main()
|
statreload.py | import os
import signal
import sys
import time
import multiprocessing
HANDLED_SIGNALS = (
signal.SIGINT, # Unix signal 2. Sent by Ctrl+C.
signal.SIGTERM, # Unix signal 15. Sent by `kill <pid>`.
)
class StatReload:
def __init__(self, logger):
self.logger = logger
self.should_exit = False
self.mtimes = {}
def handle_exit(self, sig, frame):
self.should_exit = True
def run(self, target, kwargs):
pid = os.getpid()
self.logger.info("Started reloader process [{}]".format(pid))
for sig in HANDLED_SIGNALS:
signal.signal(sig, self.handle_exit)
process = multiprocessing.Process(target=target, kwargs=kwargs)
process.start()
while process.is_alive() and not self.should_exit:
time.sleep(0.2)
if self.should_restart():
self.clear()
os.kill(process.pid, signal.SIGTERM)
process.join()
process = multiprocessing.Process(target=target, kwargs=kwargs)
process.start()
self.logger.info("Stopping reloader process [{}]".format(pid))
sys.exit(process.exitcode)
def clear(self):
self.mtimes = {}
def should_restart(self):
for filename in self.iter_py_files():
try:
mtime = os.stat(filename).st_mtime
except OSError as exc:
continue
old_time = self.mtimes.get(filename)
if old_time is None:
self.mtimes[filename] = mtime
continue
elif mtime > old_time:
message = "Detected file change in '%s'. Reloading..."
self.logger.warning(message, filename)
return True
return False
def iter_py_files(self):
for subdir, dirs, files in os.walk("."):
for file in files:
filepath = subdir + os.sep + file
if filepath.endswith(".py"):
yield filepath
|
example19.py | """
扩展性系统性能
- 垂直扩展 - 增加单节点处理能力
- 水平扩展 - 将单节点变成多节点(读写分离/分布式集群)
并发编程 - 加速程序执行 / 改善用户体验
耗时间的任务都尽可能独立的执行,不要阻塞代码的其他部分
- 多线程
1. 创建Thread对象指定target和args属性并通过start方法启动线程
2. 继承Thread类并重写run方法来定义线程执行的任务
3. 创建线程池对象ThreadPoolExecutor并通过submit来提交要执行的任务
第3种方式可以通过Future对象的result方法在将来获得线程的执行结果
也可以通过done方法判定线程是否执行结束
- 多进程
- 异步I/O
"""
import glob
import os
import time
from concurrent.futures import ThreadPoolExecutor
from threading import Thread
from PIL import Image
# class ThumbnailThread(Thread):
# def __init__(self, infile):
# self.infile = infile
# super().__init__()
# def run(self):
# file, ext = os.path.splitext(self.infile)
# filename = file[file.rfind('/') + 1:]
# for size in (32, 64, 128):
# outfile = f'thumbnails/{filename}_{size}_{size}.png'
# image = Image.open(self.infile)
# image.thumbnail((size, size))
# image.save(outfile, format='PNG')
def gen_thumbnail(infile):
file, ext = os.path.splitext(infile)
filename = file[file.rfind('/') + 1:]
for size in (32, 64, 128):
outfile = f'thumbnails/{filename}_{size}_{size}.png'
image = Image.open(infile)
image.thumbnail((size, size))
image.save(outfile, format='PNG')
# def main():
# start = time.time()
# threads = []
# for infile in glob.glob('images/*'):
# # t = Thread(target=gen_thumbnail, args=(infile, ))
# t = ThumbnailThread(infile)
# t.start()
# threads.append(t)
# for t in threads:
# t.join()
# end = time.time()
# print(f'耗时: {end - start}秒')
def main():
pool = ThreadPoolExecutor(max_workers=30)
futures = []
start = time.time()
for infile in glob.glob('images/*'):
# submit方法是非阻塞式的方法
# 即便工作线程数已经用完,submit方法也会接受提交的任务
future = pool.submit(gen_thumbnail, infile)
futures.append(future)
for future in futures:
# result方法是一个阻塞式的方法 如果线程还没有结束
# 暂时取不到线程的执行结果 代码就会在此处阻塞
future.result()
end = time.time()
print(f'耗时: {end - start}秒')
# shutdown也是非阻塞式的方法 但是如果已经提交的任务还没有执行完
# 线程池是不会停止工作的 shutdown之后再提交任务就不会执行而且会产生异常
pool.shutdown()
if __name__ == '__main__':
main()
|
worker_manager.py | """
A manager for multiple workers.
-- kandasamy@cs.cmu.edu
"""
# pylint: disable=abstract-class-little-used
# pylint: disable=invalid-name
# pylint: disable=no-member
from argparse import Namespace
from multiprocessing import Process
import numpy as np
import os
from sets import Set
import shutil
import time
# Local
from opt.function_caller import EVAL_ERROR_CODE
TIME_TOL = 1e-5
class WorkerManager(object):
""" A Base class for a worker manager. """
def __init__(self, worker_ids, poll_time):
""" Constructor. """
if hasattr(worker_ids, '__iter__'):
self.worker_ids = worker_ids
else:
self.worker_ids = list(range(worker_ids))
self.num_workers = len(self.worker_ids)
self.poll_time = poll_time
# These will be set in reset
self.optimiser = None
self.latest_results = None
# Reset
self.reset()
def reset(self):
""" Resets everything. """
self.optimiser = None
self.latest_results = [] # A list of namespaces
self._child_reset()
def _child_reset(self):
""" Child reset. """
raise NotImplementedError('Implement in a child class.')
def fetch_latest_results(self):
""" Returns the latest results. """
ret_idxs = []
for i in range(len(self.latest_results)):
if (self.latest_results[i].receive_time <=
self.optimiser.get_curr_spent_capital() + TIME_TOL):
ret_idxs.append(i)
keep_idxs = [i for i in range(len(self.latest_results)) if i not in ret_idxs]
ret = [self.latest_results[i] for i in ret_idxs]
self.latest_results = [self.latest_results[i] for i in keep_idxs]
return ret
def close_all_jobs(self):
""" Closes all jobs. """
raise NotImplementedError('Implement in a child class.')
def set_optimiser(self, optimiser):
""" Set the optimiser. """
self.optimiser = optimiser
def a_worker_is_free(self):
""" Returns true if a worker is free. """
raise NotImplementedError('Implement in a child class.')
def all_workers_are_free(self):
""" Returns true if all workers are free. """
raise NotImplementedError('Implement in a child class.')
def _dispatch_evaluation(self, func_caller, point, qinfo):
""" Dispatches job. """
raise NotImplementedError('Implement in a child class.')
def dispatch_single_evaluation(self, func_caller, point, qinfo):
""" Dispatches job. """
raise NotImplementedError('Implement in a child class.')
def dispatch_batch_of_evaluations(self, func_caller, points, qinfos):
""" Dispatches an entire batch of evaluations. """
raise NotImplementedError('Implement in a child class.')
def get_time_distro_info(self):
""" Returns information on the time distribution. """
#pylint: disable=no-self-use
return ''
# A synthetic worker manager - for simulating multiple workers ---------------------------
class SyntheticWorkerManager(WorkerManager):
""" A Worker manager for synthetic functions. Mostly to be used in simulations. """
def __init__(self, num_workers, time_distro='const', time_distro_params=None):
""" Constructor. """
self.worker_pipe = None
super(SyntheticWorkerManager, self).__init__(num_workers, poll_time=None)
# Set up the time sampler
self.time_distro = time_distro
self.time_distro_params = time_distro_params
self.time_sampler = None
self._set_up_time_sampler()
def _set_up_time_sampler(self):
""" Set up the sampler for the time random variable. """
self.time_distro_params = Namespace() if self.time_distro_params is None else \
self.time_distro_params
if self.time_distro == 'const':
if not hasattr(self.time_distro_params, 'const_val'):
self.time_distro_params.const_val = 1
self.time_sampler = lambda num_samples: (np.ones((num_samples,)) *
self.time_distro_params.const_val)
elif self.time_distro == 'uniform':
if not hasattr(self.time_distro_params, 'ub'):
self.time_distro_params.ub = 2.0
self.time_distro_params.lb = 0.0
ub = self.time_distro_params.ub
lb = self.time_distro_params.lb
self.time_sampler = lambda num_samples: (np.random.random((num_samples,)) *
(ub - lb) + lb)
elif self.time_distro == 'halfnormal':
if not hasattr(self.time_distro_params, 'ub'):
self.time_distro_params.sigma = np.sqrt(np.pi/2)
self.time_sampler = lambda num_samples: np.abs(np.random.normal(
scale=self.time_distro_params.sigma, size=(num_samples,)))
else:
raise NotImplementedError('Not implemented time_distro = %s yet.'%(
self.time_distro))
def _child_reset(self):
""" Child reset. """
self.worker_pipe = [[wid, 0.0] for wid in self.worker_ids]
def sort_worker_pipe(self):
""" Sorts worker pipe by finish time. """
self.worker_pipe.sort(key=lambda x: x[-1])
def a_worker_is_free(self):
""" Returns true if a worker is free. """
return self.worker_pipe[0][-1] # Always return true as this is synthetic.
def all_workers_are_free(self):
""" Returns true if all workers are free. """
return self.worker_pipe[-1][-1]
def close_all_jobs(self):
""" Close all jobs. """
pass
def _dispatch_evaluation(self, func_caller, point, qinfo, worker_id, **kwargs):
""" Dispatch evaluation. """
qinfo.worker_id = worker_id # indicate which worker
val, qinfo = func_caller.eval_single(point, qinfo, **kwargs)
qinfo.eval_time = float(self.time_sampler(1))
qinfo.val = val
qinfo.receive_time = qinfo.send_time + qinfo.eval_time
# Store the result in latest_results
self.latest_results.append(qinfo)
return qinfo
def dispatch_single_evaluation(self, func_caller, point, qinfo, **kwargs):
""" Dispatch a single evaluation. """
worker_id = self.worker_pipe[0][0]
qinfo = self._dispatch_evaluation(func_caller, point, qinfo, worker_id, **kwargs)
# Sort the pipe
self.worker_pipe[0][-1] = qinfo.receive_time
self.sort_worker_pipe()
def dispatch_batch_of_evaluations(self, func_caller, points, qinfos, **kwargs):
""" Dispatches an entire batch of evaluations. """
assert len(points) == self.num_workers
for idx in range(self.num_workers):
qinfo = self._dispatch_evaluation(func_caller, points[idx], qinfos[idx],
self.worker_pipe[idx][0], **kwargs)
self.worker_pipe[idx][-1] = qinfo.receive_time
self.sort_worker_pipe()
def get_time_distro_info(self):
""" Returns information on the time distribution. """
return self.time_distro
# Real worker manager - for simulating multiple workers --------------------------------
class RealWorkerManager(WorkerManager):
""" A worker manager for resnet. """
# pylint: disable=attribute-defined-outside-init
def __init__(self, worker_ids, tmp_dir, poll_time=0.5):
""" Constructor. """
super(RealWorkerManager, self).__init__(worker_ids, poll_time)
self.tmp_dir = tmp_dir
self._rwm_set_up()
self._child_reset()
def _rwm_set_up(self):
""" Sets things up for the child. """
# Create the result directories. """
self.result_dir_names = {wid:'%s/result_%s'%(self.tmp_dir, str(wid)) for wid in
self.worker_ids}
# Create the working directories
self.working_dir_names = {wid:'%s/working_%s/tmp'%(self.tmp_dir, str(wid)) for wid in
self.worker_ids}
# Create the last receive times
self.last_receive_times = {wid:0.0 for wid in self.worker_ids}
# Create file names
self._result_file_name = 'result.txt'
self._num_file_read_attempts = 10
@classmethod
def _delete_dirs(cls, list_of_dir_names):
""" Deletes a list of directories. """
for dir_name in list_of_dir_names:
if os.path.exists(dir_name):
shutil.rmtree(dir_name)
@classmethod
def _delete_and_create_dirs(cls, list_of_dir_names):
""" Deletes a list of directories and creates new ones. """
for dir_name in list_of_dir_names:
if os.path.exists(dir_name):
shutil.rmtree(dir_name)
os.makedirs(dir_name)
def _child_reset(self):
""" Resets child. """
# Delete/create the result and working directories.
if not hasattr(self, 'result_dir_names'): # Just for the super constructor.
return
self._delete_and_create_dirs(self.result_dir_names.values())
self._delete_dirs(self.working_dir_names.values())
self.free_workers = Set(self.worker_ids)
self.qinfos_in_progress = {wid:None for wid in self.worker_ids}
self.worker_processes = {wid:None for wid in self.worker_ids}
def _get_result_file_name_for_worker(self, worker_id):
""" Computes the result file name for the worker. """
return os.path.join(self.result_dir_names[worker_id], self._result_file_name)
def _read_result_from_file(self, result_file_name):
""" Reads the result from the file name. """
#pylint: disable=bare-except
num_attempts = 0
while num_attempts < self._num_file_read_attempts:
try:
file_reader = open(result_file_name, 'r')
read_in = file_reader.read().strip()
try:
# try converting to float. If not successful, it is likely an error string.
read_in = float(read_in)
except:
pass
file_reader.close()
result = read_in
break
except:
time.sleep(self.poll_time)
file_reader.close()
result = EVAL_ERROR_CODE
return result
def _read_result_from_worker_and_update(self, worker_id):
""" Reads the result from the worker. """
# Read the file
result_file_name = self._get_result_file_name_for_worker(worker_id)
val = self._read_result_from_file(result_file_name)
# Now update the relevant qinfo and put it to latest_results
qinfo = self.qinfos_in_progress[worker_id]
qinfo.val = val
if not hasattr(qinfo, 'true_val'):
qinfo.true_val = val
qinfo.receive_time = self.optimiser.get_curr_spent_capital()
qinfo.eval_time = qinfo.receive_time - qinfo.send_time
self.latest_results.append(qinfo)
# Update receive time
self.last_receive_times[worker_id] = qinfo.receive_time
# Delete the file.
os.remove(result_file_name)
# Delete content in a working directory.
shutil.rmtree(self.working_dir_names[worker_id])
# Add the worker to the list of free workers and clear qinfos in progress.
self.worker_processes[worker_id].terminate()
self.worker_processes[worker_id] = None
self.qinfos_in_progress[worker_id] = None
self.free_workers.add(worker_id)
def _worker_is_free(self, worker_id):
""" Checks if worker with worker_id is free. """
if worker_id in self.free_workers:
return True
worker_result_file_name = self._get_result_file_name_for_worker(worker_id)
if os.path.exists(worker_result_file_name):
self._read_result_from_worker_and_update(worker_id)
else:
return False
def _get_last_receive_time(self):
""" Returns the last time we received a job. """
all_receive_times = self.last_receive_times.values()
return max(all_receive_times)
def a_worker_is_free(self):
""" Returns true if a worker is free. """
for wid in self.worker_ids:
if self._worker_is_free(wid):
return self._get_last_receive_time()
return None
def all_workers_are_free(self):
""" Returns true if all workers are free. """
all_are_free = True
for wid in self.worker_ids:
all_are_free = self._worker_is_free(wid) and all_are_free
if all_are_free:
return self._get_last_receive_time()
else:
return None
def _dispatch_evaluation(self, func_caller, point, qinfo, worker_id, **kwargs):
""" Dispatches evaluation to worker_id. """
#pylint: disable=star-args
if self.qinfos_in_progress[worker_id] is not None:
err_msg = 'qinfos_in_progress: %s,\nfree_workers: %s.'%(
str(self.qinfos_in_progress), str(self.free_workers))
print err_msg
raise ValueError('Check if worker is free before sending evaluation.')
# First add all the data to qinfo
qinfo.worker_id = worker_id
qinfo.working_dir = self.working_dir_names[worker_id]
qinfo.result_file = self._get_result_file_name_for_worker(worker_id)
qinfo.point = point
# Create the working directory
os.makedirs(qinfo.working_dir)
# Dispatch the evaluation in a new process
target_func = lambda: func_caller.eval_single(point, qinfo, **kwargs)
self.worker_processes[worker_id] = Process(target=target_func)
self.worker_processes[worker_id].start()
time.sleep(3)
# Add the qinfo to the in progress bar and remove from free_workers
self.qinfos_in_progress[worker_id] = qinfo
self.free_workers.discard(worker_id)
def dispatch_single_evaluation(self, func_caller, point, qinfo, **kwargs):
""" Dispatches a single evaluation to a free worker. """
worker_id = self.free_workers.pop()
self._dispatch_evaluation(func_caller, point, qinfo, worker_id, **kwargs)
def dispatch_batch_of_evaluations(self, func_caller, points, qinfos, **kwargs):
""" Dispatches a batch of evaluations. """
assert len(points) == self.num_workers
for idx in range(self.num_workers):
self._dispatch_evaluation(func_caller, points[idx], qinfos[idx],
self.worker_ids[idx], **kwargs)
def close_all_jobs(self):
""" Closes all jobs. """
pass
def get_time_distro_info(self):
""" Returns information on the time distribution. """
return 'realtime'
|
Excel2db.py | # -*- coding: utf-8 -*-
# @Time : 2019/1/27 下午4:11
# @Author : shiwei-Du
# @Email : dusw0214@126.com
# @File : Excel2db.py
# @Software: PyCharm
import sys
import pandas as pd
from sqlalchemy import create_engine
import configparser
import threading
import argparse
import os
from lib.Log import Log
config = configparser.ConfigParser()
config.read('config/define.ini')
dbconfig = config['MYSQL']
handle = "%s+%s://%s:%s@%s:%s/%s?charset=%s" % (dbconfig['DIALECT'], dbconfig['DRIVER'], dbconfig['USER'],
dbconfig['PASSWORD'], dbconfig['HOST'], dbconfig['PORT'],
dbconfig['DBNAME'], dbconfig['CHARSET'])
engine = create_engine(handle)
class Excel2db(Log):
def __init__(self):
Log.__init__(self)
self.path = config.get('EXCEL_CONFIG', 'SOURCE_PATH')
self.back_path = config.get('EXCEL_CONFIG', 'BACKUPS_PATH')
def load_in_by_table(self, table:str):
try:
df = pd.read_excel(self.path + table + '.xls', index_col=None)
except Exception as e:
msg = 'Read %s Error, Error is:%s' % (table, str(e))
self.error(msg)
return
try:
chunksize = dbconfig['CHUNKSIZE']
if chunksize != 'None':
chunksize = int(dbconfig['CHUNKSIZE'])
else:
chunksize = None
df.to_sql(table, engine, if_exists=dbconfig['IF_EXISTS'], index=0, chunksize=chunksize)
except Exception as e:
msg = 'import %s Error, Error is:%s' % (table, str(e))
self.error(msg)
return
self.info('Table:% s Success load In' % table)
return True
def load_out_by_table(self, table:str):
try:
df = pd.read_sql_table(table, engine)
except Exception as e:
self.info('Select %s Error, Error is:%s' % (table, str(e)))
return
try:
df.to_excel(self.back_path + table + ".xls")
except Exception as e:
self.error('import %s Error, Error is:%s' % (table, str(e)))
return
self.info('Table:% s Success load out' % table)
return True
def get_all_table_names(self):
try:
sql = "select table_name from information_schema.TABLES where TABLE_SCHEMA='%s' ;" % dbconfig['DBNAME']
df = pd.read_sql(sql, engine)
except Exception as e:
self.error('Error is:%s' % (str(e)))
return
return [table[0] for table in df.values]
def get_all_files_name(self):
try:
tables = []
if not os.path.exists(self.path):
self.error('Source Path Not Exists!!!')
pass
for file in os.listdir(self.path):
if file.endswith(".xls"):
table=file[:-4]
tables.append(table)
except Exception as e:
self.error('Scan %s Error, Error is: %s' % (self.path, str(e)))
return
return tables
def load_out_all(self):
all_tables = self.get_all_table_names()
if all_tables:
self.create_thread(all_tables, self.load_out_by_table)
def load_in_all(self):
all_tables = self.get_all_files_name()
# print(all_tables)
if all_tables:
self.create_thread(all_tables, self.load_in_by_table)
else:
self.error('No File Match')
def create_thread(self, all_tables, func):
for tb in all_tables:
t = threading.Thread(target=func, args=(tb,)) # 创建线程
t.start()
def check_dir(self):
try:
if not os.path.isdir(self.back_path):
os.makedirs(self.back_path, mode=755)
except Exception as e:
self.error('Mkdirs %s error, error is:%s' % (self.back_path, str(e)))
exit()
if __name__ == '__main__':
if sys.version_info < (3, 0):
print('Python Version is too low')
exit()
'''
The description parameter can be used to insert information describing script usage, which can be empty.
Notice: formatter_class ,The purpose is to describe parameters too long without field newlines
'''
parser = argparse.ArgumentParser(description="Database and Excel Interoperate", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--version', '-v', action='version', version="%(prog)s " + config['VERSION']['version'])
parser.add_argument('--operation', '-opt', type=int, help="Operation Detail:\n"
" 1:Load In Single Table By Table Excel Name\n"
" 2:Load Out Single Table By Table Name\n"
" 3:Load In All Files By Configure Source Path\n"
" 4:Load Out All Tables By Configure Dbname\n"
, choices=[1, 2, 3, 4], required=True)
parser.add_argument('--table', '-t', default=None, help="Table Params Details\n"
" 1.The name of the Excel to be operated:\n"
" 2.There must be corresponding table names \n"
" in the configured database.\n"
" (When the name of the input table is empty, \n"
" all tables in the configuration database \n"
" are operated by default. )")
args = parser.parse_args()
if not args.operation:
print("Please Select Operation number....")
exit()
obj = Excel2db()
operation = args.operation
if operation == 1:
table = args.table
if table:
obj.check_dir()
obj.load_in_by_table(table)
else:
pass
elif operation == 2:
table = args.table
if table:
obj.load_out_by_table(table)
else:
pass
elif operation == 3:
obj.load_in_all()
elif operation == 4:
obj.check_dir()
obj.load_out_all()
else:
print('Operation Failed!!!') |
mldb_wrapper.py | # mldb_wrapper.py
# Copyright (c) 2015 mldb.ai inc. All rights reserved.
# This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
# Plugin loader for Python plugins; injectible python part
# https://bugs.python.org/issue32573 ; affects unittest
import sys
if not hasattr(sys, 'argv'):
sys.argv = ['']
import unittest
class mldb_wrapper(object):
import json as jsonlib # noqa
class MldbBaseException(Exception):
pass
class ResponseException(MldbBaseException):
def __init__(self, response):
self.response = response
def __str__(self):
return ('Response status code: {r.status_code}. '
'Response text: {r.text}'.format(r=self.response))
class TestSuiteFailureException(MldbBaseException):
def __init__(self, response):
self.response = response
def __str__(self):
return ('Test failed: {s}'.format(s=str(self.response)))
class TooManyRedirectsException(Exception):
pass
class Response(object):
def __init__(self, url, raw_response):
self.url = url
self.headers = {k: v for k, v in
raw_response.get('headers', {})}
self.status_code = raw_response['statusCode']
self.text = raw_response.get('response', '')
self.raw = raw_response
self.apparent_encoding = 'unimplemented'
self.close = 'unimplemented'
self.conection = 'unimplemented'
self.elapsed = 'unimplemented'
self.encoding = 'unimplemented'
self.history = 'unimplemented'
self.iter_content = 'unimplemented'
self.iter_lines = 'unimplemented'
self.links = 'unimplemented'
self.ok = 'unimplemented'
self.raise_for_status = 'unimplemented'
self.reason = 'unimplemented'
self.request = 'unimplemented'
def json(self):
return mldb_wrapper.jsonlib.loads(self.text)
def __str__(self):
return self.text
class StepsLogger(object):
def __init__(self, mldb):
self.done_steps = set()
self.log = mldb.log
def log_progress_steps(self, progress_steps):
from datetime import datetime
from dateutil.tz import tzutc
from dateutil.parser import parse as parse_date
now = datetime.now(tzutc())
for step in progress_steps:
if 'ended' in step:
if step['name'] in self.done_steps:
continue
self.done_steps.add(step['name'])
ran_in = parse_date(step['ended']) - parse_date(step['started'])
self.log("{} completed in {} seconds - {} {}"
.format(step['name'], ran_in.total_seconds(),
step['type'], step['value']))
elif 'started' in step:
running_since = now - parse_date(step['started'])
self.log("{} running since {} seconds - {} {}"
.format(step['name'], running_since.total_seconds(),
step['type'], step['value']))
class wrap(object):
def __init__(self, mldb):
self._mldb = mldb
import functools
self.post = functools.partial(self._post_put, 'POST')
self.put = functools.partial(self._post_put, 'PUT')
self.post_async = functools.partial(self._post_put, 'POST',
async=True)
self.put_async = functools.partial(self._post_put, 'PUT',
async=True)
self.create_dataset = self._mldb.create_dataset
def _follow_redirect(self, url, counter):
# somewhat copy pasted from _perform, but gives a nicer stacktrace
# on failure
if counter == 0:
raise mldb_wrapper.TooManyRedirectsException()
raw_res = self._mldb.perform('GET', url)
response = mldb_wrapper.Response(url, raw_res)
if response.status_code < 200 or response.status_code >= 400:
raise mldb_wrapper.ResponseException(response)
if response.status_code >= 300:
return self._follow_redirect(response.headers['location'],
counter - 1)
return response
def _perform(self, method, url, *args, **kwargs):
raw_res = self._mldb.perform(method, url, *args, **kwargs)
response = mldb_wrapper.Response(url, raw_res)
if response.status_code < 200 or response.status_code >= 400:
raise mldb_wrapper.ResponseException(response)
if response.status_code >= 300:
# 10 is the maximum count of redirects to follow
return self._follow_redirect(response.headers['location'], 10)
return response
def perform(self, *args, **kwargs):
return self._mldb.perform(*args, **kwargs)
def log(self, *args):
def fix(thing):
if type(thing) in [dict, list]:
thing = mldb_wrapper.jsonlib.dumps(thing, indent=4,
ensure_ascii=False)
if not isinstance(thing, (str)):
thing = str(thing)
return thing
fixed=[fix(thing) for thing in args]
self._mldb.log(*fixed)
@property
def script(self):
return self._mldb.script
@property
def plugin(self):
return self._mldb.plugin
def get_http_bound_address(self):
return self._mldb.get_http_bound_address()
def get(self, url, data=None, **kwargs):
query_string = []
for k, v in list(kwargs.items()):
if type(v) in [list, dict]:
v = mldb_wrapper.jsonlib.dumps(v)
query_string.append([str(k), str(v)])
return self._perform('GET', url, query_string, data)
def _post_put(self, verb, url, data=None, async=False):
if async:
return self._perform(verb, url, [], data, [['async', 'true']])
return self._perform(verb, url, [], data)
def delete(self, url):
return self._perform('DELETE', url)
def delete_async(self, url):
return self._perform('DELETE', url, [], {}, [['async', 'true']])
def query(self, query):
return self._perform('GET', '/v1/query', [], {
'q' : query,
'format' : 'table'
}).json()
def run_tests(self):
from io import StringIO
io_stream = StringIO()
runner = unittest.TextTestRunner(stream=io_stream, verbosity=2,
buffer=True)
argv = None
if self.script and self.script.args:
assert type(self.script.args) is list
if self.script.args[0]:
argv = ['python'] + self.script.args
else:
# avoid the only one empty arg issue
argv = None
res = unittest.main(exit=False, argv=argv,
testRunner=runner).result
self.log(io_stream.getvalue())
if res.wasSuccessful():
return("success")
raise mldb_wrapper.TestSuiteFailureException(res)
def post_run_and_track_procedure(self, payload, refresh_rate_sec=10):
import threading
if 'params' not in payload:
payload['params'] = {}
payload['params']['runOnCreation'] = False
res = self.post('/v1/procedures', payload).json()
proc_id = res['id']
event = threading.Event()
def monitor_progress():
# wrap everything in a try/except because exceptions are not passed to
# mldb.log by themselves.
try:
# find run id
run_id = None
sl = mldb_wrapper.StepsLogger(self)
while not event.wait(refresh_rate_sec):
if run_id is None:
res = self.get('/v1/procedures/{}/runs'.format(proc_id)).json()
if res:
run_id = res[0]
else:
continue
res = self.get('/v1/procedures/{}/runs/{}'.format(proc_id, run_id)).json()
if res['state'] == 'executing':
sl.log_progress_steps(res['progress']['steps'])
else:
break
except Exception as e:
self.log(str(e))
import traceback
self.log(traceback.format_exc())
t = threading.Thread(target=monitor_progress)
t.start()
try:
return self.post('/v1/procedures/{}/runs'.format(proc_id), {})
except mldb_wrapper.ResponseException as e:
return e.response
finally:
event.set()
t.join()
class MldbUnitTest(unittest.TestCase):
import json # noqa
longMessage = True # Appends the user message to the normal message
class _AssertMldbRaisesContext(object):
"""A context manager used to implement TestCase.assertRaises* methods.
Inspired from python unittests.
"""
def __init__(self, test_case, expected_regexp=None, status_code=None):
self.failureException = test_case.failureException
self.expected_regexp = expected_regexp
self.status_code = status_code
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is None:
raise self.failureException(
"{0} not raised".format(mldb_wrapper.MldbBaseException))
if not issubclass(exc_type, mldb_wrapper.MldbBaseException):
# let unexpected exceptions pass through
return False
self.exception = exc_value # store for later retrieval
if self.expected_regexp:
import re
expected_regexp = self.expected_regexp
if isinstance(expected_regexp, str):
expected_regexp = re.compile(expected_regexp)
if not expected_regexp.search(str(exc_value.response.text)):
raise self.failureException('"%s" does not match "%s"' %
(expected_regexp.pattern,
str(exc_value.response.text)))
if self.status_code:
if exc_value.response.status_code != self.status_code:
raise self.failureException(
"Status codes are not equal: {} != {}".format(
exc_value.response.status_code, self.status_code))
return True
def _get_base_msg(self, res, expected):
return '{line}Result: {res}{line}Expected: {expected}'.format(
line='\n' + '*' * 10 + '\n',
res=MldbUnitTest.json.dumps(res, indent=4),
expected=MldbUnitTest.json.dumps(expected, indent=4))
def assertTableResultEquals(self, res, expected, msg=""):
msg += self._get_base_msg(res, expected)
self.assertEqual(len(res), len(expected), msg)
self.assertNotEqual(len(res), 0, msg)
res_keys = sorted(res[0])
expected_keys = sorted(expected[0])
self.assertEqual(res_keys, expected_keys, msg)
# we'll make the order of `res` match the order of `expected`
# this is a map that gives us the index in `res` of a column name
colname_to_idx = {
colname: index for index, colname in enumerate(res[0])}
# this gives us the permutation we need to apply to `res`
res_perm = [colname_to_idx[colname]
for i, colname in enumerate(expected[0])]
ordered_res = [[row[i] for i in res_perm] for row in res[1:]]
for res_row, expected_row in zip(ordered_res, expected[1:]):
self.assertEqual(res_row, expected_row)
def assertFullResultEquals(self, res, expected, msg=""):
msg += self._get_base_msg(res, expected)
self.assertEqual(len(res), len(expected), msg)
for res_row, expected_row in zip(res, expected):
self.assertEqual(res_row["rowName"], expected_row["rowName"], msg)
res_columns = sorted(res_row["columns"])
expected_columns = sorted(expected_row["columns"])
self.assertEqual(res_columns, expected_columns, msg)
def assertMldbRaises(self, expected_regexp=None, status_code=None):
return MldbUnitTest._AssertMldbRaisesContext(self, expected_regexp,
status_code)
|
raspibrew.py | # Copyright (c) 2012 Stephen P. Smith
# Copyright (c) 2012 Stephen P. Smith
#
# 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.
config = ''
def loadConfig(configFile='config.json'):
with open(configFile) as data_file:
global config
config = json.load(data_file)
def initGlobalConfig(configFile):
global useLCD, runAsSimulation, speedUp, runDirPrefix, numberControllers, displayUnit
loadConfig(configFile)
useLCD = config['raspibrew']['useLCD']
numberControllers = config['raspibrew']['numberControllers']
runDirPrefix = config['raspibrew']['runDirPrefix']
runAsSimulation = config['globals']['runAsSimulation']
speedUp = config['globals']['speedUp']
displayUnit = config['globals']['displayUnit']
from multiprocessing import Process, Pipe, Queue, current_process
import threading
from subprocess import Popen, PIPE, call
from datetime import datetime
import web, time, random, json, serial, os
from pid import pidpy as PIDController
import sys
# Simulated Initial Water Temperature in Degree Celsius
temp_sim = 10.0
'''
# Simulated Room Temperature in Degree Celsius
temp_room_sim = 20.0
# Maximal Heatup of Water in Degree Celsius per Minute
# at Room Temperature when using 100% Power and already warmed up heater
temp_dTHm_sim = 1.5
# Maximal Cooldown of Water in Degree Celsius per Minute
# at measured at Boil Temperature (100 Degree Celsius)
temp_dTCm_sim = 0.78
'''
mpid = 0
def tempValueSave():
f = open(runDirPrefix + 'run/temp_sim' + str(mpid), 'w')
f.write(str(temp_sim))
f.close()
def tempValueRead():
global temp_sim
rv = ""
try:
f = open(runDirPrefix + 'run/temp_sim' + str(mpid), 'r')
rv = f.read()
f.close()
except:
1 == 1
if rv != "":
temp_sim = float(rv)
# default values used for initialization
class param:
mode = "off"
cycle_time = 2.0
duty_cycle = 0.0
boil_duty_cycle = 60
set_point = 0.0
boil_manage_temp = 200
num_pnts_smooth = 5
k_param = 44
i_param = 165
d_param = 4
# global hook for communication between web POST and temp control process as well as web GET and temp control process
def add_global_hook(parent_conn, statusQ, numberControllers):
g = web.storage({"parent_conn" : parent_conn, "statusQ" : statusQ, 'numberControllers': numberControllers})
def _wrapper(handler):
web.ctx.globals = g
return handler()
return _wrapper
class raspibrew:
def __init__(self):
self.mode = param.mode
self.cycle_time = param.cycle_time
self.duty_cycle = param.duty_cycle
self.set_point = param.set_point
self.boil_manage_temp = param.boil_manage_temp
self.num_pnts_smooth = param.num_pnts_smooth
self.k_param = param.k_param
self.i_param = param.i_param
self.d_param = param.d_param
# main web page
def GET(self):
id = int(web.input(id=1)['id'])
return render.raspibrew(self.mode, self.set_point, self.duty_cycle, self.cycle_time, \
self.k_param, self.i_param, self.d_param, id, displayUnit)
# get command from web browser or Android
def POST(self):
data = web.data()
datalist = data.split("&")
for item in datalist:
datalistkey = item.split("=")
if datalistkey[0] == "mode":
self.mode = datalistkey[1]
if datalistkey[0] == "setpoint":
self.set_point = float(datalistkey[1])
if datalistkey[0] == "dutycycle": # is boil duty cycle if mode == "boil"
self.duty_cycle = float(datalistkey[1])
if datalistkey[0] == "cycletime":
self.cycle_time = float(datalistkey[1])
if datalistkey[0] == "boilManageTemp":
self.boil_manage_temp = float(datalistkey[1])
if datalistkey[0] == "numPntsSmooth":
self.num_pnts_smooth = int(datalistkey[1])
if datalistkey[0] == "k":
self.k_param = float(datalistkey[1])
if datalistkey[0] == "i":
self.i_param = float(datalistkey[1])
if datalistkey[0] == "d":
self.d_param = float(datalistkey[1])
if datalistkey[0] == "id":
id = int(datalistkey[1])
# send to main temp control process
# if did not receive variable key value in POST, the param class default is used
web.ctx.globals.parent_conn[id - 1].send([self.mode, self.cycle_time, self.duty_cycle, self.set_point, \
self.boil_manage_temp, self.num_pnts_smooth, self.k_param, self.i_param, self.d_param])
class getstatus:
def __init__(self):
pass
def GET(self):
# blocking receive - current status
id = int(web.input(id=1)['id'])
temp, elapsed, mode, cycle_time, duty_cycle, set_point, boil_manage_temp, num_pnts_smooth, \
k_param, i_param, d_param = web.ctx.globals.statusQ[id - 1].get()
out = json.dumps({"temp" : temp,
"elapsed" : elapsed,
"mode" : mode,
"cycle_time" : cycle_time,
"duty_cycle" : duty_cycle,
"set_point" : set_point,
"boil_manage_temp" : boil_manage_temp,
"num_pnts_smooth" : num_pnts_smooth,
"k_param" : k_param,
"i_param" : i_param,
"d_param" : d_param})
return out
def POST(self):
pass
class getLCD:
def __init__(self):
pass
def GET(self):
return render.lcd(display.lcd.getMirror())
def POST(self):
pass
# Retrieve temperature from simulated temperature sensor
def tempDataSim(tempSensorId):
tempValueRead()
return temp_sim
# Retrieve temperature from DS18B20 temperature sensor
def tempData1Wire(tempSensorId):
with open("/opt/owfs/uncached/" + tempSensorId + "/temperature", 'r') as f:
result = f.read()
f.close()
if (float(result) == 85):
print "FAILED"
time.sleep(1.0)
with open("/opt/owfs/uncached/" + tempSensorId + "/temperature", 'r') as f:
result = f.read()
f.close()
temp_C = float(result) # temp in Celcius
return temp_C
# Stand Alone Get Temperature Process
def gettempProc(configFile, num, conn):
initGlobalConfig(configFile)
global mpid
mpid = num
p = current_process()
print 'Starting:', p.name, p.pid
tempSensorId = config['raspibrew']['controller'][num]['sensorId']
tempSensorType = config['raspibrew']['controller'][num]['sensorType']
t = time.time()
while (True):
time.sleep(0.5 / speedUp) # .5+~.83 = ~1.33 seconds
if tempSensorType == "Simulated":
num = tempDataSim(tempSensorId)
elif tempSensorType == "1w":
try:
num = tempData1Wire(tempSensorId)
except IOError:
print tempSensorId
num = -99
elif tempSensorType == "none":
num = -100
else:
raise Exception("Unknown Sensor Type: " + tempSensorType)
t1 = time.time()
elapsed = "%.2f" % ((t1 - t) * speedUp)
t = t1
conn.send([num, elapsed])
# Get time heating element is on and off during a set cycle time
def getonofftime(cycle_time, duty_cycle):
duty = duty_cycle / 100.0
on_time = cycle_time * (duty)
off_time = cycle_time * (1.0 - duty)
return [on_time, off_time]
class SoftPWMBase(threading.Thread):
def off(self,waitTime):
self.cycleDuration = self.cycleDuration + self.waitTimeOrChange(waitTime)
def on(self,waitTime):
self.cycleDuration = self.cycleDuration + self.waitTimeOrChange(waitTime)
def initLoopIteration(self):
self.cycleDuration = 0.0
def __init__(self,num):
self.num = num
self.cycle_time = 1.0
self.duty_cycle = 0
self.cycleDuration = 0.0
threading.Thread.__init__(self)
def waitTimeOrChange(self, waitTime):
cycleTime = self.cycle_time
dutyCycle = self.duty_cycle
cycleDuration = 0.0
seconds = int(waitTime)
subseconds = waitTime - seconds
for secondStep in range(0,seconds):
time.sleep(1.0 / speedUp)
cycleDuration = cycleDuration + 1.0
if cycleTime != self.cycle_time or dutyCycle != self.duty_cycle:
return cycleDuration
if subseconds:
time.sleep(subseconds / speedUp)
cycleDuration = cycleDuration + subseconds
return cycleDuration
def run(self):
self.cycleDuration = 0.0
while (True):
self.initLoopIteration()
if self.duty_cycle == 0:
self.off(self.cycle_time)
elif self.duty_cycle == 100:
self.on(self.cycle_time)
else:
on_time, off_time = getonofftime(self.cycle_time, self.duty_cycle)
self.on(on_time)
self.off(off_time)
class SoftPWMSiumulation(SoftPWMBase):
def on(self, waitTime):
global temp_sim
if self.num == 2:
#print "ON ", self.num
pass
SoftPWMBase.on(self, waitTime)
temp_sim = temp_sim + self.temp_dTHm_sim * (self.cycleDuration / 60)
def off(self, waitTime):
if self.num == 2:
pass
SoftPWMBase.on(self, waitTime)
def init(self):
global temp_sim
self.temp_dTCm_sim = config['raspibrew']['controller'][self.num]['dTCm']
self.temp_dTHm_sim = config['raspibrew']['controller'][self.num]['dTHm']
temp_sim = config['raspibrew']['controller'][self.num]['waterTemp']
self.temp_room_sim = config['raspibrew']['simulation']['roomTemp']
def initLoopIteration(self):
global temp_sim
temp_sim = temp_sim - self.temp_dTCm_sim * (self.cycleDuration / 60) * (temp_sim - self.temp_room_sim) / (100.0 - self.temp_room_sim)
tempValueSave()
self.cycleDuration = 0.0
def __init__(self,num):
SoftPWMBase.__init__(self,num)
self.init()
class SoftPWMGPIO(SoftPWMBase):
def off(self,waitTime):
import RPi.GPIO as GPIO
GPIO.output(self.pin, False)
SoftPWMBase.off(self,waitTime)
def on(self,waitTime):
import RPi.GPIO as GPIO
GPIO.output(self.pin, True)
SoftPWMBase.on(self,waitTime)
def init(self):
self.pin = config['raspibrew']['controller'][self.num]['heaterId']
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.pin, GPIO.OUT)
self.off(0)
def __init__(self, num):
SoftPWMBase.__init__(self,num)
self.init()
class SoftPWMI2C(SoftPWMBase):
def off(self, waitTime):
self.bus.write_byte_data(0x26, 0x09, 0x00)
SoftPWMBase.off(self,waitTime)
def on(self, waitTime):
self.bus.write_byte_data(0x26, 0x09, 0x01)
SoftPWMBase.on(self,waitTime)
def init(self):
self.bus = SMBus(0)
self.off()
def __init__(self, num):
SoftPWMBase.__init__(self,num)
self.init()
def heatProcGeneric(configFile, num,cycle_time, duty_cycle, conn):
global mpid
mpid = num
initGlobalConfig(configFile)
p = current_process()
heaterId = config['raspibrew']['controller'][num]['heaterId']
heaterType = config['raspibrew']['controller'][num]['heaterType']
if heaterType == 'Simulated':
pwm = SoftPWMSiumulation(num)
elif heaterType == 'GPIO':
pwm = SoftPWMGPIO(num)
elif heaterType == 'I2C':
pwm = SoftPWMI2C(num)
else:
raise Exception("Unknown Heater Process Style")
print 'Starting ',heaterType,' Heater Process ', num,' with id', heaterId, ' :', p.name, p.pid
try:
pwm.start()
while (True):
pwm.cycle_time, pwm.duty_cycle = conn.recv()
conn.send([pwm.cycle_time, pwm.duty_cycle])
finally:
pwm.off()
# Main Teerature Control Process
def tempControlProc(configFile, num, mode, cycle_time, duty_cycle, boil_duty_cycle, set_point, boil_manage_temp, num_pnts_smooth, k_param, i_param, d_param, statusQ, conn):
initGlobalConfig(configFile)
if useLCD:
# initialize LCD
ser = serial.Serial("/dev/ttyAMA0", 9600)
ser.write("?BFF")
time.sleep(.1) # wait 100msec
ser.write("?f?a")
ser.write("?y0?x00PID off ")
ser.write("?y1?x00HLT:")
ser.write("?y3?x00Heat: off ")
ser.write("?D70609090600000000") # define degree symbol
time.sleep(.1) # wait 100msec
p = current_process()
print 'Starting Controller ', num, ':', p.name, p.pid
# Pipe to communicate with "Get Temperature Process"
parent_conn_temp, child_conn_temp = Pipe()
# Start Get Temperature Process
ptemp = Process(name="gettempProc", target=gettempProc, args=(configFile, num, child_conn_temp,))
ptemp.daemon = True
ptemp.start()
# Pipe to communicate with "Heat Process"
parent_conn_heat, child_conn_heat = Pipe()
# Start Heat Process
pheat = Process(name="heatProcGeneric", target=heatProcGeneric, args=(configFile, num, cycle_time, duty_cycle, child_conn_heat))
pheat.daemon = True
pheat.start()
temp_F_ma_list = []
manage_boil_trigger = False
elapsed = 0.0
while (True):
readytemp = False
if ptemp.is_alive() == False:
# switch off if temperature process fails to deliver data
parent_conn_heat.send([cycle_time, 0])
print "Emergency Stop, no temperature"
time.sleep(2)
sys.exit()
if pheat.is_alive() == False:
print "Emergency Stop, no heater"
sys.exit()
while parent_conn_temp.poll(): # Poll Get Temperature Process Pipe
temp_C, elapsedMeasurement = parent_conn_temp.recv() # non blocking receive from Get Temperature Process
elapsed = elapsed + float(elapsedMeasurement)
if temp_C == -99:
print "Bad Temp Reading - retry"
continue
temp_F = (9.0 / 5.0) * temp_C + 32
temp_F_ma_list.append(temp_F)
# smooth data
temp_F_ma = 0.0 # moving avg init
while (len(temp_F_ma_list) > num_pnts_smooth):
temp_F_ma_list.pop(0) # remove oldest elements in list
if (len(temp_F_ma_list) < num_pnts_smooth):
for temp_pnt in temp_F_ma_list:
temp_F_ma += temp_pnt
temp_F_ma /= len(temp_F_ma_list)
else: # len(temp_F_ma_list) == num_pnts_smooth
for temp_idx in range(num_pnts_smooth):
temp_F_ma += temp_F_ma_list[temp_idx]
temp_F_ma /= num_pnts_smooth
# print "len(temp_F_ma_list) = %d" % len(temp_F_ma_list)
# print "Num Points smooth = %d" % num_pnts_smooth
# print "temp_F_ma = %.2f" % temp_F_ma
# print temp_F_ma_list
temp_C_str = "%3.2f" % temp_C
temp_F_str = "%3.2f" % temp_F
# write to LCD
if useLCD:
ser.write("?y1?x05")
ser.write(temp_F_str)
ser.write("?7") # degree
time.sleep(.005) # wait 5msec
ser.write("F ")
readytemp = True
if readytemp == True:
if mode == "auto":
# calculate PID every cycle - always get latest temperature
# print "Temp F MA %.2f" % temp_F_ma
duty_cycle = pid.calcPID_reg4(temp_F_ma, set_point, True)
# send to heat process every cycle
parent_conn_heat.send([cycle_time, duty_cycle])
if mode == "boil":
if (temp_F > boil_manage_temp) and (manage_boil_trigger == True): # do once
manage_boil_trigger = False
duty_cycle = boil_duty_cycle
parent_conn_heat.send([cycle_time, duty_cycle])
# put current status in queue
try:
statusQ.put([temp_F_str, elapsed, mode, cycle_time, duty_cycle, set_point, \
boil_manage_temp, num_pnts_smooth, k_param, i_param, d_param]) # GET request
except Queue.Full:
pass
while (statusQ.qsize() >= 2):
statusQ.get() # remove old status
# print "Temp: %3.2f deg F, Heat Output: %3.1f%% %s %f" % (temp_F, duty_cycle, mode, boil_manage_temp)
readytemp == False
while parent_conn_heat.poll(): # Poll Heat Process Pipe
cycle_time, duty_cycle = parent_conn_heat.recv() # non blocking receive from Heat Process
# write to LCD
if useLCD:
ser.write("?y2?x00Duty: ")
ser.write("%3.1f" % duty_cycle)
ser.write("% ")
readyPOST = False
while conn.poll(): # POST settings - Received POST from web browser or Android device
mode, cycle_time, duty_cycle_temp, set_point, boil_manage_temp, num_pnts_smooth, k_param, i_param, d_param = conn.recv()
readyPOST = True
if readyPOST == True:
if mode == "auto":
if useLCD:
ser.write("?y0?x00Auto Mode ")
ser.write("?y1?x00HLT:")
ser.write("?y3?x00Set To: ")
ser.write("%3.1f" % set_point)
ser.write("?7") # degree
time.sleep(.005) # wait 5msec
ser.write("F ")
print "auto selected"
pid = PIDController.pidpy(cycle_time, k_param, i_param, d_param) # init pid
duty_cycle = pid.calcPID_reg4(temp_F_ma, set_point, True)
if mode == "boil":
if useLCD:
ser.write("?y0?x00Boil Mode ")
ser.write("?y1?x00BK: ")
ser.write("?y3?x00Heat: on ")
print "boil selected"
boil_duty_cycle = duty_cycle_temp
duty_cycle = 100 # full power to boil manage temperature
manage_boil_trigger = True
if mode == "manual":
if useLCD:
ser.write("?y0?x00Manual Mode ")
ser.write("?y1?x00BK: ")
ser.write("?y3?x00Heat: on ")
print "manual selected"
duty_cycle = duty_cycle_temp
if mode == "off":
if useLCD:
ser.write("?y0?x00PID off ")
ser.write("?y1?x00HLT:")
ser.write("?y3?x00Heat: off ")
print "off selected"
duty_cycle = 0
parent_conn_heat.send([cycle_time, duty_cycle])
readyPOST = False
time.sleep(.01)
def startRasPiBrew(configFile, lcdDisplay = None):
global display
display = lcdDisplay
initGlobalConfig(configFile)
mydir = os.getcwd()
urls = ("/", "raspibrew",
"/getrand", "getrand",
"/getstatus", "getstatus",
"/lcd","getLCD")
global render
render = web.template.render(mydir + "/templates/")
app = web.application(urls, globals())
statusQ = []
parent_conn = []
child_conn = []
p = []
for idx in range(0, numberControllers):
statusQ.append(Queue(2)) # blocking queue
p_c, c_c = Pipe()
parent_conn.append(p_c)
child_conn.append(c_c)
p.append(Process(name="tempControlProc" + str(idx + 1), target=tempControlProc, args=(configFile, idx + 1, param.mode, param.cycle_time, param.duty_cycle, param.boil_duty_cycle, \
param.set_point, param.boil_manage_temp, param.num_pnts_smooth, \
param.k_param, param.i_param, param.d_param, \
statusQ[idx], child_conn[idx])))
p[idx].start()
app.add_processor(add_global_hook(parent_conn, statusQ, numberControllers))
# app.run()
web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", 8080))
if __name__ == '__main__':
startRasPiBrew('config.json')
|
event_demo.py | import threading
import time
# 创建事件
event = threading.Event()
def drive(name):
i = 0
while True:
i = i + 1
print(name + "正在行驶中,行驶了" + str(i * 60) + "Km")
time.sleep(1)
event.wait()
print(name + '通过了红灯')
# 红绿灯信号
def sign():
print("绿灯初始化")
# 将 flag 设为 True,通知所有处于阻塞状态的线程恢复运行状态。
event.set()
while True:
time.sleep(3)
if event.isSet():
print("红灯亮起,所有行驶中的车辆不允许通过")
event.clear()
else:
print("绿灯亮起,所有行驶中的车辆必须通过")
event.set()
if __name__ == '__main__':
# 设置公路线程组
highwayThreads = []
# 创建汽车新线程
bmwCar = threading.Thread(target=drive, args=('BMWCar',))
vmCar = threading.Thread(target=drive, args=('VMCar',))
# 将汽车线程添加到公路线程组
highwayThreads.append(bmwCar)
highwayThreads.append(vmCar)
# 汽车启动
for thread in highwayThreads:
thread.start()
# 红绿灯发送事件通知
sign() |
portscanner.py | # coding=utf-8
# Author: calfcrusher@inventati.org
import optparse
import socket
from socket import *
from threading import *
def connect(targethost, targetports):
"""Connect function"""
# A simple semaphore provides us a lock to prevent other threads from printing on stdout
screenLock = Semaphore(value=1)
try:
c = socket(AF_INET, SOCK_STREAM)
c.connect((targethost, targetports))
banner = c.recv()
# Prior printing an output we grabs a hold of the lock
screenLock.acquire()
print '[+] %d/TCP open |' % targetports + str(banner).strip('\n')
c.close()
except:
screenLock.acquire()
print '[-] %d/TCP closed' % targetports
def portscan(targethost, targetports):
"""Multithreading Portscan function"""
global ip
try:
ip = gethostbyname(targethost)
except:
print "[-] Cannot resolve '%s': Unknown host" % targethost
try:
hostname = gethostbyaddr(ip)
print '\n[*] Scan Results for: ' + hostname[0]
except:
print '\n[*] Scan Results for: ' + ip
setdefaulttimeout(2)
# Convert string to list, splitting by commas
portlist = str(targetports).split(",")
for port in portlist:
t = Thread(target=connect, args=(targethost, int(port)))
t.start()
def main():
"""Tool usage"""
print """
,------. ,--.,--.,--------. ,-----.,------. ,------. ,--.
| .---',--.,--.| || |'--. .--'' .--./| .--. ' | .--. ' ,---. ,--.--.,-' '-. ,---. ,---. ,--,--.,--,--,
| `--, | || || || | | | | | | '--' | | '--' || .-. || .--''-. .-'( .-' | .--'' ,-. || \
| |` ' '' '| || | | | ' '--'\| | --' | | --' ' '-' '| | | | .-' `)\ `--.\ '-' || || |
`--' `----' `--'`--' `--' `-----'`--' `--' `---' `--' `--' `----' `---' `--`--'`--''--'
._ o o
\_`-)|_
,"" \
," ## | ಠ ಠ. Full TCP fast Multithreading Port scanner
," ## ,-\__ `. developed by calfcrusher@inventati.org
," / `--._;) example: ./portscanner.py –H localhost -P 21,80,443
," ## /
," ## /
"""
parser = optparse.OptionParser('./portscanner.py –H <host> -p <ports>\n')
parser.add_option('-H', dest='host', type='string', help='set target host')
parser.add_option('-p', dest='port', type='string', help='set target ports separated by commas')
(options, args) = parser.parse_args()
host = options.host
port = options.port
if host is None or port is None:
print "Usage: " + parser.usage
exit(0)
portscan(host, port)
if __name__ == "__main__":
main()
|
utils.py | # -*- coding: utf-8 -*-
"""
Various useful functions
"""
# Author: Remi Flamary <remi.flamary@unice.fr>
#
# License: MIT License
import multiprocessing
from functools import reduce
import time
import numpy as np
from scipy.spatial.distance import cdist
import sys
import warnings
from inspect import signature
__time_tic_toc = time.time()
def tic():
""" Python implementation of Matlab tic() function """
global __time_tic_toc
__time_tic_toc = time.time()
def toc(message='Elapsed time : {} s'):
""" Python implementation of Matlab toc() function """
t = time.time()
print(message.format(t - __time_tic_toc))
return t - __time_tic_toc
def toq():
""" Python implementation of Julia toc() function """
t = time.time()
return t - __time_tic_toc
def kernel(x1, x2, method='gaussian', sigma=1, **kwargs):
"""Compute kernel matrix"""
if method.lower() in ['gaussian', 'gauss', 'rbf']:
K = np.exp(-dist(x1, x2) / (2 * sigma**2))
return K
def laplacian(x):
"""Compute Laplacian matrix"""
L = np.diag(np.sum(x, axis=0)) - x
return L
def unif(n):
""" return a uniform histogram of length n (simplex)
Parameters
----------
n : int
number of bins in the histogram
Returns
-------
h : np.array (n,)
histogram of length n such that h_i=1/n for all i
"""
return np.ones((n,)) / n
def clean_zeros(a, b, M):
""" Remove all components with zeros weights in a and b
"""
M2 = M[a > 0, :][:, b > 0].copy() # copy force c style matrix (froemd)
a2 = a[a > 0]
b2 = b[b > 0]
return a2, b2, M2
def euclidean_distances(X, Y, squared=False):
"""
Considering the rows of X (and Y=X) as vectors, compute the
distance matrix between each pair of vectors.
Parameters
----------
X : {array-like}, shape (n_samples_1, n_features)
Y : {array-like}, shape (n_samples_2, n_features)
squared : boolean, optional
Return squared Euclidean distances.
Returns
-------
distances : {array}, shape (n_samples_1, n_samples_2)
"""
XX = np.einsum('ij,ij->i', X, X)[:, np.newaxis]
YY = np.einsum('ij,ij->i', Y, Y)[np.newaxis, :]
distances = np.dot(X, Y.T)
distances *= -2
distances += XX
distances += YY
np.maximum(distances, 0, out=distances)
if X is Y:
# Ensure that distances between vectors and themselves are set to 0.0.
# This may not be the case due to floating point rounding errors.
distances.flat[::distances.shape[0] + 1] = 0.0
return distances if squared else np.sqrt(distances, out=distances)
def dist(x1, x2=None, metric='sqeuclidean'):
"""Compute distance between samples in x1 and x2 using function scipy.spatial.distance.cdist
Parameters
----------
x1 : ndarray, shape (n1,d)
matrix with n1 samples of size d
x2 : array, shape (n2,d), optional
matrix with n2 samples of size d (if None then x2=x1)
metric : str | callable, optional
Name of the metric to be computed (full list in the doc of scipy), If a string,
the distance function can be 'braycurtis', 'canberra', 'chebyshev', 'cityblock',
'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski',
'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean',
'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', 'yule'.
Returns
-------
M : np.array (n1,n2)
distance matrix computed with given metric
"""
if x2 is None:
x2 = x1
if metric == "sqeuclidean":
return euclidean_distances(x1, x2, squared=True)
return cdist(x1, x2, metric=metric)
def dist0(n, method='lin_square'):
"""Compute standard cost matrices of size (n, n) for OT problems
Parameters
----------
n : int
Size of the cost matrix.
method : str, optional
Type of loss matrix chosen from:
* 'lin_square' : linear sampling between 0 and n-1, quadratic loss
Returns
-------
M : ndarray, shape (n1,n2)
Distance matrix computed with given metric.
"""
res = 0
if method == 'lin_square':
x = np.arange(n, dtype=np.float64).reshape((n, 1))
res = dist(x, x)
return res
def cost_normalization(C, norm=None):
""" Apply normalization to the loss matrix
Parameters
----------
C : ndarray, shape (n1, n2)
The cost matrix to normalize.
norm : str
Type of normalization from 'median', 'max', 'log', 'loglog'. Any
other value do not normalize.
Returns
-------
C : ndarray, shape (n1, n2)
The input cost matrix normalized according to given norm.
"""
if norm is None:
pass
elif norm == "median":
C /= float(np.median(C))
elif norm == "max":
C /= float(np.max(C))
elif norm == "log":
C = np.log(1 + C)
elif norm == "loglog":
C = np.log1p(np.log1p(C))
else:
raise ValueError('Norm %s is not a valid option.\n'
'Valid options are:\n'
'median, max, log, loglog' % norm)
return C
def dots(*args):
""" dots function for multiple matrix multiply """
return reduce(np.dot, args)
def label_normalization(y, start=0):
""" Transform labels to start at a given value
Parameters
----------
y : array-like, shape (n, )
The vector of labels to be normalized.
start : int
Desired value for the smallest label in y (default=0)
Returns
-------
y : array-like, shape (n1, )
The input vector of labels normalized according to given start value.
"""
diff = np.min(np.unique(y)) - start
if diff != 0:
y -= diff
return y
def fun(f, q_in, q_out):
""" Utility function for parmap with no serializing problems """
while True:
i, x = q_in.get()
if i is None:
break
q_out.put((i, f(x)))
def parmap(f, X, nprocs=multiprocessing.cpu_count()):
""" paralell map for multiprocessing (only map on windows)"""
if not sys.platform.endswith('win32'):
q_in = multiprocessing.Queue(1)
q_out = multiprocessing.Queue()
proc = [multiprocessing.Process(target=fun, args=(f, q_in, q_out))
for _ in range(nprocs)]
for p in proc:
p.daemon = True
p.start()
sent = [q_in.put((i, x)) for i, x in enumerate(X)]
[q_in.put((None, None)) for _ in range(nprocs)]
res = [q_out.get() for _ in range(len(sent))]
[p.join() for p in proc]
return [x for i, x in sorted(res)]
else:
return list(map(f, X))
def check_params(**kwargs):
"""check_params: check whether some parameters are missing
"""
missing_params = []
check = True
for param in kwargs:
if kwargs[param] is None:
missing_params.append(param)
if len(missing_params) > 0:
print("POT - Warning: following necessary parameters are missing")
for p in missing_params:
print("\n", p)
check = False
return check
def check_random_state(seed):
"""Turn seed into a np.random.RandomState instance
Parameters
----------
seed : None | int | instance of RandomState
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance seeded with seed.
If seed is already a RandomState instance, return it.
Otherwise raise ValueError.
"""
if seed is None or seed is np.random:
return np.random.mtrand._rand
if isinstance(seed, (int, np.integer)):
return np.random.RandomState(seed)
if isinstance(seed, np.random.RandomState):
return seed
raise ValueError('{} cannot be used to seed a numpy.random.RandomState'
' instance'.format(seed))
class deprecated(object):
"""Decorator to mark a function or class as deprecated.
deprecated class from scikit-learn package
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/deprecation.py
Issue a warning when the function is called/the class is instantiated and
adds a warning to the docstring.
The optional extra argument will be appended to the deprecation message
and the docstring. Note: to use this with the default value for extra, put
in an empty of parentheses:
>>> from ot.deprecation import deprecated # doctest: +SKIP
>>> @deprecated() # doctest: +SKIP
... def some_function(): pass # doctest: +SKIP
Parameters
----------
extra : str
To be added to the deprecation messages.
"""
# Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary,
# but with many changes.
def __init__(self, extra=''):
self.extra = extra
def __call__(self, obj):
"""Call method
Parameters
----------
obj : object
"""
if isinstance(obj, type):
return self._decorate_class(obj)
else:
return self._decorate_fun(obj)
def _decorate_class(self, cls):
msg = "Class %s is deprecated" % cls.__name__
if self.extra:
msg += "; %s" % self.extra
# FIXME: we should probably reset __new__ for full generality
init = cls.__init__
def wrapped(*args, **kwargs):
warnings.warn(msg, category=DeprecationWarning)
return init(*args, **kwargs)
cls.__init__ = wrapped
wrapped.__name__ = '__init__'
wrapped.__doc__ = self._update_doc(init.__doc__)
wrapped.deprecated_original = init
return cls
def _decorate_fun(self, fun):
"""Decorate function fun"""
msg = "Function %s is deprecated" % fun.__name__
if self.extra:
msg += "; %s" % self.extra
def wrapped(*args, **kwargs):
warnings.warn(msg, category=DeprecationWarning)
return fun(*args, **kwargs)
wrapped.__name__ = fun.__name__
wrapped.__dict__ = fun.__dict__
wrapped.__doc__ = self._update_doc(fun.__doc__)
return wrapped
def _update_doc(self, olddoc):
newdoc = "DEPRECATED"
if self.extra:
newdoc = "%s: %s" % (newdoc, self.extra)
if olddoc:
newdoc = "%s\n\n%s" % (newdoc, olddoc)
return newdoc
def _is_deprecated(func):
"""Helper to check if func is wraped by our deprecated decorator"""
if sys.version_info < (3, 5):
raise NotImplementedError("This is only available for python3.5 "
"or above")
closures = getattr(func, '__closure__', [])
if closures is None:
closures = []
is_deprecated = ('deprecated' in ''.join([c.cell_contents
for c in closures
if isinstance(c.cell_contents, str)]))
return is_deprecated
class BaseEstimator(object):
"""Base class for most objects in POT
Code adapted from sklearn BaseEstimator class
Notes
-----
All estimators should specify all the parameters that can be set
at the class level in their ``__init__`` as explicit keyword
arguments (no ``*args`` or ``**kwargs``).
"""
@classmethod
def _get_param_names(cls):
"""Get parameter names for the estimator"""
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
if init is object.__init__:
# No explicit constructor to introspect
return []
# introspect the constructor arguments to find the model parameters
# to represent
init_signature = signature(init)
# Consider the constructor parameters excluding 'self'
parameters = [p for p in init_signature.parameters.values()
if p.name != 'self' and p.kind != p.VAR_KEYWORD]
for p in parameters:
if p.kind == p.VAR_POSITIONAL:
raise RuntimeError("POT estimators should always "
"specify their parameters in the signature"
" of their __init__ (no varargs)."
" %s with constructor %s doesn't "
" follow this convention."
% (cls, init_signature))
# Extract and sort argument names excluding 'self'
return sorted([p.name for p in parameters])
def get_params(self, deep=True):
"""Get parameters for this estimator.
Parameters
----------
deep : bool, optional
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------
params : mapping of string to any
Parameter names mapped to their values.
"""
out = dict()
for key in self._get_param_names():
# We need deprecation warnings to always be on in order to
# catch deprecated param values.
# This is set in utils/__init__.py but it gets overwritten
# when running under python3 somehow.
warnings.simplefilter("always", DeprecationWarning)
try:
with warnings.catch_warnings(record=True) as w:
value = getattr(self, key, None)
if len(w) and w[0].category == DeprecationWarning:
# if the parameter is deprecated, don't show it
continue
finally:
warnings.filters.pop(0)
# XXX: should we rather test if instance of estimator?
if deep and hasattr(value, 'get_params'):
deep_items = value.get_params().items()
out.update((key + '__' + k, val) for k, val in deep_items)
out[key] = value
return out
def set_params(self, **params):
"""Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects
(such as pipelines). The latter have parameters of the form
``<component>__<parameter>`` so that it's possible to update each
component of a nested object.
Returns
-------
self
"""
if not params:
# Simple optimisation to gain speed (inspect is slow)
return self
valid_params = self.get_params(deep=True)
# for key, value in iteritems(params):
for key, value in params.items():
split = key.split('__', 1)
if len(split) > 1:
# nested objects case
name, sub_name = split
if name not in valid_params:
raise ValueError('Invalid parameter %s for estimator %s. '
'Check the list of available parameters '
'with `estimator.get_params().keys()`.' %
(name, self))
sub_object = valid_params[name]
sub_object.set_params(**{sub_name: value})
else:
# simple objects case
if key not in valid_params:
raise ValueError('Invalid parameter %s for estimator %s. '
'Check the list of available parameters '
'with `estimator.get_params().keys()`.' %
(key, self.__class__.__name__))
setattr(self, key, value)
return self
class UndefinedParameter(Exception):
"""
Aim at raising an Exception when a undefined parameter is called
"""
pass
|
minion.py | # -*- coding: utf-8 -*-
'''
Routines to set up a minion
'''
# Import python libs
from __future__ import print_function
import copy
import errno
import fnmatch
import hashlib
import logging
import multiprocessing
import os
import re
import salt
import signal
import sys
import threading
import time
import traceback
import types
from random import randint, shuffle
# Import third party libs
try:
import zmq
HAS_ZMQ = True
except ImportError:
# Running in local, zmq not needed
HAS_ZMQ = False
HAS_RANGE = False
try:
import seco.range
HAS_RANGE = True
except ImportError:
pass
HAS_PSUTIL = False
try:
import psutil
HAS_PSUTIL = True
except ImportError:
pass
HAS_RESOURCE = False
try:
import resource
HAS_RESOURCE = True
except ImportError:
pass
# Import salt libs
from salt.exceptions import (
AuthenticationError, CommandExecutionError, CommandNotFoundError,
SaltInvocationError, SaltReqTimeoutError, SaltClientError,
SaltSystemExit
)
import salt.client
import salt.crypt
import salt.loader
import salt.payload
import salt.utils
import salt.utils.args
import salt.utils.event
import salt.utils.schedule
from salt._compat import string_types
from salt.utils.debug import enable_sigusr1_handler
from salt.utils.event import tagify
import salt.syspaths
log = logging.getLogger(__name__)
# To set up a minion:
# 1. Read in the configuration
# 2. Generate the function mapping dict
# 3. Authenticate with the master
# 4. Store the AES key
# 5. Connect to the publisher
# 6. Handle publications
def resolve_dns(opts):
'''
Resolves the master_ip and master_uri options
'''
ret = {}
check_dns = True
if opts.get('file_client', 'remote') == 'local' and check_dns:
check_dns = False
if check_dns is True:
# Because I import salt.log below I need to re-import salt.utils here
import salt.utils
try:
ret['master_ip'] = \
salt.utils.dns_check(opts['master'], True, opts['ipv6'])
except SaltClientError:
if opts['retry_dns']:
while True:
import salt.log
msg = ('Master hostname: {0} not found. Retrying in {1} '
'seconds').format(opts['master'], opts['retry_dns'])
if salt.log.is_console_configured():
log.warn(msg)
else:
print('WARNING: {0}'.format(msg))
time.sleep(opts['retry_dns'])
try:
ret['master_ip'] = salt.utils.dns_check(
opts['master'], True, opts['ipv6']
)
break
except SaltClientError:
pass
else:
ret['master_ip'] = '127.0.0.1'
except SaltSystemExit:
err = 'Master address: {0} could not be resolved. Invalid or unresolveable address.'.format(
opts.get('master', 'Unknown'))
log.error(err)
raise SaltSystemExit(code=42, msg=err)
else:
ret['master_ip'] = '127.0.0.1'
if 'master_ip' in ret and 'master_ip' in opts:
if ret['master_ip'] != opts['master_ip']:
log.warning('Master ip address changed from {0} to {1}'.format(opts['master_ip'],
ret['master_ip'])
)
ret['master_uri'] = 'tcp://{ip}:{port}'.format(ip=ret['master_ip'],
port=opts['master_port'])
return ret
def get_proc_dir(cachedir):
'''
Given the cache directory, return the directory that process data is
stored in, creating it if it doesn't exist.
'''
fn_ = os.path.join(cachedir, 'proc')
if not os.path.isdir(fn_):
# proc_dir is not present, create it
os.makedirs(fn_)
return fn_
def parse_args_and_kwargs(func, args, data=None):
'''
Wrap load_args_and_kwargs
'''
salt.utils.warn_until(
'Boron',
'salt.minion.parse_args_and_kwargs() has been renamed to '
'salt.minion.load_args_and_kwargs(). Please change this function call '
'before the Boron release of Salt.'
)
return load_args_and_kwargs(func, args, data=data)
def load_args_and_kwargs(func, args, data=None):
'''
Detect the args and kwargs that need to be passed to a function call, and
check them against what was passed.
'''
argspec = salt.utils.get_function_argspec(func)
_args = []
_kwargs = {}
invalid_kwargs = []
for arg in args:
if isinstance(arg, string_types):
string_arg, string_kwarg = salt.utils.args.parse_input([arg], condition=False) # pylint: disable=W0632
if string_arg:
# Don't append the version that was just derived from parse_cli
# above, that would result in a 2nd call to
# salt.utils.cli.yamlify_arg(), which could mangle the input.
_args.append(arg)
elif string_kwarg:
salt.utils.warn_until(
'Boron',
'The list of function args and kwargs should be parsed '
'by salt.utils.args.parse_input() before calling '
'salt.minion.load_args_and_kwargs().'
)
if argspec.keywords or string_kwarg.keys()[0] in argspec.args:
# Function supports **kwargs or is a positional argument to
# the function.
_kwargs.update(string_kwarg)
else:
# **kwargs not in argspec and parsed argument name not in
# list of positional arguments. This keyword argument is
# invalid.
invalid_kwargs.append('{0}'.format(arg))
continue
# if the arg is a dict with __kwarg__ == True, then its a kwarg
elif isinstance(arg, dict) and arg.pop('__kwarg__', False) is True:
for key, val in arg.iteritems():
if argspec.keywords or key in argspec.args:
# Function supports **kwargs or is a positional argument to
# the function.
_kwargs[key] = val
else:
# **kwargs not in argspec and parsed argument name not in
# list of positional arguments. This keyword argument is
# invalid.
invalid_kwargs.append('{0}'.format(arg))
continue
else:
_args.append(arg)
if invalid_kwargs:
raise SaltInvocationError(
'The following keyword arguments are not valid: {0}'
.format(', '.join(invalid_kwargs))
)
if argspec.keywords and isinstance(data, dict):
# this function accepts **kwargs, pack in the publish data
for key, val in data.items():
_kwargs['__pub_{0}'.format(key)] = val
return _args, _kwargs
class SMinion(object):
'''
Create an object that has loaded all of the minion module functions,
grains, modules, returners etc. The SMinion allows developers to
generate all of the salt minion functions and present them with these
functions for general use.
'''
def __init__(self, opts):
# Late setup of the opts grains, so we can log from the grains module
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
# Clean out the proc directory (default /var/cache/salt/minion/proc)
if self.opts.get('file_client', 'remote') == 'remote':
if isinstance(self.opts['master'], list):
masters = self.opts['master']
if self.opts['random_master'] is True:
shuffle(masters)
self.opts['_safe_auth'] = False
for master in masters:
self.opts['master'] = master
self.opts.update(resolve_dns(opts))
try:
self.gen_modules()
break
except SaltClientError:
log.warning(('Attempted to authenticate with master '
'{0} and failed'.format(master)))
continue
else:
if self.opts['random_master'] is True:
log.warning('random_master is True but there is only one master specified. Ignoring.')
self.opts.update(resolve_dns(opts))
self.gen_modules()
else:
self.gen_modules()
def gen_modules(self):
'''
Load all of the modules for the minion
'''
self.opts['pillar'] = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['environment'],
).compile_pillar()
self.functions = salt.loader.minion_mods(self.opts)
self.returners = salt.loader.returners(self.opts, self.functions)
self.states = salt.loader.states(self.opts, self.functions)
self.rend = salt.loader.render(self.opts, self.functions)
self.matcher = Matcher(self.opts, self.functions)
self.functions['sys.reload_modules'] = self.gen_modules
class MinionBase(object):
def __init__(self, opts):
self.opts = opts
def _init_context_and_poller(self):
self.context = zmq.Context()
self.poller = zmq.Poller()
def _prepare_minion_event_system(self):
# Prepare the minion event system
#
# Start with the publish socket
self._init_context_and_poller()
hash_type = getattr(hashlib, self.opts.get('hash_type', 'md5'))
id_hash = hash_type(self.opts['id']).hexdigest()
if self.opts.get('hash_type', 'md5') == 'sha256':
id_hash = id_hash[:10]
epub_sock_path = os.path.join(
self.opts['sock_dir'],
'minion_event_{0}_pub.ipc'.format(id_hash)
)
if os.path.exists(epub_sock_path):
os.unlink(epub_sock_path)
epull_sock_path = os.path.join(
self.opts['sock_dir'],
'minion_event_{0}_pull.ipc'.format(id_hash)
)
if os.path.exists(epull_sock_path):
os.unlink(epull_sock_path)
self.epub_sock = self.context.socket(zmq.PUB)
if self.opts.get('ipc_mode', '') == 'tcp':
epub_uri = 'tcp://127.0.0.1:{0}'.format(
self.opts['tcp_pub_port']
)
epull_uri = 'tcp://127.0.0.1:{0}'.format(
self.opts['tcp_pull_port']
)
else:
epub_uri = 'ipc://{0}'.format(epub_sock_path)
salt.utils.check_ipc_path_max_len(epub_uri)
epull_uri = 'ipc://{0}'.format(epull_sock_path)
salt.utils.check_ipc_path_max_len(epull_uri)
log.debug(
'{0} PUB socket URI: {1}'.format(
self.__class__.__name__, epub_uri
)
)
log.debug(
'{0} PULL socket URI: {1}'.format(
self.__class__.__name__, epull_uri
)
)
# Check to make sure the sock_dir is available, create if not
default_minion_sock_dir = os.path.join(
salt.syspaths.SOCK_DIR,
'minion'
)
minion_sock_dir = self.opts.get('sock_dir', default_minion_sock_dir)
if not os.path.isdir(minion_sock_dir):
# Let's try to create the directory defined on the configuration
# file
try:
os.makedirs(minion_sock_dir, 0755)
except OSError as exc:
log.error('Could not create SOCK_DIR: {0}'.format(exc))
# Let's not fail yet and try using the default path
if minion_sock_dir == default_minion_sock_dir:
# We're already trying the default system path, stop now!
raise
if not os.path.isdir(default_minion_sock_dir):
try:
os.makedirs(default_minion_sock_dir, 0755)
except OSError as exc:
log.error('Could not create SOCK_DIR: {0}'.format(exc))
# Let's stop at this stage
raise
# Create the pull socket
self.epull_sock = self.context.socket(zmq.PULL)
# Securely bind the event sockets
if self.opts.get('ipc_mode', '') != 'tcp':
old_umask = os.umask(0177)
try:
log.info('Starting pub socket on {0}'.format(epub_uri))
self.epub_sock.bind(epub_uri)
log.info('Starting pull socket on {0}'.format(epull_uri))
self.epull_sock.bind(epull_uri)
finally:
if self.opts.get('ipc_mode', '') != 'tcp':
os.umask(old_umask)
@staticmethod
def process_schedule(minion, loop_interval):
try:
minion.schedule.eval()
# Check if scheduler requires lower loop interval than
# the loop_interval setting
if minion.schedule.loop_interval < loop_interval:
loop_interval = minion.schedule.loop_interval
log.debug(
'Overriding loop_interval because of scheduled jobs.'
)
except Exception as exc:
log.error(
'Exception {0} occurred in scheduled job'.format(exc)
)
return loop_interval
class MasterMinion(object):
'''
Create a fully loaded minion function object for generic use on the
master. What makes this class different is that the pillar is
omitted, otherwise everything else is loaded cleanly.
'''
def __init__(
self,
opts,
returners=True,
states=True,
rend=True,
matcher=True,
whitelist=None):
self.opts = salt.config.minion_config(opts['conf_file'])
self.opts.update(opts)
self.whitelist = whitelist
self.opts['grains'] = salt.loader.grains(opts)
self.opts['pillar'] = {}
self.mk_returners = returners
self.mk_states = states
self.mk_rend = rend
self.mk_matcher = matcher
self.gen_modules()
def gen_modules(self):
'''
Load all of the modules for the minion
'''
self.functions = salt.loader.minion_mods(
self.opts,
whitelist=self.whitelist)
if self.mk_returners:
self.returners = salt.loader.returners(self.opts, self.functions)
if self.mk_states:
self.states = salt.loader.states(self.opts, self.functions)
if self.mk_rend:
self.rend = salt.loader.render(self.opts, self.functions)
if self.mk_matcher:
self.matcher = Matcher(self.opts, self.functions)
self.functions['sys.reload_modules'] = self.gen_modules
class MultiMinion(MinionBase):
'''
Create a multi minion interface, this creates as many minions as are
defined in the master option and binds each minion object to a respective
master.
'''
def __init__(self, opts):
super(MultiMinion, self).__init__(opts)
def _gen_minions(self):
'''
Set up and tune in the minion options
'''
if not isinstance(self.opts['master'], list):
log.error(
'Attempting to start a multimaster system with one master')
return False
minions = []
for master in set(self.opts['master']):
s_opts = copy.copy(self.opts)
s_opts['master'] = master
try:
minions.append(Minion(s_opts, 5, False))
except SaltClientError:
minions.append(s_opts)
return minions
def minions(self):
'''
Return a list of minion generators bound to the tune_in method
'''
ret = {}
minions = self._gen_minions()
for minion in minions:
if isinstance(minion, dict):
ret[minion['master']] = minion
else:
ret[minion.opts['master']] = {
'minion': minion,
'generator': minion.tune_in_no_block()}
return ret
# Multi Master Tune In
def tune_in(self):
'''
Bind to the masters
'''
self._prepare_minion_event_system()
self.poller.register(self.epull_sock, zmq.POLLIN)
module_refresh = False
pillar_refresh = False
# Prepare the minion generators
minions = self.minions()
loop_interval = int(self.opts['loop_interval'])
last = time.time()
auth_wait = self.opts['acceptance_wait_time']
max_wait = auth_wait * 6
while True:
for minion in minions.values():
if isinstance(minion, dict):
continue
if not hasattr(minion, 'schedule'):
continue
loop_interval = self.process_schedule(minion, loop_interval)
socks = dict(self.poller.poll(1))
if socks.get(self.epull_sock) == zmq.POLLIN:
try:
while True:
package = self.epull_sock.recv(zmq.NOBLOCK)
if package.startswith('module_refresh'):
module_refresh = True
elif package.startswith('pillar_refresh'):
pillar_refresh = True
elif package.startswith('fire_master'):
tag, data = salt.utils.event.MinionEvent.unpack(package)
log.debug('Forwarding master event tag={tag}'.format(tag=data['tag']))
self._fire_master(data['data'], data['tag'], data['events'], data['pretag'])
self.epub_sock.send(package)
except Exception:
pass
# get commands from each master
for master, minion in minions.items():
if 'generator' not in minion:
if time.time() - auth_wait > last:
last = time.time()
if auth_wait < max_wait:
auth_wait += auth_wait
try:
if not isinstance(minion, dict):
minions[master] = {'minion': minion}
t_minion = Minion(minion, 5, False)
minions[master]['minion'] = t_minion
minions[master]['generator'] = t_minion.tune_in_no_block()
auth_wait = self.opts['acceptance_wait_time']
except SaltClientError:
continue
else:
continue
if module_refresh:
minion['minion'].module_refresh()
if pillar_refresh:
minion['minion'].pillar_refresh()
minion['generator'].next()
class Minion(MinionBase):
'''
This class instantiates a minion, runs connections for a minion,
and loads all of the functions into the minion
'''
def __init__(self, opts, timeout=60, safe=True):
'''
Pass in the options dict
'''
self._running = None
# Warn if ZMQ < 3.2
if HAS_ZMQ and (not(hasattr(zmq, 'zmq_version_info')) or
zmq.zmq_version_info() < (3, 2)):
# PyZMQ 2.1.9 does not have zmq_version_info
log.warning('You have a version of ZMQ less than ZMQ 3.2! There '
'are known connection keep-alive issues with ZMQ < '
'3.2 which may result in loss of contact with '
'minions. Please upgrade your ZMQ!')
# Late setup the of the opts grains, so we can log from the grains
# module
opts['grains'] = salt.loader.grains(opts)
opts.update(resolve_dns(opts))
super(Minion, self).__init__(opts)
self.authenticate(timeout, safe)
self.opts['pillar'] = salt.pillar.get_pillar(
opts,
opts['grains'],
opts['id'],
opts['environment'],
).compile_pillar()
self.serial = salt.payload.Serial(self.opts)
self.mod_opts = self._prep_mod_opts()
self.functions, self.returners = self._load_modules()
self.matcher = Matcher(self.opts, self.functions)
self.proc_dir = get_proc_dir(opts['cachedir'])
self.schedule = salt.utils.schedule.Schedule(
self.opts,
self.functions,
self.returners)
self.grains_cache = self.opts['grains']
if 'proxy' in self.opts['pillar']:
log.debug('I am {0} and I need to start some proxies for {0}'.format(self.opts['id'],
self.opts['pillar']['proxy']))
for p in self.opts['pillar']['proxy']:
log.debug('Starting {0} proxy.'.format(p))
pid = os.fork()
if pid > 0:
continue
else:
proxyminion = salt.ProxyMinion()
proxyminion.start(self.opts['pillar']['proxy'][p])
self.clean_die(signal.SIGTERM, None)
else:
log.debug('I am {0} and I am not supposed to start any proxies. '
'(Likely not a problem)'.format(self.opts['id']))
def _prep_mod_opts(self):
'''
Returns a copy of the opts with key bits stripped out
'''
mod_opts = {}
for key, val in self.opts.items():
if key == 'logger':
continue
mod_opts[key] = val
return mod_opts
def _load_modules(self):
'''
Return the functions and the returners loaded up from the loader
module
'''
# if this is a *nix system AND modules_max_memory is set, lets enforce
# a memory limit on module imports
# this feature ONLY works on *nix like OSs (resource module doesn't work on windows)
modules_max_memory = False
if self.opts.get('modules_max_memory', -1) > 0 and HAS_PSUTIL and HAS_RESOURCE:
log.debug('modules_max_memory set, enforcing a maximum of {0}'.format(self.opts['modules_max_memory']))
modules_max_memory = True
old_mem_limit = resource.getrlimit(resource.RLIMIT_AS)
rss, vms = psutil.Process(os.getpid()).get_memory_info()
mem_limit = rss + vms + self.opts['modules_max_memory']
resource.setrlimit(resource.RLIMIT_AS, (mem_limit, mem_limit))
elif self.opts.get('modules_max_memory', -1) > 0:
if not HAS_PSUTIL:
log.error('Unable to enforce modules_max_memory because psutil is missing')
if not HAS_RESOURCE:
log.error('Unable to enforce modules_max_memory because resource is missing')
self.opts['grains'] = salt.loader.grains(self.opts)
functions = salt.loader.minion_mods(self.opts)
returners = salt.loader.returners(self.opts, functions)
# we're done, reset the limits!
if modules_max_memory is True:
resource.setrlimit(resource.RLIMIT_AS, old_mem_limit)
return functions, returners
def _fire_master(self, data=None, tag=None, events=None, pretag=None):
'''
Fire an event on the master, or drop message if unable to send.
'''
load = {'id': self.opts['id'],
'cmd': '_minion_event',
'pretag': pretag,
'tok': self.tok}
if events:
load['events'] = events
elif data and tag:
load['data'] = data
load['tag'] = tag
else:
return
sreq = salt.payload.SREQ(self.opts['master_uri'])
try:
result = sreq.send('aes', self.crypticle.dumps(load))
try:
data = self.crypticle.loads(result)
except AuthenticationError:
log.info("AES key changed, re-authenticating")
# We can't decode the master's response to our event,
# so we will need to re-authenticate.
self.authenticate()
except SaltReqTimeoutError:
log.info("Master failed to respond. Preforming re-authenticating")
self.authenticate()
except Exception:
log.info("fire_master failed: {0}".format(traceback.format_exc()))
def _handle_payload(self, payload):
'''
Takes a payload from the master publisher and does whatever the
master wants done.
'''
{'aes': self._handle_aes,
'pub': self._handle_pub,
'clear': self._handle_clear}[payload['enc']](payload['load'],
payload['sig'] if 'sig' in payload else None)
def _handle_aes(self, load, sig=None):
'''
Takes the AES encrypted load, checks the signature if pub signatures
are turned on, decrypts it, and runs the encapsulated instructions
'''
# Verify that the signature is valid
master_pubkey_path = os.path.join(self.opts['pki_dir'], 'minion_master.pub')
if sig and self.functions['config.get']('sign_pub_messages'):
if not salt.crypt.verify_signature(master_pubkey_path, load, sig):
raise AuthenticationError('Message signature failed to validate.')
try:
data = self.crypticle.loads(load)
except AuthenticationError:
# decryption of the payload failed, try to re-auth but wait
# random seconds if set in config with random_reauth_delay
if 'random_reauth_delay' in self.opts:
reauth_delay = randint(0, int(self.opts['random_reauth_delay']))
log.debug('Waiting {0} seconds to re-authenticate'.format(reauth_delay))
time.sleep(reauth_delay)
self.authenticate()
data = self.crypticle.loads(load)
# Verify that the publication is valid
if 'tgt' not in data or 'jid' not in data or 'fun' not in data \
or 'arg' not in data:
return
# Verify that the publication applies to this minion
# It's important to note that the master does some pre-processing
# to determine which minions to send a request to. So for example,
# a "salt -G 'grain_key:grain_val' test.ping" will invoke some
# pre-processing on the master and this minion should not see the
# publication if the master does not determine that it should.
if 'tgt_type' in data:
match_func = getattr(self.matcher,
'{0}_match'.format(data['tgt_type']), None)
if match_func is None or not match_func(data['tgt']):
return
else:
if not self.matcher.glob_match(data['tgt']):
return
# If the minion does not have the function, don't execute,
# this prevents minions that could not load a minion module
# from returning a predictable exception
#if data['fun'] not in self.functions:
# return
if 'user' in data:
log.info(
'User {0[user]} Executing command {0[fun]} with jid '
'{0[jid]}'.format(data)
)
else:
log.info(
'Executing command {0[fun]} with jid {0[jid]}'.format(data)
)
log.debug('Command details {0}'.format(data))
self._handle_decoded_payload(data)
def _handle_pub(self, load):
'''
Handle public key payloads
'''
pass
def _handle_clear(self, load):
'''
Handle un-encrypted transmissions
'''
pass
def _handle_decoded_payload(self, data):
'''
Override this method if you wish to handle the decoded data
differently.
'''
if isinstance(data['fun'], string_types):
if data['fun'] == 'sys.reload_modules':
self.functions, self.returners = self._load_modules()
self.schedule.functions = self.functions
self.schedule.returners = self.returners
if isinstance(data['fun'], tuple) or isinstance(data['fun'], list):
target = Minion._thread_multi_return
else:
target = Minion._thread_return
# We stash an instance references to allow for the socket
# communication in Windows. You can't pickle functions, and thus
# python needs to be able to reconstruct the reference on the other
# side.
instance = self
if self.opts['multiprocessing']:
if sys.platform.startswith('win'):
# let python reconstruct the minion on the other side if we're
# running on windows
instance = None
process = multiprocessing.Process(
target=target, args=(instance, self.opts, data)
)
else:
process = threading.Thread(
target=target, args=(instance, self.opts, data),
name=data['jid']
)
process.start()
if not sys.platform.startswith('win'):
process.join()
@classmethod
def _thread_return(cls, minion_instance, opts, data):
'''
This method should be used as a threading target, start the actual
minion side execution.
'''
# this seems awkward at first, but it's a workaround for Windows
# multiprocessing communication.
if not minion_instance:
minion_instance = cls(opts)
fn_ = os.path.join(minion_instance.proc_dir, data['jid'])
if opts['multiprocessing']:
salt.utils.daemonize_if(opts)
sdata = {'pid': os.getpid()}
sdata.update(data)
log.info('Starting a new job with PID {0}'.format(sdata['pid']))
with salt.utils.fopen(fn_, 'w+b') as fp_:
fp_.write(minion_instance.serial.dumps(sdata))
ret = {'success': False}
function_name = data['fun']
if function_name in minion_instance.functions:
try:
func = minion_instance.functions[data['fun']]
args, kwargs = load_args_and_kwargs(
func,
data['arg'],
data)
sys.modules[func.__module__].__context__['retcode'] = 0
return_data = func(*args, **kwargs)
if isinstance(return_data, types.GeneratorType):
ind = 0
iret = {}
for single in return_data:
if isinstance(single, dict) and isinstance(iret, list):
iret.update(single)
else:
if not iret:
iret = []
iret.append(single)
tag = tagify([data['jid'], 'prog', opts['id'], str(ind)], 'job')
event_data = {'return': single}
minion_instance._fire_master(event_data, tag)
ind += 1
ret['return'] = iret
else:
ret['return'] = return_data
ret['retcode'] = sys.modules[func.__module__].__context__.get(
'retcode',
0
)
ret['success'] = True
except CommandNotFoundError as exc:
msg = 'Command required for {0!r} not found'.format(
function_name
)
log.debug(msg, exc_info=True)
ret['return'] = '{0}: {1}'.format(msg, exc)
ret['out'] = 'nested'
except CommandExecutionError as exc:
log.error(
'A command in {0!r} had a problem: {1}'.format(
function_name,
exc
),
exc_info=log.isEnabledFor(logging.DEBUG)
)
ret['return'] = 'ERROR: {0}'.format(exc)
ret['out'] = 'nested'
except SaltInvocationError as exc:
log.error(
'Problem executing {0!r}: {1}'.format(
function_name,
exc
),
exc_info=log.isEnabledFor(logging.DEBUG)
)
ret['return'] = 'ERROR executing {0!r}: {1}'.format(
function_name, exc
)
ret['out'] = 'nested'
except TypeError as exc:
trb = traceback.format_exc()
aspec = salt.utils.get_function_argspec(
minion_instance.functions[data['fun']]
)
msg = ('TypeError encountered executing {0}: {1}. See '
'debug log for more info. Possibly a missing '
'arguments issue: {2}').format(function_name,
exc,
aspec)
log.warning(msg, exc_info=log.isEnabledFor(logging.DEBUG))
ret['return'] = msg
ret['out'] = 'nested'
except Exception:
msg = 'The minion function caused an exception'
log.warning(msg, exc_info=log.isEnabledFor(logging.DEBUG))
ret['return'] = '{0}: {1}'.format(msg, traceback.format_exc())
ret['out'] = 'nested'
else:
ret['return'] = '{0!r} is not available.'.format(function_name)
ret['out'] = 'nested'
ret['jid'] = data['jid']
ret['fun'] = data['fun']
ret['fun_args'] = data['arg']
minion_instance._return_pub(ret)
if data['ret']:
ret['id'] = opts['id']
for returner in set(data['ret'].split(',')):
try:
minion_instance.returners['{0}.returner'.format(
returner
)](ret)
except Exception as exc:
log.error(
'The return failed for job {0} {1}'.format(
data['jid'],
exc
)
)
@classmethod
def _thread_multi_return(cls, minion_instance, opts, data):
'''
This method should be used as a threading target, start the actual
minion side execution.
'''
# this seems awkward at first, but it's a workaround for Windows
# multiprocessing communication.
if not minion_instance:
minion_instance = cls(opts)
ret = {
'return': {},
'success': {},
}
for ind in range(0, len(data['fun'])):
ret['success'][data['fun'][ind]] = False
try:
func = minion_instance.functions[data['fun'][ind]]
args, kwargs = load_args_and_kwargs(
func,
data['arg'][ind],
data)
ret['return'][data['fun'][ind]] = func(*args, **kwargs)
ret['success'][data['fun'][ind]] = True
except Exception as exc:
trb = traceback.format_exc()
log.warning(
'The minion function caused an exception: {0}'.format(
exc
)
)
ret['return'][data['fun'][ind]] = trb
ret['jid'] = data['jid']
ret['fun'] = data['fun']
ret['fun_args'] = data['arg']
minion_instance._return_pub(ret)
if data['ret']:
for returner in set(data['ret'].split(',')):
ret['id'] = opts['id']
try:
minion_instance.returners['{0}.returner'.format(
returner
)](ret)
except Exception as exc:
log.error(
'The return failed for job {0} {1}'.format(
data['jid'],
exc
)
)
def _return_pub(self, ret, ret_cmd='_return'):
'''
Return the data from the executed command to the master server
'''
jid = ret.get('jid', ret.get('__jid__'))
fun = ret.get('fun', ret.get('__fun__'))
if self.opts['multiprocessing']:
fn_ = os.path.join(self.proc_dir, jid)
if os.path.isfile(fn_):
try:
os.remove(fn_)
except (OSError, IOError):
# The file is gone already
pass
log.info('Returning information for job: {0}'.format(jid))
sreq = salt.payload.SREQ(self.opts['master_uri'])
if ret_cmd == '_syndic_return':
load = {'cmd': ret_cmd,
'id': self.opts['id'],
'jid': jid,
'fun': fun,
'load': ret.get('__load__')}
load['return'] = {}
for key, value in ret.items():
if key.startswith('__'):
continue
load['return'][key] = value
else:
load = {'cmd': ret_cmd,
'id': self.opts['id']}
for key, value in ret.items():
load[key] = value
if 'out' in ret:
if isinstance(ret['out'], string_types):
load['out'] = ret['out']
else:
log.error('Invalid outputter {0}. This is likely a bug.'
.format(ret['out']))
else:
try:
oput = self.functions[fun].__outputter__
except (KeyError, AttributeError, TypeError):
pass
else:
if isinstance(oput, string_types):
load['out'] = oput
if self.opts['cache_jobs']:
# Local job cache has been enabled
fn_ = os.path.join(
self.opts['cachedir'],
'minion_jobs',
load['jid'],
'return.p')
jdir = os.path.dirname(fn_)
if not os.path.isdir(jdir):
os.makedirs(jdir)
salt.utils.fopen(fn_, 'w+b').write(self.serial.dumps(ret))
try:
ret_val = sreq.send('aes', self.crypticle.dumps(load))
except SaltReqTimeoutError:
msg = ('The minion failed to return the job information for job '
'{0}. This is often due to the master being shut down or '
'overloaded. If the master is running consider incresing '
'the worker_threads value.').format(jid)
log.warn(msg)
return ''
if isinstance(ret_val, string_types) and not ret_val:
# The master AES key has changed, reauth
self.authenticate()
ret_val = sreq.send('aes', self.crypticle.dumps(load))
log.trace('ret_val = {0}'.format(ret_val))
return ret_val
def _state_run(self):
'''
Execute a state run based on information set in the minion config file
'''
if self.opts['startup_states']:
data = {'jid': 'req', 'ret': self.opts.get('ext_job_cache', '')}
if self.opts['startup_states'] == 'sls':
data['fun'] = 'state.sls'
data['arg'] = [self.opts['sls_list']]
elif self.opts['startup_states'] == 'top':
data['fun'] = 'state.top'
data['arg'] = [self.opts['top_file']]
else:
data['fun'] = 'state.highstate'
data['arg'] = []
self._handle_decoded_payload(data)
def _refresh_grains_watcher(self, refresh_interval_in_minutes):
'''
Create a loop that will fire a pillar refresh to inform a master about a change in the grains of this minion
:param refresh_interval_in_minutes:
:return: None
'''
if '__update_grains' not in self.opts.get('schedule', {}):
if not 'schedule' in self.opts:
self.opts['schedule'] = {}
self.opts['schedule'].update({
'__update_grains':
{
'function': 'event.fire',
'args': [{}, 'grains_refresh'],
'minutes': refresh_interval_in_minutes
}
})
def _set_tcp_keepalive(self):
if hasattr(zmq, 'TCP_KEEPALIVE'):
self.socket.setsockopt(
zmq.TCP_KEEPALIVE, self.opts['tcp_keepalive']
)
self.socket.setsockopt(
zmq.TCP_KEEPALIVE_IDLE, self.opts['tcp_keepalive_idle']
)
self.socket.setsockopt(
zmq.TCP_KEEPALIVE_CNT, self.opts['tcp_keepalive_cnt']
)
self.socket.setsockopt(
zmq.TCP_KEEPALIVE_INTVL, self.opts['tcp_keepalive_intvl']
)
def _set_reconnect_ivl(self):
recon_delay = self.opts['recon_default']
if self.opts['recon_randomize']:
recon_delay = randint(self.opts['recon_default'],
self.opts['recon_default'] + self.opts['recon_max']
)
log.debug("Generated random reconnect delay between '{0}ms' and '{1}ms' ({2})".format(
self.opts['recon_default'],
self.opts['recon_default'] + self.opts['recon_max'],
recon_delay)
)
log.debug("Setting zmq_reconnect_ivl to '{0}ms'".format(recon_delay))
self.socket.setsockopt(zmq.RECONNECT_IVL, recon_delay)
def _set_reconnect_ivl_max(self):
if hasattr(zmq, 'RECONNECT_IVL_MAX'):
log.debug("Setting zmq_reconnect_ivl_max to '{0}ms'".format(
self.opts['recon_default'] + self.opts['recon_max'])
)
self.socket.setsockopt(
zmq.RECONNECT_IVL_MAX, self.opts['recon_max']
)
def _set_ipv4only(self):
if self.opts['ipv6'] is True and hasattr(zmq, 'IPV4ONLY'):
# IPv6 sockets work for both IPv6 and IPv4 addresses
self.socket.setsockopt(zmq.IPV4ONLY, 0)
def _fire_master_minion_start(self):
# Send an event to the master that the minion is live
self._fire_master(
'Minion {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
'minion_start'
)
# dup name spaced event
self._fire_master(
'Minion {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
tagify([self.opts['id'], 'start'], 'minion'),
)
def _setsockopts(self):
self.socket.setsockopt(zmq.SUBSCRIBE, '')
self.socket.setsockopt(zmq.IDENTITY, self.opts['id'])
self._set_ipv4only()
self._set_reconnect_ivl_max()
self._set_tcp_keepalive()
@property
def master_pub(self):
'''
Return the master publish port
'''
return 'tcp://{ip}:{port}'.format(ip=self.opts['master_ip'],
port=self.publish_port)
def authenticate(self, timeout=60, safe=True):
'''
Authenticate with the master, this method breaks the functional
paradigm, it will update the master information from a fresh sign
in, signing in can occur as often as needed to keep up with the
revolving master AES key.
'''
log.debug(
'Attempting to authenticate with the Salt Master at {0}'.format(
self.opts['master_ip']
)
)
auth = salt.crypt.Auth(self.opts)
self.tok = auth.gen_token('salt')
acceptance_wait_time = self.opts['acceptance_wait_time']
acceptance_wait_time_max = self.opts['acceptance_wait_time_max']
if not acceptance_wait_time_max:
acceptance_wait_time_max = acceptance_wait_time
tries = self.opts.get('auth_tries', 1)
safe = self.opts.get('auth_safemode', safe)
while True:
creds = auth.sign_in(timeout, safe, tries)
if creds != 'retry':
log.info('Authentication with master successful!')
break
log.info('Waiting for minion key to be accepted by the master.')
if acceptance_wait_time:
log.info('Waiting {0} seconds before retry.'.format(acceptance_wait_time))
time.sleep(acceptance_wait_time)
if acceptance_wait_time < acceptance_wait_time_max:
acceptance_wait_time += acceptance_wait_time
log.debug('Authentication wait time is {0}'.format(acceptance_wait_time))
self.aes = creds['aes']
if self.opts.get('syndic_master_publish_port'):
self.publish_port = self.opts.get('syndic_master_publish_port')
else:
self.publish_port = creds['publish_port']
self.crypticle = salt.crypt.Crypticle(self.opts, self.aes)
def module_refresh(self):
'''
Refresh the functions and returners.
'''
self.functions, self.returners = self._load_modules()
self.schedule.functions = self.functions
self.schedule.returners = self.returners
def pillar_refresh(self):
'''
Refresh the pillar
'''
self.opts['pillar'] = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['environment'],
).compile_pillar()
self.module_refresh()
def environ_setenv(self, package):
'''
Set the salt-minion main process environment according to
the data contained in the minion event data
'''
tag, data = salt.utils.event.MinionEvent.unpack(package)
environ = data.get('environ', None)
if environ is None:
return False
false_unsets = data.get('false_unsets', False)
clear_all = data.get('clear_all', False)
import salt.modules.environ as mod_environ
return mod_environ.setenv(environ, false_unsets, clear_all)
def clean_die(self, signum, frame):
'''
Python does not handle the SIGTERM cleanly, if it is signaled exit
the minion process cleanly
'''
self._running = False
exit(0)
def _pre_tune(self):
'''
Set the minion running flag and issue the appropriate warnings if
the minion cannot be started or is already running
'''
if self._running is None:
self._running = True
elif self._running is False:
log.error(
'This {0} was scheduled to stop. Not running '
'{0}.tune_in()'.format(self.__class__.__name__)
)
return
elif self._running is True:
log.error(
'This {0} is already running. Not running '
'{0}.tune_in()'.format(self.__class__.__name__)
)
return
try:
log.info(
'{0} is starting as user \'{1}\''.format(
self.__class__.__name__,
salt.utils.get_user()
)
)
except Exception as err:
# Only windows is allowed to fail here. See #3189. Log as debug in
# that case. Else, error.
log.log(
salt.utils.is_windows() and logging.DEBUG or logging.ERROR,
'Failed to get the user who is starting {0}'.format(
self.__class__.__name__
),
exc_info=err
)
# Main Minion Tune In
def tune_in(self):
'''
Lock onto the publisher. This is the main event loop for the minion
:rtype : None
'''
self._pre_tune()
# Properly exit if a SIGTERM is signalled
signal.signal(signal.SIGTERM, self.clean_die)
log.debug('Minion {0!r} trying to tune in'.format(self.opts['id']))
self._prepare_minion_event_system()
self.socket = self.context.socket(zmq.SUB)
self._set_reconnect_ivl()
self._setsockopts()
self.socket.connect(self.master_pub)
self.poller.register(self.socket, zmq.POLLIN)
self.poller.register(self.epull_sock, zmq.POLLIN)
self._fire_master_minion_start()
# Make sure to gracefully handle SIGUSR1
enable_sigusr1_handler()
# Make sure to gracefully handle CTRL_LOGOFF_EVENT
salt.utils.enable_ctrl_logoff_handler()
# On first startup execute a state run if configured to do so
self._state_run()
time.sleep(.5)
loop_interval = int(self.opts['loop_interval'])
try:
if self.opts['grains_refresh_every']: # If exists and is not zero. In minutes, not seconds!
if self.opts['grains_refresh_every'] > 1:
log.debug(
'Enabling the grains refresher. Will run every {0} minutes.'.format(
self.opts['grains_refresh_every'])
)
else: # Clean up minute vs. minutes in log message
log.debug(
'Enabling the grains refresher. Will run every {0} minute.'.format(
self.opts['grains_refresh_every'])
)
self._refresh_grains_watcher(
abs(self.opts['grains_refresh_every'])
)
except Exception as exc:
log.error(
'Exception occurred in attempt to initialize grain refresh routine during minion tune-in: {0}'.format(
exc)
)
ping_interval = self.opts.get('ping_interval', 0) * 60
ping_at = None
while self._running is True:
loop_interval = self.process_schedule(self, loop_interval)
try:
socks = self._do_poll(loop_interval)
if ping_interval > 0:
if socks or not ping_at:
ping_at = time.time() + ping_interval
if ping_at < time.time():
log.debug('Ping master')
self._fire_master('ping', 'minion_ping')
ping_at = time.time() + ping_interval
self._do_socket_recv(socks)
# Check the event system
if socks.get(self.epull_sock) == zmq.POLLIN:
package = self.epull_sock.recv(zmq.NOBLOCK)
log.debug('Handling event {0!r}'.format(package))
try:
if package.startswith('module_refresh'):
self.module_refresh()
elif package.startswith('pillar_refresh'):
self.pillar_refresh()
elif package.startswith('grains_refresh'):
if self.grains_cache != self.opts['grains']:
self.pillar_refresh()
self.grains_cache = self.opts['grains']
elif package.startswith('environ_setenv'):
self.environ_setenv(package)
elif package.startswith('fire_master'):
tag, data = salt.utils.event.MinionEvent.unpack(package)
log.debug('Forwarding master event tag={tag}'.format(tag=data['tag']))
self._fire_master(data['data'], data['tag'], data['events'], data['pretag'])
self.epub_sock.send(package)
except Exception:
log.debug('Exception while handling events', exc_info=True)
# Add an extra fallback in case a forked process leeks through
multiprocessing.active_children()
except zmq.ZMQError as exc:
# The interrupt caused by python handling the
# SIGCHLD. Throws this error with errno == EINTR.
# Nothing to recieve on the zmq socket throws this error
# with EAGAIN.
# Both are safe to ignore
if exc.errno != errno.EAGAIN and exc.errno != errno.EINTR:
log.critical('Unexpected ZMQError while polling minion',
exc_info=True)
continue
except SaltClientError:
raise
except Exception:
log.critical(
'An exception occurred while polling the minion',
exc_info=True
)
def tune_in_no_block(self):
'''
Executes the tune_in sequence but omits extra logging and the
management of the event bus assuming that these are handled outside
the tune_in sequence
'''
self._pre_tune()
self._init_context_and_poller()
self.socket = self.context.socket(zmq.SUB)
self._setsockopts()
self.socket.connect(self.master_pub)
self.poller.register(self.socket, zmq.POLLIN)
self._fire_master_minion_start()
loop_interval = int(self.opts['loop_interval'])
# On first startup execute a state run if configured to do so
self._state_run()
time.sleep(.5)
while self._running is True:
try:
socks = self._do_poll(loop_interval)
self._do_socket_recv(socks)
# Check the event system
except zmq.ZMQError:
# If a zeromq error happens recover
yield True
except Exception:
log.critical(
'An exception occurred while polling the minion',
exc_info=True
)
yield True
def _do_poll(self, loop_interval):
log.trace('Check main poller timeout {0}'.format(loop_interval))
return dict(self.poller.poll(
loop_interval * 1000)
)
def _do_socket_recv(self, socks):
if socks.get(self.socket) == zmq.POLLIN:
payload = self.serial.loads(self.socket.recv(zmq.NOBLOCK))
log.trace('Handling payload')
self._handle_payload(payload)
def destroy(self):
'''
Tear down the minion
'''
self._running = False
if getattr(self, 'poller', None) is not None:
if isinstance(self.poller.sockets, dict):
for socket in self.poller.sockets.keys():
if socket.closed is False:
socket.close()
self.poller.unregister(socket)
else:
for socket in self.poller.sockets:
if socket[0].closed is False:
socket[0].close()
self.poller.unregister(socket[0])
if hasattr(self, 'epub_sock') and self.epub_sock.closed is False:
self.epub_sock.close()
if hasattr(self, 'epull_sock') and self.epull_sock.closed is False:
self.epull_sock.close()
if hasattr(self, 'socket') and self.socket.closed is False:
self.socket.close()
if hasattr(self, 'context') and self.context.closed is False:
self.context.term()
def __del__(self):
self.destroy()
class Syndic(Minion):
'''
Make a Syndic minion, this minion will use the minion keys on the
master to authenticate with a higher level master.
'''
def __init__(self, opts):
self._syndic_interface = opts.get('interface')
self._syndic = True
opts['loop_interval'] = 1
super(Syndic, self).__init__(opts)
self.mminion = salt.minion.MasterMinion(opts)
def _handle_aes(self, load, sig=None):
'''
Takes the AES encrypted load, decrypts it, and runs the encapsulated
instructions
'''
# If the AES authentication has changed, re-authenticate
try:
data = self.crypticle.loads(load)
except AuthenticationError:
self.authenticate()
data = self.crypticle.loads(load)
# Verify that the publication is valid
if 'tgt' not in data or 'jid' not in data or 'fun' not in data \
or 'to' not in data or 'arg' not in data:
return
data['to'] = int(data['to']) - 1
if 'user' in data:
log.debug(
'User {0[user]} Executing syndic command {0[fun]} with '
'jid {0[jid]}'.format(
data
)
)
else:
log.debug(
'Executing syndic command {0[fun]} with jid {0[jid]}'.format(
data
)
)
log.debug('Command details: {0}'.format(data))
self._handle_decoded_payload(data)
def _handle_decoded_payload(self, data):
'''
Override this method if you wish to handle the decoded data
differently.
'''
self.syndic_cmd(data)
def syndic_cmd(self, data):
'''
Take the now clear load and forward it on to the client cmd
'''
# Set up default tgt_type
if 'tgt_type' not in data:
data['tgt_type'] = 'glob'
# Send out the publication
self.local.pub(data['tgt'],
data['fun'],
data['arg'],
data['tgt_type'],
data['ret'],
data['jid'],
data['to'])
# Syndic Tune In
def tune_in(self):
'''
Lock onto the publisher. This is the main event loop for the syndic
'''
# Instantiate the local client
self.local = salt.client.get_local_client(self.opts['_minion_conf_file'])
self.local.event.subscribe('')
self.local.opts['interface'] = self._syndic_interface
signal.signal(signal.SIGTERM, self.clean_die)
log.debug('Syndic {0!r} trying to tune in'.format(self.opts['id']))
self.context = zmq.Context()
# Start with the publish socket
# Share the poller with the event object
self.poller = self.local.event.poller
self.socket = self.context.socket(zmq.SUB)
self.socket.setsockopt(zmq.SUBSCRIBE, '')
self.socket.setsockopt(zmq.IDENTITY, self.opts['id'])
if hasattr(zmq, 'RECONNECT_IVL_MAX'):
self.socket.setsockopt(
zmq.RECONNECT_IVL_MAX, self.opts['recon_max']
)
if hasattr(zmq, 'TCP_KEEPALIVE'):
self.socket.setsockopt(
zmq.TCP_KEEPALIVE, self.opts['tcp_keepalive']
)
self.socket.setsockopt(
zmq.TCP_KEEPALIVE_IDLE, self.opts['tcp_keepalive_idle']
)
self.socket.setsockopt(
zmq.TCP_KEEPALIVE_CNT, self.opts['tcp_keepalive_cnt']
)
self.socket.setsockopt(
zmq.TCP_KEEPALIVE_INTVL, self.opts['tcp_keepalive_intvl']
)
self.socket.connect(self.master_pub)
self.poller.register(self.socket, zmq.POLLIN)
# Send an event to the master that the minion is live
self._fire_master(
'Syndic {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
'syndic_start'
)
self._fire_master(
'Syndic {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
tagify([self.opts['id'], 'start'], 'syndic'),
)
# Make sure to gracefully handle SIGUSR1
enable_sigusr1_handler()
loop_interval = int(self.opts['loop_interval'])
self._reset_event_aggregation()
while True:
try:
# Do all the maths in seconds
timeout = loop_interval
if self.event_forward_timeout is not None:
timeout = min(timeout,
self.event_forward_timeout - time.time())
if timeout >= 0:
log.trace('Polling timeout: %f', timeout)
socks = dict(self.poller.poll(timeout * 1000))
else:
# This shouldn't really happen.
# But there's no harm being defensive
log.warning('Negative timeout in syndic main loop')
socks = {}
if socks.get(self.socket) == zmq.POLLIN:
self._process_cmd_socket()
if socks.get(self.local.event.sub) == zmq.POLLIN:
self._process_event_socket()
if (self.event_forward_timeout is not None and
self.event_forward_timeout < time.time()):
self._forward_events()
# We don't handle ZMQErrors like the other minions
# I've put explicit handling around the recieve calls
# in the process_*_socket methods. If we see any other
# errors they may need some kind of handling so log them
# for now.
except Exception:
log.critical(
'An exception occurred while polling the syndic',
exc_info=True
)
def _process_cmd_socket(self):
try:
payload = self.serial.loads(self.socket.recv(zmq.NOBLOCK))
except zmq.ZMQError as e:
# Swallow errors for bad wakeups or signals needing processing
if e.errno != errno.EAGAIN and e.errno != errno.EINTR:
raise
log.trace('Handling payload')
self._handle_payload(payload)
def _reset_event_aggregation(self):
self.jids = {}
self.raw_events = []
self.event_forward_timeout = None
def _process_event_socket(self):
tout = time.time() + self.opts['syndic_max_event_process_time']
while tout > time.time():
try:
event = self.local.event.get_event_noblock()
except zmq.ZMQError as e:
# EAGAIN indicates no more events at the moment
# EINTR some kind of signal maybe someone trying
# to get us to quit so escape our timeout
if e.errno == errno.EAGAIN or e.errno == errno.EINTR:
break
raise
log.trace('Got event {0}'.format(event['tag']))
if self.event_forward_timeout is None:
self.event_forward_timeout = (
time.time() + self.opts['syndic_event_forward_timeout']
)
if salt.utils.is_jid(event['tag']) and 'return' in event['data']:
if not 'jid' in event['data']:
# Not a job return
continue
jdict = self.jids.setdefault(event['tag'], {})
if not jdict:
jdict['__fun__'] = event['data'].get('fun')
jdict['__jid__'] = event['data']['jid']
jdict['__load__'] = {}
fstr = '{0}.get_jid'.format(self.opts['master_job_cache'])
jdict['__load__'].update(
self.mminion.returners[fstr](event['data']['jid'])
)
jdict[event['data']['id']] = event['data']['return']
else:
# Add generic event aggregation here
if not 'retcode' in event['data']:
self.raw_events.append(event)
def _forward_events(self):
log.trace('Forwarding events')
if self.raw_events:
self._fire_master(events=self.raw_events,
pretag=tagify(self.opts['id'], base='syndic'),
)
for jid in self.jids:
self._return_pub(self.jids[jid], '_syndic_return')
self._reset_event_aggregation()
def destroy(self):
'''
Tear down the syndic minion
'''
# We borrowed the local clients poller so give it back before
# it's destroyed. Reset the local poller reference.
self.poller = None
super(Syndic, self).destroy()
if hasattr(self, 'local'):
del self.local
class Matcher(object):
'''
Use to return the value for matching calls from the master
'''
def __init__(self, opts, functions=None):
self.opts = opts
if functions is None:
functions = salt.loader.minion_mods(self.opts)
self.functions = functions
def confirm_top(self, match, data, nodegroups=None):
'''
Takes the data passed to a top file environment and determines if the
data matches this minion
'''
matcher = 'compound'
if not data:
log.error('Received bad data when setting the match from the top '
'file')
return False
for item in data:
if isinstance(item, dict):
if 'match' in item:
matcher = item['match']
if hasattr(self, matcher + '_match'):
funcname = '{0}_match'.format(matcher)
if matcher == 'nodegroup':
return getattr(self, funcname)(match, nodegroups)
return getattr(self, funcname)(match)
else:
log.error('Attempting to match with unknown matcher: {0}'.format(
matcher
))
return False
def glob_match(self, tgt):
'''
Returns true if the passed glob matches the id
'''
if type(tgt) != str:
return False
return fnmatch.fnmatch(self.opts['id'], tgt)
def pcre_match(self, tgt):
'''
Returns true if the passed pcre regex matches
'''
return bool(re.match(tgt, self.opts['id']))
def list_match(self, tgt):
'''
Determines if this host is on the list
'''
if isinstance(tgt, string_types):
tgt = tgt.split(',')
return bool(self.opts['id'] in tgt)
def grain_match(self, tgt, delim=':'):
'''
Reads in the grains glob match
'''
log.debug('grains target: {0}'.format(tgt))
if delim not in tgt:
log.error('Got insufficient arguments for grains match '
'statement from master')
return False
return salt.utils.subdict_match(self.opts['grains'], tgt, delim=delim)
def grain_pcre_match(self, tgt, delim=':'):
'''
Matches a grain based on regex
'''
log.debug('grains pcre target: {0}'.format(tgt))
if delim not in tgt:
log.error('Got insufficient arguments for grains pcre match '
'statement from master')
return False
return salt.utils.subdict_match(self.opts['grains'], tgt,
delim=delim, regex_match=True)
def data_match(self, tgt):
'''
Match based on the local data store on the minion
'''
comps = tgt.split(':')
if len(comps) < 2:
return False
val = self.functions['data.getval'](comps[0])
if val is None:
# The value is not defined
return False
if isinstance(val, list):
# We are matching a single component to a single list member
for member in val:
if fnmatch.fnmatch(str(member).lower(), comps[1].lower()):
return True
return False
if isinstance(val, dict):
if comps[1] in val:
return True
return False
return bool(fnmatch.fnmatch(
val,
comps[1],
))
def exsel_match(self, tgt):
'''
Runs a function and return the exit code
'''
if tgt not in self.functions:
return False
return self.functions[tgt]()
def pillar_match(self, tgt, delim=':'):
'''
Reads in the pillar glob match
'''
log.debug('pillar target: {0}'.format(tgt))
if delim not in tgt:
log.error('Got insufficient arguments for pillar match '
'statement from master')
return False
return salt.utils.subdict_match(self.opts['pillar'], tgt, delim=delim)
def ipcidr_match(self, tgt):
'''
Matches based on ip address or CIDR notation
'''
num_parts = len(tgt.split('/'))
if num_parts > 2:
# Target is not valid CIDR
return False
elif num_parts == 2:
# Target is CIDR
return salt.utils.network.in_subnet(
tgt,
addrs=self.opts['grains'].get('ipv4', [])
)
else:
# Target is an IPv4 address
import socket
try:
socket.inet_aton(tgt)
except socket.error:
# Not a valid IPv4 address
return False
else:
return tgt in self.opts['grains'].get('ipv4', [])
def range_match(self, tgt):
'''
Matches based on range cluster
'''
if HAS_RANGE:
range_ = seco.range.Range(self.opts['range_server'])
try:
return self.opts['grains']['fqdn'] in range_.expand(tgt)
except seco.range.RangeException as exc:
log.debug('Range exception in compound match: {0}'.format(exc))
return False
return False
def compound_match(self, tgt):
'''
Runs the compound target check
'''
if not isinstance(tgt, string_types):
log.debug('Compound target received that is not a string')
return False
ref = {'G': 'grain',
'P': 'grain_pcre',
'I': 'pillar',
'L': 'list',
'S': 'ipcidr',
'E': 'pcre'}
if HAS_RANGE:
ref['R'] = 'range'
results = []
opers = ['and', 'or', 'not', '(', ')']
tokens = tgt.split()
for match in tokens:
# Try to match tokens from the compound target, first by using
# the 'G, X, I, L, S, E' matcher types, then by hostname glob.
if '@' in match and match[1] == '@':
comps = match.split('@')
matcher = ref.get(comps[0])
if not matcher:
# If an unknown matcher is called at any time, fail out
return False
results.append(
str(
getattr(self, '{0}_match'.format(matcher))(
'@'.join(comps[1:])
)
)
)
elif match in opers:
# We didn't match a target, so append a boolean operator or
# subexpression
if results or match in ['(', ')']:
if match == 'not':
if results[-1] == 'and':
pass
elif results[-1] == 'or':
pass
else:
results.append('and')
results.append(match)
else:
# seq start with oper, fail
if match not in ['(', ')']:
return False
else:
# The match is not explicitly defined, evaluate it as a glob
results.append(str(self.glob_match(match)))
results = ' '.join(results)
try:
return eval(results) # pylint: disable=W0123
except Exception:
log.error('Invalid compound target: {0} for results: {1}'.format(tgt, results))
return False
return False
def nodegroup_match(self, tgt, nodegroups):
'''
This is a compatibility matcher and is NOT called when using
nodegroups for remote execution, but is called when the nodegroups
matcher is used in states
'''
if tgt in nodegroups:
return self.compound_match(
salt.utils.minions.nodegroup_comp(tgt, nodegroups)
)
return False
class ProxyMinion(Minion):
'''
This class instantiates a 'proxy' minion--a minion that does not manipulate
the host it runs on, but instead manipulates a device that cannot run a minion.
'''
def __init__(self, opts, timeout=60, safe=True): # pylint: disable=W0231
'''
Pass in the options dict
'''
self._running = None
# Warn if ZMQ < 3.2
if HAS_ZMQ and (not(hasattr(zmq, 'zmq_version_info')) or
zmq.zmq_version_info() < (3, 2)):
# PyZMQ 2.1.9 does not have zmq_version_info
log.warning('You have a version of ZMQ less than ZMQ 3.2! There '
'are known connection keep-alive issues with ZMQ < '
'3.2 which may result in loss of contact with '
'minions. Please upgrade your ZMQ!')
# Late setup the of the opts grains, so we can log from the grains
# module
# print opts['proxymodule']
fq_proxyname = 'proxy.'+opts['proxy']['proxytype']
self.proxymodule = salt.loader.proxy(opts, fq_proxyname)
opts['proxyobject'] = self.proxymodule[opts['proxy']['proxytype']+'.Proxyconn'](opts['proxy'])
opts['id'] = opts['proxyobject'].id(opts)
opts.update(resolve_dns(opts))
self.opts = opts
self.authenticate(timeout, safe)
self.opts['pillar'] = salt.pillar.get_pillar(
opts,
opts['grains'],
opts['id'],
opts['environment'],
).compile_pillar()
self.serial = salt.payload.Serial(self.opts)
self.mod_opts = self._prep_mod_opts()
self.functions, self.returners = self._load_modules()
self.matcher = Matcher(self.opts, self.functions)
self.proc_dir = get_proc_dir(opts['cachedir'])
self.schedule = salt.utils.schedule.Schedule(
self.opts,
self.functions,
self.returners)
self.grains_cache = self.opts['grains']
# self._running = True
def _prep_mod_opts(self):
'''
Returns a copy of the opts with key bits stripped out
'''
return super(ProxyMinion, self)._prep_mod_opts()
def _load_modules(self):
'''
Return the functions and the returners loaded up from the loader
module
'''
return super(ProxyMinion, self)._load_modules()
|
data_plane.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Implementation of ``DataChannel``s to communicate across the data plane."""
# pytype: skip-file
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import collections
import logging
import queue
import sys
import threading
import time
from builtins import object
from builtins import range
from typing import TYPE_CHECKING
from typing import Callable
from typing import DefaultDict
from typing import Dict
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
import grpc
from future.utils import raise_
from future.utils import with_metaclass
from apache_beam.coders import coder_impl
from apache_beam.portability.api import beam_fn_api_pb2
from apache_beam.portability.api import beam_fn_api_pb2_grpc
from apache_beam.runners.worker.channel_factory import GRPCChannelFactory
from apache_beam.runners.worker.worker_id_interceptor import WorkerIdInterceptor
if TYPE_CHECKING:
# TODO: remove from TYPE_CHECKING scope when we drop support for python < 3.6
from typing import Collection
# This module is experimental. No backwards-compatibility guarantees.
_LOGGER = logging.getLogger(__name__)
_DEFAULT_SIZE_FLUSH_THRESHOLD = 10 << 20 # 10MB
_DEFAULT_TIME_FLUSH_THRESHOLD_MS = 0 # disable time-based flush by default
if TYPE_CHECKING:
import apache_beam.coders.slow_stream
OutputStream = apache_beam.coders.slow_stream.OutputStream
else:
OutputStream = type(coder_impl.create_OutputStream())
class ClosableOutputStream(OutputStream):
"""A Outputstream for use with CoderImpls that has a close() method."""
def __init__(self, close_callback=None):
super(ClosableOutputStream, self).__init__()
self._close_callback = close_callback
def close(self):
if self._close_callback:
self._close_callback(self.get())
@staticmethod
def create(close_callback, flush_callback, data_buffer_time_limit_ms):
if data_buffer_time_limit_ms > 0:
return TimeBasedBufferingClosableOutputStream(
close_callback,
flush_callback=flush_callback,
time_flush_threshold_ms=data_buffer_time_limit_ms)
else:
return SizeBasedBufferingClosableOutputStream(
close_callback, flush_callback=flush_callback)
class SizeBasedBufferingClosableOutputStream(ClosableOutputStream):
"""A size-based buffering OutputStream."""
def __init__(self,
close_callback=None, # type: Optional[Callable[[bytes], None]]
flush_callback=None, # type: Optional[Callable[[bytes], None]]
size_flush_threshold=_DEFAULT_SIZE_FLUSH_THRESHOLD):
super(SizeBasedBufferingClosableOutputStream, self).__init__(close_callback)
self._flush_callback = flush_callback
self._size_flush_threshold = size_flush_threshold
# This must be called explicitly to avoid flushing partial elements.
def maybe_flush(self):
if self.size() > self._size_flush_threshold:
self.flush()
def flush(self):
if self._flush_callback:
self._flush_callback(self.get())
self._clear()
class TimeBasedBufferingClosableOutputStream(
SizeBasedBufferingClosableOutputStream):
"""A buffering OutputStream with both time-based and size-based."""
def __init__(
self,
close_callback=None,
flush_callback=None,
size_flush_threshold=_DEFAULT_SIZE_FLUSH_THRESHOLD,
time_flush_threshold_ms=_DEFAULT_TIME_FLUSH_THRESHOLD_MS):
super(TimeBasedBufferingClosableOutputStream,
self).__init__(close_callback, flush_callback, size_flush_threshold)
assert time_flush_threshold_ms > 0
self._time_flush_threshold_ms = time_flush_threshold_ms
self._flush_lock = threading.Lock()
self._schedule_lock = threading.Lock()
self._closed = False
self._schedule_periodic_flush()
def flush(self):
with self._flush_lock:
super(TimeBasedBufferingClosableOutputStream, self).flush()
def close(self):
with self._schedule_lock:
self._closed = True
if self._periodic_flusher:
self._periodic_flusher.cancel()
self._periodic_flusher = None
super(TimeBasedBufferingClosableOutputStream, self).close()
def _schedule_periodic_flush(self):
def _flush():
with self._schedule_lock:
if not self._closed:
self.flush()
self._periodic_flusher = PeriodicThread(
self._time_flush_threshold_ms / 1000.0, _flush)
self._periodic_flusher.daemon = True
self._periodic_flusher.start()
class PeriodicThread(threading.Thread):
"""Call a function periodically with the specified number of seconds"""
def __init__(self, interval, function, args=None, kwargs=None):
threading.Thread.__init__(self)
self._interval = interval
self._function = function
self._args = args if args is not None else []
self._kwargs = kwargs if kwargs is not None else {}
self._finished = threading.Event()
def run(self):
next_call = time.time() + self._interval
while not self._finished.wait(next_call - time.time()):
next_call = next_call + self._interval
self._function(*self._args, **self._kwargs)
def cancel(self):
"""Stop the thread if it hasn't finished yet."""
self._finished.set()
class DataChannel(with_metaclass(abc.ABCMeta, object)): # type: ignore[misc]
"""Represents a channel for reading and writing data over the data plane.
Read from this channel with the input_elements method::
for elements_data in data_channel.input_elements(
instruction_id, transform_ids):
[process elements_data]
Write to this channel using the output_stream method::
out1 = data_channel.output_stream(instruction_id, transform_id)
out1.write(...)
out1.close()
When all data for all instructions is written, close the channel::
data_channel.close()
"""
@abc.abstractmethod
def input_elements(self,
instruction_id, # type: str
expected_transforms, # type: Collection[str]
abort_callback=None # type: Optional[Callable[[], bool]]
):
# type: (...) -> Iterator[beam_fn_api_pb2.Elements.Data]
"""Returns an iterable of all Element.Data bundles for instruction_id.
This iterable terminates only once the full set of data has been recieved
for each of the expected transforms. It may block waiting for more data.
Args:
instruction_id: which instruction the results must belong to
expected_transforms: which transforms to wait on for completion
abort_callback: a callback to invoke if blocking returning whether
to abort before consuming all the data
"""
raise NotImplementedError(type(self))
@abc.abstractmethod
def output_stream(
self,
instruction_id, # type: str
transform_id # type: str
):
# type: (...) -> ClosableOutputStream
"""Returns an output stream writing elements to transform_id.
Args:
instruction_id: which instruction this stream belongs to
transform_id: the transform_id of the returned stream
"""
raise NotImplementedError(type(self))
@abc.abstractmethod
def close(self):
# type: () -> None
"""Closes this channel, indicating that all data has been written.
Data can continue to be read.
If this channel is shared by many instructions, should only be called on
worker shutdown.
"""
raise NotImplementedError(type(self))
class InMemoryDataChannel(DataChannel):
"""An in-memory implementation of a DataChannel.
This channel is two-sided. What is written to one side is read by the other.
The inverse() method returns the other side of a instance.
"""
def __init__(self, inverse=None, data_buffer_time_limit_ms=0):
# type: (Optional[InMemoryDataChannel], Optional[int]) -> None
self._inputs = [] # type: List[beam_fn_api_pb2.Elements.Data]
self._data_buffer_time_limit_ms = data_buffer_time_limit_ms
self._inverse = inverse or InMemoryDataChannel(
self, data_buffer_time_limit_ms=data_buffer_time_limit_ms)
def inverse(self):
# type: () -> InMemoryDataChannel
return self._inverse
def input_elements(self,
instruction_id, # type: str
unused_expected_transforms=None, # type: Optional[Collection[str]]
abort_callback=None # type: Optional[Callable[[], bool]]
):
# type: (...) -> Iterator[beam_fn_api_pb2.Elements.Data]
other_inputs = []
for data in self._inputs:
if data.instruction_id == instruction_id:
if data.data:
yield data
else:
other_inputs.append(data)
self._inputs = other_inputs
def output_stream(self, instruction_id, transform_id):
# type: (str, str) -> ClosableOutputStream
def add_to_inverse_output(data):
self._inverse._inputs.append( # pylint: disable=protected-access
beam_fn_api_pb2.Elements.Data(
instruction_id=instruction_id,
transform_id=transform_id,
data=data))
return ClosableOutputStream.create(
add_to_inverse_output,
add_to_inverse_output,
self._data_buffer_time_limit_ms)
def close(self):
pass
class _GrpcDataChannel(DataChannel):
"""Base class for implementing a BeamFnData-based DataChannel."""
_WRITES_FINISHED = object()
def __init__(self, data_buffer_time_limit_ms=0):
# type: (Optional[int]) -> None
self._data_buffer_time_limit_ms = data_buffer_time_limit_ms
self._to_send = queue.Queue(
) # type: queue.Queue[beam_fn_api_pb2.Elements.Data]
self._received = collections.defaultdict(
lambda: queue.Queue(maxsize=5)
) # type: DefaultDict[str, queue.Queue[beam_fn_api_pb2.Elements.Data]]
self._receive_lock = threading.Lock()
self._reads_finished = threading.Event()
self._closed = False
self._exc_info = None
def close(self):
self._to_send.put(self._WRITES_FINISHED)
self._closed = True
def wait(self, timeout=None):
self._reads_finished.wait(timeout)
def _receiving_queue(self, instruction_id):
# type: (str) -> queue.Queue[beam_fn_api_pb2.Elements.Data]
with self._receive_lock:
return self._received[instruction_id]
def _clean_receiving_queue(self, instruction_id):
# type: (str) -> None
with self._receive_lock:
self._received.pop(instruction_id)
def input_elements(self,
instruction_id, # type: str
expected_transforms, # type: Collection[str]
abort_callback=None # type: Optional[Callable[[], bool]]
):
# type: (...) -> Iterator[beam_fn_api_pb2.Elements.Data]
"""
Generator to retrieve elements for an instruction_id
input_elements should be called only once for an instruction_id
Args:
instruction_id(str): instruction_id for which data is read
expected_transforms(collection): expected transforms
"""
received = self._receiving_queue(instruction_id)
done_transforms = [] # type: List[str]
abort_callback = abort_callback or (lambda: False)
try:
while len(done_transforms) < len(expected_transforms):
try:
data = received.get(timeout=1)
except queue.Empty:
if self._closed:
raise RuntimeError('Channel closed prematurely.')
if abort_callback():
return
if self._exc_info:
t, v, tb = self._exc_info
raise_(t, v, tb)
else:
if not data.data and data.transform_id in expected_transforms:
done_transforms.append(data.transform_id)
else:
assert data.transform_id not in done_transforms
yield data
finally:
# Instruction_ids are not reusable so Clean queue once we are done with
# an instruction_id
self._clean_receiving_queue(instruction_id)
def output_stream(self, instruction_id, transform_id):
# type: (str, str) -> ClosableOutputStream
def add_to_send_queue(data):
# type: (bytes) -> None
if data:
self._to_send.put(
beam_fn_api_pb2.Elements.Data(
instruction_id=instruction_id,
transform_id=transform_id,
data=data))
def close_callback(data):
# type: (bytes) -> None
add_to_send_queue(data)
# End of stream marker.
self._to_send.put(
beam_fn_api_pb2.Elements.Data(
instruction_id=instruction_id,
transform_id=transform_id,
data=b''))
return ClosableOutputStream.create(
close_callback, add_to_send_queue, self._data_buffer_time_limit_ms)
def _write_outputs(self):
# type: () -> Iterator[beam_fn_api_pb2.Elements]
done = False
while not done:
data = [self._to_send.get()]
try:
# Coalesce up to 100 other items.
for _ in range(100):
data.append(self._to_send.get_nowait())
except queue.Empty:
pass
if data[-1] is self._WRITES_FINISHED:
done = True
data.pop()
if data:
yield beam_fn_api_pb2.Elements(data=data)
def _read_inputs(self, elements_iterator):
# type: (Iterable[beam_fn_api_pb2.Elements]) -> None
try:
for elements in elements_iterator:
for data in elements.data:
self._receiving_queue(data.instruction_id).put(data)
except: # pylint: disable=bare-except
if not self._closed:
_LOGGER.exception('Failed to read inputs in the data plane.')
self._exc_info = sys.exc_info()
raise
finally:
self._closed = True
self._reads_finished.set()
def set_inputs(self, elements_iterator):
# type: (Iterable[beam_fn_api_pb2.Elements]) -> None
reader = threading.Thread(
target=lambda: self._read_inputs(elements_iterator),
name='read_grpc_client_inputs')
reader.daemon = True
reader.start()
class GrpcClientDataChannel(_GrpcDataChannel):
"""A DataChannel wrapping the client side of a BeamFnData connection."""
def __init__(self,
data_stub, # type: beam_fn_api_pb2_grpc.BeamFnDataStub
data_buffer_time_limit_ms=0 # type: Optional[int]
):
# type: (...) -> None
super(GrpcClientDataChannel, self).__init__(data_buffer_time_limit_ms)
self.set_inputs(data_stub.Data(self._write_outputs()))
class BeamFnDataServicer(beam_fn_api_pb2_grpc.BeamFnDataServicer):
"""Implementation of BeamFnDataServicer for any number of clients"""
def __init__(
self,
data_buffer_time_limit_ms=0 # type: Optional[int]
):
self._lock = threading.Lock()
self._connections_by_worker_id = collections.defaultdict(
lambda: _GrpcDataChannel(data_buffer_time_limit_ms)
) # type: DefaultDict[str, _GrpcDataChannel]
def get_conn_by_worker_id(self, worker_id):
# type: (str) -> _GrpcDataChannel
with self._lock:
return self._connections_by_worker_id[worker_id]
def Data(self,
elements_iterator, # type: Iterable[beam_fn_api_pb2.Elements]
context
):
# type: (...) -> Iterator[beam_fn_api_pb2.Elements]
worker_id = dict(context.invocation_metadata())['worker_id']
data_conn = self.get_conn_by_worker_id(worker_id)
data_conn.set_inputs(elements_iterator)
for elements in data_conn._write_outputs():
yield elements
class DataChannelFactory(with_metaclass(abc.ABCMeta,
object)): # type: ignore[misc]
"""An abstract factory for creating ``DataChannel``."""
@abc.abstractmethod
def create_data_channel(self, remote_grpc_port):
# type: (beam_fn_api_pb2.RemoteGrpcPort) -> GrpcClientDataChannel
"""Returns a ``DataChannel`` from the given RemoteGrpcPort."""
raise NotImplementedError(type(self))
@abc.abstractmethod
def close(self):
# type: () -> None
"""Close all channels that this factory owns."""
raise NotImplementedError(type(self))
class GrpcClientDataChannelFactory(DataChannelFactory):
"""A factory for ``GrpcClientDataChannel``.
Caches the created channels by ``data descriptor url``.
"""
def __init__(self,
credentials=None,
worker_id=None, # type: Optional[str]
data_buffer_time_limit_ms=0 # type: Optional[int]
):
# type: (...) -> None
self._data_channel_cache = {} # type: Dict[str, GrpcClientDataChannel]
self._lock = threading.Lock()
self._credentials = None
self._worker_id = worker_id
self._data_buffer_time_limit_ms = data_buffer_time_limit_ms
if credentials is not None:
_LOGGER.info('Using secure channel creds.')
self._credentials = credentials
def create_data_channel(self, remote_grpc_port):
# type: (beam_fn_api_pb2.RemoteGrpcPort) -> GrpcClientDataChannel
url = remote_grpc_port.api_service_descriptor.url
if url not in self._data_channel_cache:
with self._lock:
if url not in self._data_channel_cache:
_LOGGER.info('Creating client data channel for %s', url)
# Options to have no limits (-1) on the size of the messages
# received or sent over the data plane. The actual buffer size
# is controlled in a layer above.
channel_options = [("grpc.max_receive_message_length", -1),
("grpc.max_send_message_length", -1)]
grpc_channel = None
if self._credentials is None:
grpc_channel = GRPCChannelFactory.insecure_channel(
url, options=channel_options)
else:
grpc_channel = GRPCChannelFactory.secure_channel(
url, self._credentials, options=channel_options)
# Add workerId to the grpc channel
grpc_channel = grpc.intercept_channel(
grpc_channel, WorkerIdInterceptor(self._worker_id))
self._data_channel_cache[url] = GrpcClientDataChannel(
beam_fn_api_pb2_grpc.BeamFnDataStub(grpc_channel),
self._data_buffer_time_limit_ms)
return self._data_channel_cache[url]
def close(self):
# type: () -> None
_LOGGER.info('Closing all cached grpc data channels.')
for _, channel in self._data_channel_cache.items():
channel.close()
self._data_channel_cache.clear()
class InMemoryDataChannelFactory(DataChannelFactory):
"""A singleton factory for ``InMemoryDataChannel``."""
def __init__(self, in_memory_data_channel):
# type: (GrpcClientDataChannel) -> None
self._in_memory_data_channel = in_memory_data_channel
def create_data_channel(self, unused_remote_grpc_port):
# type: (beam_fn_api_pb2.RemoteGrpcPort) -> GrpcClientDataChannel
return self._in_memory_data_channel
def close(self):
# type: () -> None
pass
|
__init__.py | """
The top level interface used to translate configuration data back to the
correct cloud modules
"""
import copy
import glob
import logging
import multiprocessing
import os
import signal
import time
import traceback
from itertools import groupby
import salt.client
import salt.config
import salt.loader
import salt.syspaths
import salt.utils.args
import salt.utils.cloud
import salt.utils.context
import salt.utils.crypt
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.user
import salt.utils.verify
import salt.utils.yaml
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudException,
SaltCloudNotFound,
SaltCloudSystemExit,
)
from salt.template import compile_template
try:
import Cryptodome.Random
except ImportError:
try:
import Crypto.Random # nosec
except ImportError:
pass # pycrypto < 2.1
log = logging.getLogger(__name__)
def communicator(func):
"""Warning, this is a picklable decorator !"""
def _call(queue, args, kwargs):
"""called with [queue, args, kwargs] as first optional arg"""
kwargs["queue"] = queue
ret = None
try:
ret = func(*args, **kwargs)
queue.put("END")
except KeyboardInterrupt as ex:
trace = traceback.format_exc()
queue.put("KEYBOARDINT")
queue.put("Keyboard interrupt")
queue.put("{}\n{}\n".format(ex, trace))
except Exception as ex: # pylint: disable=broad-except
trace = traceback.format_exc()
queue.put("ERROR")
queue.put("Exception")
queue.put("{}\n{}\n".format(ex, trace))
except SystemExit as ex:
trace = traceback.format_exc()
queue.put("ERROR")
queue.put("System exit")
queue.put("{}\n{}\n".format(ex, trace))
return ret
return _call
def enter_mainloop(
target,
mapped_args=None,
args=None,
kwargs=None,
pool=None,
pool_size=None,
callback=None,
queue=None,
):
"""
Manage a multiprocessing pool
- If the queue does not output anything, the pool runs indefinitely
- If the queue returns KEYBOARDINT or ERROR, this will kill the pool
totally calling terminate & join and ands with a SaltCloudSystemExit
exception notifying callers from the abnormal termination
- If the queue returns END or callback is defined and returns True,
it just join the process and return the data.
target
the function you want to execute in multiprocessing
pool
pool object can be None if you want a default pool, but you ll
have then to define pool_size instead
pool_size
pool size if you did not provide yourself a pool
callback
a boolean taking a string in argument which returns True to
signal that 'target' is finished and we need to join
the pool
queue
A custom multiprocessing queue in case you want to do
extra stuff and need it later in your program
args
positional arguments to call the function with
if you don't want to use pool.map
mapped_args
a list of one or more arguments combinations to call the function with
e.g. (foo, [[1], [2]]) will call::
foo([1])
foo([2])
kwargs
kwargs to give to the function in case of process
Attention, the function must have the following signature:
target(queue, *args, **kw)
You may use the 'communicator' decorator to generate such a function
(see end of this file)
"""
if not kwargs:
kwargs = {}
if not pool_size:
pool_size = 1
if not pool:
pool = multiprocessing.Pool(pool_size)
if not queue:
manager = multiprocessing.Manager()
queue = manager.Queue()
if mapped_args is not None and not mapped_args:
msg = (
"We are called to asynchronously execute {}"
" but we do no have anything to execute, weird,"
" we bail out".format(target)
)
log.error(msg)
raise SaltCloudSystemExit("Exception caught\n{}".format(msg))
elif mapped_args is not None:
iterable = [[queue, [arg], kwargs] for arg in mapped_args]
ret = pool.map(func=target, iterable=iterable)
else:
ret = pool.apply(target, [queue, args, kwargs])
while True:
test = queue.get()
if test in ["ERROR", "KEYBOARDINT"]:
type_ = queue.get()
trace = queue.get()
msg = "Caught {}, terminating workers\n".format(type_)
msg += "TRACE: {}\n".format(trace)
log.error(msg)
pool.terminate()
pool.join()
raise SaltCloudSystemExit("Exception caught\n{}".format(msg))
elif test in ["END"] or (callback and callback(test)):
pool.close()
pool.join()
break
else:
time.sleep(0.125)
return ret
class CloudClient:
"""
The client class to wrap cloud interactions
"""
def __init__(self, path=None, opts=None, config_dir=None, pillars=None):
if opts:
self.opts = opts
else:
self.opts = salt.config.cloud_config(path)
# Check the cache-dir exists. If not, create it.
v_dirs = [self.opts["cachedir"]]
salt.utils.verify.verify_env(v_dirs, salt.utils.user.get_user())
if pillars:
for name, provider in pillars.pop("providers", {}).items():
driver = provider["driver"]
provider["profiles"] = {}
self.opts["providers"].update({name: {driver: provider}})
for name, profile in pillars.pop("profiles", {}).items():
provider = profile["provider"].split(":")[0]
driver = next(iter(self.opts["providers"][provider].keys()))
profile["provider"] = "{}:{}".format(provider, driver)
profile["profile"] = name
self.opts["profiles"].update({name: profile})
self.opts["providers"][provider][driver]["profiles"].update(
{name: profile}
)
for name, map_dct in pillars.pop("maps", {}).items():
if "maps" not in self.opts:
self.opts["maps"] = {}
self.opts["maps"][name] = map_dct
self.opts.update(pillars)
def _opts_defaults(self, **kwargs):
"""
Set the opts dict to defaults and allow for opts to be overridden in
the kwargs
"""
# Let's start with the default salt cloud configuration
opts = salt.config.DEFAULT_CLOUD_OPTS.copy()
# Update it with the loaded configuration
opts.update(self.opts.copy())
# Reset some of the settings to sane values
opts["parallel"] = False
opts["keep_tmp"] = False
opts["deploy"] = True
opts["update_bootstrap"] = False
opts["show_deploy_args"] = False
opts["script_args"] = ""
# Update it with the passed kwargs
if "kwargs" in kwargs:
opts.update(kwargs["kwargs"])
opts.update(kwargs)
profile = opts.get("profile", None)
# filter other profiles if one is specified
if profile:
tmp_profiles = opts.get("profiles", {}).copy()
for _profile in [a for a in tmp_profiles]:
if not _profile == profile:
tmp_profiles.pop(_profile)
# if profile is specified and we have enough info about providers
# also filter them to speedup methods like
# __filter_non_working_providers
providers = [
a.get("provider", "").split(":")[0]
for a in tmp_profiles.values()
if a.get("provider", "")
]
if providers:
_providers = opts.get("providers", {})
for provider in _providers.copy():
if provider not in providers:
_providers.pop(provider)
return opts
def low(self, fun, low):
"""
Pass the cloud function and low data structure to run
"""
l_fun = getattr(self, fun)
f_call = salt.utils.args.format_call(l_fun, low)
return l_fun(*f_call.get("args", ()), **f_call.get("kwargs", {}))
def list_sizes(self, provider=None):
"""
List all available sizes in configured cloud systems
"""
mapper = salt.cloud.Map(self._opts_defaults())
return salt.utils.data.simple_types_filter(mapper.size_list(provider))
def list_images(self, provider=None):
"""
List all available images in configured cloud systems
"""
mapper = salt.cloud.Map(self._opts_defaults())
return salt.utils.data.simple_types_filter(mapper.image_list(provider))
def list_locations(self, provider=None):
"""
List all available locations in configured cloud systems
"""
mapper = salt.cloud.Map(self._opts_defaults())
return salt.utils.data.simple_types_filter(mapper.location_list(provider))
def query(self, query_type="list_nodes"):
"""
Query basic instance information
"""
mapper = salt.cloud.Map(self._opts_defaults())
mapper.opts["selected_query_option"] = "list_nodes"
return mapper.map_providers_parallel(query_type)
def full_query(self, query_type="list_nodes_full"):
"""
Query all instance information
"""
mapper = salt.cloud.Map(self._opts_defaults())
mapper.opts["selected_query_option"] = "list_nodes_full"
return mapper.map_providers_parallel(query_type)
def select_query(self, query_type="list_nodes_select"):
"""
Query select instance information
"""
mapper = salt.cloud.Map(self._opts_defaults())
mapper.opts["selected_query_option"] = "list_nodes_select"
return mapper.map_providers_parallel(query_type)
def min_query(self, query_type="list_nodes_min"):
"""
Query select instance information
"""
mapper = salt.cloud.Map(self._opts_defaults())
mapper.opts["selected_query_option"] = "list_nodes_min"
return mapper.map_providers_parallel(query_type)
def profile(self, profile, names, vm_overrides=None, **kwargs):
"""
Pass in a profile to create, names is a list of vm names to allocate
vm_overrides is a special dict that will be per node options
overrides
Example:
.. code-block:: python
>>> client= salt.cloud.CloudClient(path='/etc/salt/cloud')
>>> client.profile('do_512_git', names=['minion01',])
{'minion01': {'backups_active': 'False',
'created_at': '2014-09-04T18:10:15Z',
'droplet': {'event_id': 31000502,
'id': 2530006,
'image_id': 5140006,
'name': 'minion01',
'size_id': 66},
'id': '2530006',
'image_id': '5140006',
'ip_address': '107.XXX.XXX.XXX',
'locked': 'True',
'name': 'minion01',
'private_ip_address': None,
'region_id': '4',
'size_id': '66',
'status': 'new'}}
"""
if not vm_overrides:
vm_overrides = {}
kwargs["profile"] = profile
mapper = salt.cloud.Map(self._opts_defaults(**kwargs))
if isinstance(names, str):
names = names.split(",")
return salt.utils.data.simple_types_filter(
mapper.run_profile(profile, names, vm_overrides=vm_overrides)
)
def map_run(self, path=None, **kwargs):
"""
To execute a map
"""
kwarg = {}
if path:
kwarg["map"] = path
kwarg.update(kwargs)
mapper = salt.cloud.Map(self._opts_defaults(**kwarg))
dmap = mapper.map_data()
return salt.utils.data.simple_types_filter(mapper.run_map(dmap))
def destroy(self, names):
"""
Destroy the named VMs
"""
mapper = salt.cloud.Map(self._opts_defaults(destroy=True))
if isinstance(names, str):
names = names.split(",")
return salt.utils.data.simple_types_filter(mapper.destroy(names))
def create(self, provider, names, **kwargs):
"""
Create the named VMs, without using a profile
Example:
.. code-block:: python
client.create(provider='my-ec2-config', names=['myinstance'],
image='ami-1624987f', size='t1.micro', ssh_username='ec2-user',
securitygroup='default', delvol_on_destroy=True)
"""
mapper = salt.cloud.Map(self._opts_defaults())
providers = self.opts["providers"]
if provider in providers:
provider += ":{}".format(next(iter(providers[provider].keys())))
else:
return False
if isinstance(names, str):
names = names.split(",")
ret = {}
for name in names:
vm_ = kwargs.copy()
vm_["name"] = name
vm_["driver"] = provider
# This function doesn't require a profile, but many cloud drivers
# check for profile information (which includes the provider key) to
# help with config file debugging and setting up instances. Setting
# the profile and provider defaults here avoids errors in other
# cloud functions relying on these keys. See SaltStack Issue #41971
# and PR #38166 for more information.
vm_["profile"] = None
vm_["provider"] = provider
ret[name] = salt.utils.data.simple_types_filter(mapper.create(vm_))
return ret
def extra_action(self, names, provider, action, **kwargs):
"""
Perform actions with block storage devices
Example:
.. code-block:: python
client.extra_action(names=['myblock'], action='volume_create',
provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000}
)
client.extra_action(names=['salt-net'], action='network_create',
provider='my-nova', kwargs={'cidr': '192.168.100.0/24'}
)
"""
mapper = salt.cloud.Map(self._opts_defaults())
providers = mapper.map_providers_parallel()
if provider in providers:
provider += ":{}".format(next(iter(providers[provider].keys())))
else:
return False
if isinstance(names, str):
names = names.split(",")
ret = {}
for name in names:
extra_ = kwargs.copy()
extra_["name"] = name
extra_["provider"] = provider
extra_["profile"] = None
extra_["action"] = action
ret[name] = salt.utils.data.simple_types_filter(mapper.extras(extra_))
return ret
def action(
self,
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
kwargs=None,
):
"""
Execute a single action via the cloud plugin backend
Examples:
.. code-block:: python
client.action(fun='show_instance', names=['myinstance'])
client.action(fun='show_image', provider='my-ec2-config',
kwargs={'image': 'ami-10314d79'}
)
"""
if kwargs is None:
kwargs = {}
mapper = salt.cloud.Map(self._opts_defaults(action=fun, names=names, **kwargs))
if instance:
if names:
raise SaltCloudConfigError(
"Please specify either a list of 'names' or a single "
"'instance', but not both."
)
names = [instance]
if names and not provider:
self.opts["action"] = fun
return mapper.do_action(names, kwargs)
if provider and not names:
return mapper.do_function(provider, fun, kwargs)
else:
# This should not be called without either an instance or a
# provider. If both an instance/list of names and a provider
# are given, then we also need to exit. We can only have one
# or the other.
raise SaltCloudConfigError(
"Either an instance (or list of names) or a provider must be "
"specified, but not both."
)
class Cloud:
"""
An object for the creation of new VMs
"""
def __init__(self, opts):
self.opts = opts
self.clouds = salt.loader.clouds(self.opts)
self.__filter_non_working_providers()
self.__cached_provider_queries = {}
def get_configured_providers(self):
"""
Return the configured providers
"""
providers = set()
for alias, drivers in self.opts["providers"].items():
if len(drivers) > 1:
for driver in drivers:
providers.add("{}:{}".format(alias, driver))
continue
providers.add(alias)
return providers
def lookup_providers(self, lookup):
"""
Get a dict describing the configured providers
"""
if lookup is None:
lookup = "all"
if lookup == "all":
providers = set()
for alias, drivers in self.opts["providers"].items():
for driver in drivers:
providers.add((alias, driver))
if not providers:
raise SaltCloudSystemExit("There are no cloud providers configured.")
return providers
if ":" in lookup:
alias, driver = lookup.split(":")
if (
alias not in self.opts["providers"]
or driver not in self.opts["providers"][alias]
):
raise SaltCloudSystemExit(
"No cloud providers matched '{}'. Available: {}".format(
lookup, ", ".join(self.get_configured_providers())
)
)
providers = set()
for alias, drivers in self.opts["providers"].items():
for driver in drivers:
if lookup in (alias, driver):
providers.add((alias, driver))
if not providers:
raise SaltCloudSystemExit(
"No cloud providers matched '{}'. Available selections: {}".format(
lookup, ", ".join(self.get_configured_providers())
)
)
return providers
def lookup_profiles(self, provider, lookup):
"""
Return a dictionary describing the configured profiles
"""
if provider is None:
provider = "all"
if lookup is None:
lookup = "all"
if lookup == "all":
profiles = set()
provider_profiles = set()
for alias, info in self.opts["profiles"].items():
providers = info.get("provider")
if providers:
given_prov_name = providers.split(":")[0]
salt_prov_name = providers.split(":")[1]
if given_prov_name == provider:
provider_profiles.add((alias, given_prov_name))
elif salt_prov_name == provider:
provider_profiles.add((alias, salt_prov_name))
profiles.add((alias, given_prov_name))
if not profiles:
raise SaltCloudSystemExit("There are no cloud profiles configured.")
if provider != "all":
return provider_profiles
return profiles
def map_providers(self, query="list_nodes", cached=False):
"""
Return a mapping of what named VMs are running on what VM providers
based on what providers are defined in the configuration and VMs
"""
if cached is True and query in self.__cached_provider_queries:
return self.__cached_provider_queries[query]
pmap = {}
for alias, drivers in self.opts["providers"].items():
for driver, details in drivers.items():
fun = "{}.{}".format(driver, query)
if fun not in self.clouds:
log.error("Public cloud provider %s is not available", driver)
continue
if alias not in pmap:
pmap[alias] = {}
try:
with salt.utils.context.func_globals_inject(
self.clouds[fun],
__active_provider_name__=":".join([alias, driver]),
):
pmap[alias][driver] = self.clouds[fun]()
except Exception as err: # pylint: disable=broad-except
log.debug(
"Failed to execute '%s()' while querying for running nodes: %s",
fun,
err,
exc_info_on_loglevel=logging.DEBUG,
)
# Failed to communicate with the provider, don't list any
# nodes
pmap[alias][driver] = []
self.__cached_provider_queries[query] = pmap
return pmap
def map_providers_parallel(self, query="list_nodes", cached=False):
"""
Return a mapping of what named VMs are running on what VM providers
based on what providers are defined in the configuration and VMs
Same as map_providers but query in parallel.
"""
if cached is True and query in self.__cached_provider_queries:
return self.__cached_provider_queries[query]
opts = self.opts.copy()
multiprocessing_data = []
# Optimize Providers
opts["providers"] = self._optimize_providers(opts["providers"])
for alias, drivers in opts["providers"].items():
# Make temp query for this driver to avoid overwrite next
this_query = query
for driver, details in drivers.items():
# If driver has function list_nodes_min, just replace it
# with query param to check existing vms on this driver
# for minimum information, Otherwise still use query param.
if (
opts.get("selected_query_option") is None
and "{}.list_nodes_min".format(driver) in self.clouds
):
this_query = "list_nodes_min"
fun = "{}.{}".format(driver, this_query)
if fun not in self.clouds:
log.error("Public cloud provider %s is not available", driver)
continue
multiprocessing_data.append(
{
"fun": fun,
"opts": opts,
"query": this_query,
"alias": alias,
"driver": driver,
}
)
output = {}
if not multiprocessing_data:
return output
data_count = len(multiprocessing_data)
pool = multiprocessing.Pool(
data_count < 10 and data_count or 10, init_pool_worker
)
parallel_pmap = enter_mainloop(
_run_parallel_map_providers_query, multiprocessing_data, pool=pool
)
for alias, driver, details in parallel_pmap:
if not details:
# There's no providers details?! Skip it!
continue
if alias not in output:
output[alias] = {}
output[alias][driver] = details
self.__cached_provider_queries[query] = output
return output
def get_running_by_names(
self, names, query="list_nodes", cached=False, profile=None
):
if isinstance(names, str):
names = [names]
matches = {}
handled_drivers = {}
mapped_providers = self.map_providers_parallel(query, cached=cached)
for alias, drivers in mapped_providers.items():
for driver, vms in drivers.items():
if driver not in handled_drivers:
handled_drivers[driver] = alias
# When a profile is specified, only return an instance
# that matches the provider specified in the profile.
# This solves the issues when many providers return the
# same instance. For example there may be one provider for
# each availability zone in amazon in the same region, but
# the search returns the same instance for each provider
# because amazon returns all instances in a region, not
# availability zone.
if (
profile
and alias
not in self.opts["profiles"][profile]["provider"].split(":")[0]
):
continue
for vm_name, details in vms.items():
# XXX: The logic below can be removed once the aws driver
# is removed
if vm_name not in names:
continue
elif (
driver == "ec2"
and "aws" in handled_drivers
and "aws" in matches[handled_drivers["aws"]]
and vm_name in matches[handled_drivers["aws"]]["aws"]
):
continue
elif (
driver == "aws"
and "ec2" in handled_drivers
and "ec2" in matches[handled_drivers["ec2"]]
and vm_name in matches[handled_drivers["ec2"]]["ec2"]
):
continue
if alias not in matches:
matches[alias] = {}
if driver not in matches[alias]:
matches[alias][driver] = {}
matches[alias][driver][vm_name] = details
return matches
def _optimize_providers(self, providers):
"""
Return an optimized mapping of available providers
"""
new_providers = {}
provider_by_driver = {}
for alias, driver in providers.items():
for name, data in driver.items():
if name not in provider_by_driver:
provider_by_driver[name] = {}
provider_by_driver[name][alias] = data
for driver, providers_data in provider_by_driver.items():
fun = "{}.optimize_providers".format(driver)
if fun not in self.clouds:
log.debug("The '%s' cloud driver is unable to be optimized.", driver)
for name, prov_data in providers_data.items():
if name not in new_providers:
new_providers[name] = {}
new_providers[name][driver] = prov_data
continue
new_data = self.clouds[fun](providers_data)
if new_data:
for name, prov_data in new_data.items():
if name not in new_providers:
new_providers[name] = {}
new_providers[name][driver] = prov_data
return new_providers
def location_list(self, lookup="all"):
"""
Return a mapping of all location data for available providers
"""
data = {}
lookups = self.lookup_providers(lookup)
if not lookups:
return data
for alias, driver in lookups:
fun = "{}.avail_locations".format(driver)
if fun not in self.clouds:
# The capability to gather locations is not supported by this
# cloud module
log.debug(
"The '%s' cloud driver defined under '%s' provider "
"alias is unable to get the locations information",
driver,
alias,
)
continue
if alias not in data:
data[alias] = {}
try:
with salt.utils.context.func_globals_inject(
self.clouds[fun], __active_provider_name__=":".join([alias, driver])
):
data[alias][driver] = self.clouds[fun]()
except Exception as err: # pylint: disable=broad-except
log.error(
"Failed to get the output of '%s()': %s",
fun,
err,
exc_info_on_loglevel=logging.DEBUG,
)
return data
def image_list(self, lookup="all"):
"""
Return a mapping of all image data for available providers
"""
data = {}
lookups = self.lookup_providers(lookup)
if not lookups:
return data
for alias, driver in lookups:
fun = "{}.avail_images".format(driver)
if fun not in self.clouds:
# The capability to gather images is not supported by this
# cloud module
log.debug(
"The '%s' cloud driver defined under '%s' provider "
"alias is unable to get the images information",
driver,
alias,
)
continue
if alias not in data:
data[alias] = {}
try:
with salt.utils.context.func_globals_inject(
self.clouds[fun], __active_provider_name__=":".join([alias, driver])
):
data[alias][driver] = self.clouds[fun]()
except Exception as err: # pylint: disable=broad-except
log.error(
"Failed to get the output of '%s()': %s",
fun,
err,
exc_info_on_loglevel=logging.DEBUG,
)
return data
def size_list(self, lookup="all"):
"""
Return a mapping of all image data for available providers
"""
data = {}
lookups = self.lookup_providers(lookup)
if not lookups:
return data
for alias, driver in lookups:
fun = "{}.avail_sizes".format(driver)
if fun not in self.clouds:
# The capability to gather sizes is not supported by this
# cloud module
log.debug(
"The '%s' cloud driver defined under '%s' provider "
"alias is unable to get the sizes information",
driver,
alias,
)
continue
if alias not in data:
data[alias] = {}
try:
with salt.utils.context.func_globals_inject(
self.clouds[fun], __active_provider_name__=":".join([alias, driver])
):
data[alias][driver] = self.clouds[fun]()
except Exception as err: # pylint: disable=broad-except
log.error(
"Failed to get the output of '%s()': %s",
fun,
err,
exc_info_on_loglevel=logging.DEBUG,
)
return data
def provider_list(self, lookup="all"):
"""
Return a mapping of all image data for available providers
"""
data = {}
lookups = self.lookup_providers(lookup)
if not lookups:
return data
for alias, driver in lookups:
if alias not in data:
data[alias] = {}
if driver not in data[alias]:
data[alias][driver] = {}
return data
def profile_list(self, provider, lookup="all"):
"""
Return a mapping of all configured profiles
"""
data = {}
lookups = self.lookup_profiles(provider, lookup)
if not lookups:
return data
for alias, driver in lookups:
if alias not in data:
data[alias] = {}
if driver not in data[alias]:
data[alias][driver] = {}
return data
def create_all(self):
"""
Create/Verify the VMs in the VM data
"""
ret = []
for vm_name, vm_details in self.opts["profiles"].items():
ret.append({vm_name: self.create(vm_details)})
return ret
def destroy(self, names, cached=False):
"""
Destroy the named VMs
"""
processed = {}
names = set(names)
matching = self.get_running_by_names(names, cached=cached)
vms_to_destroy = set()
parallel_data = []
for alias, drivers in matching.items():
for driver, vms in drivers.items():
for name in vms:
if name in names:
vms_to_destroy.add((alias, driver, name))
if self.opts["parallel"]:
parallel_data.append(
{
"opts": self.opts,
"name": name,
"alias": alias,
"driver": driver,
}
)
# destroying in parallel
if self.opts["parallel"] and parallel_data:
# set the pool size based on configuration or default to
# the number of machines we're destroying
if "pool_size" in self.opts:
pool_size = self.opts["pool_size"]
else:
pool_size = len(parallel_data)
log.info("Destroying in parallel mode; Cloud pool size: %s", pool_size)
# kick off the parallel destroy
output_multip = enter_mainloop(
_destroy_multiprocessing, parallel_data, pool_size=pool_size
)
# massage the multiprocessing output a bit
ret_multip = {}
for obj in output_multip:
ret_multip.update(obj)
# build up a data structure similar to what the non-parallel
# destroy uses
for obj in parallel_data:
alias = obj["alias"]
driver = obj["driver"]
name = obj["name"]
if alias not in processed:
processed[alias] = {}
if driver not in processed[alias]:
processed[alias][driver] = {}
processed[alias][driver][name] = ret_multip[name]
if name in names:
names.remove(name)
# not destroying in parallel
else:
log.info("Destroying in non-parallel mode.")
for alias, driver, name in vms_to_destroy:
fun = "{}.destroy".format(driver)
with salt.utils.context.func_globals_inject(
self.clouds[fun], __active_provider_name__=":".join([alias, driver])
):
ret = self.clouds[fun](name)
if alias not in processed:
processed[alias] = {}
if driver not in processed[alias]:
processed[alias][driver] = {}
processed[alias][driver][name] = ret
if name in names:
names.remove(name)
# now the processed data structure contains the output from either
# the parallel or non-parallel destroy and we should finish up
# with removing minion keys if necessary
for alias, driver, name in vms_to_destroy:
ret = processed[alias][driver][name]
if not ret:
continue
vm_ = {
"name": name,
"profile": None,
"provider": ":".join([alias, driver]),
"driver": driver,
}
minion_dict = salt.config.get_cloud_config_value(
"minion", vm_, self.opts, default={}
)
key_file = os.path.join(
self.opts["pki_dir"], "minions", minion_dict.get("id", name)
)
globbed_key_file = glob.glob("{}.*".format(key_file))
if not os.path.isfile(key_file) and not globbed_key_file:
# There's no such key file!? It might have been renamed
if isinstance(ret, dict) and "newname" in ret:
salt.utils.cloud.remove_key(self.opts["pki_dir"], ret["newname"])
continue
if os.path.isfile(key_file) and not globbed_key_file:
# Single key entry. Remove it!
salt.utils.cloud.remove_key(
self.opts["pki_dir"], os.path.basename(key_file)
)
continue
# Since we have globbed matches, there are probably some keys for which their minion
# configuration has append_domain set.
if (
not os.path.isfile(key_file)
and globbed_key_file
and len(globbed_key_file) == 1
):
# Single entry, let's remove it!
salt.utils.cloud.remove_key(
self.opts["pki_dir"], os.path.basename(globbed_key_file[0])
)
continue
# Since we can't get the profile or map entry used to create
# the VM, we can't also get the append_domain setting.
# And if we reached this point, we have several minion keys
# who's name starts with the machine name we're deleting.
# We need to ask one by one!?
print(
"There are several minion keys who's name starts "
"with '{}'. We need to ask you which one should be "
"deleted:".format(name)
)
while True:
for idx, filename in enumerate(globbed_key_file):
print(" {}: {}".format(idx, os.path.basename(filename)))
selection = input("Which minion key should be deleted(number)? ")
try:
selection = int(selection)
except ValueError:
print("'{}' is not a valid selection.".format(selection))
try:
filename = os.path.basename(globbed_key_file.pop(selection))
except Exception: # pylint: disable=broad-except
continue
delete = input("Delete '{}'? [Y/n]? ".format(filename))
if delete == "" or delete.lower().startswith("y"):
salt.utils.cloud.remove_key(self.opts["pki_dir"], filename)
print("Deleted '{}'".format(filename))
break
print("Did not delete '{}'".format(filename))
break
if names and not processed:
# These machines were asked to be destroyed but could not be found
raise SaltCloudSystemExit(
"The following VM's were not found: {}".format(", ".join(names))
)
elif names and processed:
processed["Not Found"] = names
elif not processed:
raise SaltCloudSystemExit("No machines were destroyed!")
return processed
def reboot(self, names):
"""
Reboot the named VMs
"""
ret = []
pmap = self.map_providers_parallel()
acts = {}
for prov, nodes in pmap.items():
acts[prov] = []
for node in nodes:
if node in names:
acts[prov].append(node)
for prov, names_ in acts.items():
fun = "{}.reboot".format(prov)
for name in names_:
ret.append({name: self.clouds[fun](name)})
return ret
def create(self, vm_, local_master=True, sync_sleep=3):
"""
Create a single VM
"""
output = {}
minion_dict = salt.config.get_cloud_config_value(
"minion", vm_, self.opts, default={}
)
alias, driver = vm_["provider"].split(":")
fun = "{}.create".format(driver)
if fun not in self.clouds:
log.error(
"Creating '%s' using '%s' as the provider "
"cannot complete since '%s' is not available",
vm_["name"],
vm_["provider"],
driver,
)
return
deploy = salt.config.get_cloud_config_value("deploy", vm_, self.opts)
make_master = salt.config.get_cloud_config_value("make_master", vm_, self.opts)
if deploy:
if not make_master and "master" not in minion_dict:
log.warning(
"There's no master defined on the '%s' VM settings.", vm_["name"]
)
if "pub_key" not in vm_ and "priv_key" not in vm_:
log.debug("Generating minion keys for '%s'", vm_["name"])
priv, pub = salt.utils.cloud.gen_keys(
salt.config.get_cloud_config_value("keysize", vm_, self.opts)
)
vm_["pub_key"] = pub
vm_["priv_key"] = priv
else:
# Note(pabelanger): We still reference pub_key and priv_key when
# deploy is disabled.
vm_["pub_key"] = None
vm_["priv_key"] = None
key_id = minion_dict.get("id", vm_["name"])
domain = vm_.get("domain")
if vm_.get("use_fqdn") and domain:
minion_dict["append_domain"] = domain
if "append_domain" in minion_dict:
key_id = ".".join([key_id, minion_dict["append_domain"]])
if make_master is True and "master_pub" not in vm_ and "master_pem" not in vm_:
log.debug("Generating the master keys for '%s'", vm_["name"])
master_priv, master_pub = salt.utils.cloud.gen_keys(
salt.config.get_cloud_config_value("keysize", vm_, self.opts)
)
vm_["master_pub"] = master_pub
vm_["master_pem"] = master_priv
if local_master is True and deploy is True:
# Accept the key on the local master
salt.utils.cloud.accept_key(self.opts["pki_dir"], vm_["pub_key"], key_id)
vm_["os"] = salt.config.get_cloud_config_value("script", vm_, self.opts)
try:
vm_["inline_script"] = salt.config.get_cloud_config_value(
"inline_script", vm_, self.opts
)
except KeyError:
pass
try:
alias, driver = vm_["provider"].split(":")
func = "{}.create".format(driver)
with salt.utils.context.func_globals_inject(
self.clouds[fun], __active_provider_name__=":".join([alias, driver])
):
output = self.clouds[func](vm_)
if output is not False and "sync_after_install" in self.opts:
if self.opts["sync_after_install"] and self.opts[
"sync_after_install"
] not in (
"all",
"beacons",
"clouds",
"engines",
"executors",
"grains",
"log",
"matchers",
"modules",
"output",
"pillar",
"proxymodules",
"renderers",
"returners",
"sdb",
"serializers",
"states",
"thorium",
"utils",
):
log.warning(
"Bad option for sync_after_install. Defaulting to 'all'"
)
self.opts["sync_after_install"] = "all"
# A small pause helps the sync work more reliably
time.sleep(sync_sleep)
expiration_time = time.time() + 60
while time.time() < expiration_time:
# We'll try every <timeout> seconds, up to a minute
mopts_ = copy.deepcopy(salt.config.DEFAULT_MASTER_OPTS)
conf_path = "/".join(self.opts["conf_file"].split("/")[:-1])
mopts_.update(
salt.config.master_config(os.path.join(conf_path, "master"))
)
with salt.client.get_local_client(mopts=mopts_) as client:
ret = client.cmd(
vm_["name"],
"saltutil.sync_{}".format(self.opts["sync_after_install"]),
timeout=self.opts["timeout"],
)
if ret:
log.info(
"Synchronized the following dynamic modules: %s", ret
)
break
except KeyError as exc:
log.exception(
"Failed to create VM %s. Configuration value %s needs to be set",
vm_["name"],
exc,
)
# If it's a map then we need to respect the 'requires'
# so we do it later
try:
opt_map = self.opts["map"]
except KeyError:
opt_map = False
if self.opts["parallel"] and self.opts["start_action"] and not opt_map:
log.info("Running %s on %s", self.opts["start_action"], vm_["name"])
with salt.client.get_local_client(mopts=self.opts) as client:
action_out = client.cmd(
vm_["name"],
self.opts["start_action"],
timeout=self.opts["timeout"] * 60,
)
output["ret"] = action_out
return output
@staticmethod
def vm_config(name, main, provider, profile, overrides):
"""
Create vm config.
:param str name: The name of the vm
:param dict main: The main cloud config
:param dict provider: The provider config
:param dict profile: The profile config
:param dict overrides: The vm's config overrides
"""
vm = main.copy()
vm = salt.utils.dictupdate.update(vm, provider)
vm = salt.utils.dictupdate.update(vm, profile)
vm.update(overrides)
vm["name"] = name
return vm
def extras(self, extra_):
"""
Extra actions
"""
output = {}
alias, driver = extra_["provider"].split(":")
fun = "{}.{}".format(driver, extra_["action"])
if fun not in self.clouds:
log.error(
"Creating '%s' using '%s' as the provider "
"cannot complete since '%s' is not available",
extra_["name"],
extra_["provider"],
driver,
)
return
try:
with salt.utils.context.func_globals_inject(
self.clouds[fun], __active_provider_name__=extra_["provider"]
):
output = self.clouds[fun](**extra_)
except KeyError as exc:
log.exception(
"Failed to perform %s.%s on %s. Configuration value %s needs to be set",
extra_["provider"],
extra_["action"],
extra_["name"],
exc,
)
return output
def run_profile(self, profile, names, vm_overrides=None):
"""
Parse over the options passed on the command line and determine how to
handle them
"""
if profile not in self.opts["profiles"]:
msg = "Profile {} is not defined".format(profile)
log.error(msg)
return {"Error": msg}
ret = {}
if not vm_overrides:
vm_overrides = {}
try:
with salt.utils.files.fopen(self.opts["conf_file"], "r") as mcc:
main_cloud_config = salt.utils.yaml.safe_load(mcc)
if not main_cloud_config:
main_cloud_config = {}
except KeyError:
main_cloud_config = {}
except OSError:
main_cloud_config = {}
if main_cloud_config is None:
main_cloud_config = {}
mapped_providers = self.map_providers_parallel()
profile_details = self.opts["profiles"][profile]
vms = {}
for prov, val in mapped_providers.items():
prov_name = next(iter(val))
for node in mapped_providers[prov][prov_name]:
vms[node] = mapped_providers[prov][prov_name][node]
vms[node]["provider"] = prov
vms[node]["driver"] = prov_name
alias, driver = profile_details["provider"].split(":")
provider_details = self.opts["providers"][alias][driver].copy()
del provider_details["profiles"]
for name in names:
if name in vms:
prov = vms[name]["provider"]
driv = vms[name]["driver"]
msg = "{} already exists under {}:{}".format(name, prov, driv)
log.error(msg)
ret[name] = {"Error": msg}
continue
vm_ = self.vm_config(
name,
main_cloud_config,
provider_details,
profile_details,
vm_overrides,
)
if self.opts["parallel"]:
process = multiprocessing.Process(target=self.create, args=(vm_,))
process.start()
ret[name] = {
"Provisioning": "VM being provisioned in parallel. PID: {}".format(
process.pid
)
}
continue
try:
# No need to inject __active_provider_name__ into the context
# here because self.create takes care of that
ret[name] = self.create(vm_)
if not ret[name]:
ret[name] = {"Error": "Failed to deploy VM"}
if len(names) == 1:
raise SaltCloudSystemExit("Failed to deploy VM")
continue
if self.opts.get("show_deploy_args", False) is False:
ret[name].pop("deploy_kwargs", None)
except (SaltCloudSystemExit, SaltCloudConfigError) as exc:
if len(names) == 1:
raise
ret[name] = {"Error": str(exc)}
return ret
def do_action(self, names, kwargs):
"""
Perform an action on a VM which may be specific to this cloud provider
"""
ret = {}
invalid_functions = {}
names = set(names)
for alias, drivers in self.map_providers_parallel().items():
if not names:
break
for driver, vms in drivers.items():
if not names:
break
valid_function = True
fun = "{}.{}".format(driver, self.opts["action"])
if fun not in self.clouds:
log.info("'%s()' is not available. Not actioning...", fun)
valid_function = False
for vm_name, vm_details in vms.items():
if not names:
break
if vm_name not in names:
if not isinstance(vm_details, dict):
vm_details = {}
if "id" in vm_details and vm_details["id"] in names:
vm_name = vm_details["id"]
else:
log.debug(
"vm:%s in provider:%s is not in name list:'%s'",
vm_name,
driver,
names,
)
continue
# Build the dictionary of invalid functions with their associated VMs.
if valid_function is False:
if invalid_functions.get(fun) is None:
invalid_functions.update({fun: []})
invalid_functions[fun].append(vm_name)
continue
with salt.utils.context.func_globals_inject(
self.clouds[fun],
__active_provider_name__=":".join([alias, driver]),
):
if alias not in ret:
ret[alias] = {}
if driver not in ret[alias]:
ret[alias][driver] = {}
# Clean kwargs of "__pub_*" data before running the cloud action call.
# Prevents calling positional "kwarg" arg before "call" when no kwarg
# argument is present in the cloud driver function's arg spec.
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
ret[alias][driver][vm_name] = self.clouds[fun](
vm_name, kwargs, call="action"
)
else:
ret[alias][driver][vm_name] = self.clouds[fun](
vm_name, call="action"
)
names.remove(vm_name)
# Set the return information for the VMs listed in the invalid_functions dict.
missing_vms = set()
if invalid_functions:
ret["Invalid Actions"] = invalid_functions
invalid_func_vms = set()
for key, val in invalid_functions.items():
invalid_func_vms = invalid_func_vms.union(set(val))
# Find the VMs that are in names, but not in set of invalid functions.
missing_vms = names.difference(invalid_func_vms)
if missing_vms:
ret["Not Found"] = list(missing_vms)
ret["Not Actioned/Not Running"] = list(names)
if not names:
return ret
# Don't return missing VM information for invalid functions until after we've had a
# Chance to return successful actions. If a function is valid for one driver, but
# Not another, we want to make sure the successful action is returned properly.
if missing_vms:
return ret
# If we reach this point, the Not Actioned and Not Found lists will be the same,
# But we want to list both for clarity/consistency with the invalid functions lists.
ret["Not Actioned/Not Running"] = list(names)
ret["Not Found"] = list(names)
return ret
def do_function(self, prov, func, kwargs):
"""
Perform a function against a cloud provider
"""
matches = self.lookup_providers(prov)
if len(matches) > 1:
raise SaltCloudSystemExit(
"More than one results matched '{}'. Please specify one of: {}".format(
prov,
", ".join(
["{}:{}".format(alias, driver) for (alias, driver) in matches]
),
)
)
alias, driver = matches.pop()
fun = "{}.{}".format(driver, func)
if fun not in self.clouds:
raise SaltCloudSystemExit(
"The '{}' cloud provider alias, for the '{}' driver, does "
"not define the function '{}'".format(alias, driver, func)
)
log.debug("Trying to execute '%s' with the following kwargs: %s", fun, kwargs)
with salt.utils.context.func_globals_inject(
self.clouds[fun], __active_provider_name__=":".join([alias, driver])
):
if kwargs:
return {
alias: {driver: self.clouds[fun](call="function", kwargs=kwargs)}
}
return {alias: {driver: self.clouds[fun](call="function")}}
def __filter_non_working_providers(self):
"""
Remove any mis-configured cloud providers from the available listing
"""
for alias, drivers in self.opts["providers"].copy().items():
for driver in drivers.copy():
fun = "{}.get_configured_provider".format(driver)
if fun not in self.clouds:
# Mis-configured provider that got removed?
log.warning(
"The cloud driver, '%s', configured under the "
"'%s' cloud provider alias, could not be loaded. "
"Please check your provider configuration files and "
"ensure all required dependencies are installed "
"for the '%s' driver.\n"
"In rare cases, this could indicate the '%s()' "
"function could not be found.\nRemoving '%s' from "
"the available providers list",
driver,
alias,
driver,
fun,
driver,
)
self.opts["providers"][alias].pop(driver)
if alias not in self.opts["providers"]:
continue
if not self.opts["providers"][alias]:
self.opts["providers"].pop(alias)
continue
with salt.utils.context.func_globals_inject(
self.clouds[fun], __active_provider_name__=":".join([alias, driver])
):
if self.clouds[fun]() is False:
log.warning(
"The cloud driver, '%s', configured under the "
"'%s' cloud provider alias is not properly "
"configured. Removing it from the available "
"providers list.",
driver,
alias,
)
self.opts["providers"][alias].pop(driver)
if alias not in self.opts["providers"]:
continue
if not self.opts["providers"][alias]:
self.opts["providers"].pop(alias)
class Map(Cloud):
"""
Create a VM stateful map execution object
"""
def __init__(self, opts):
Cloud.__init__(self, opts)
self.rendered_map = self.read()
def interpolated_map(self, query="list_nodes", cached=False):
rendered_map = self.read().copy()
interpolated_map = {}
for profile, mapped_vms in rendered_map.items():
names = set(mapped_vms)
if profile not in self.opts["profiles"]:
if "Errors" not in interpolated_map:
interpolated_map["Errors"] = {}
msg = (
"No provider for the mapped '{}' profile was found. "
"Skipped VMS: {}".format(profile, ", ".join(names))
)
log.info(msg)
interpolated_map["Errors"][profile] = msg
continue
matching = self.get_running_by_names(names, query, cached)
for alias, drivers in matching.items():
for driver, vms in drivers.items():
for vm_name, vm_details in vms.items():
if alias not in interpolated_map:
interpolated_map[alias] = {}
if driver not in interpolated_map[alias]:
interpolated_map[alias][driver] = {}
interpolated_map[alias][driver][vm_name] = vm_details
try:
names.remove(vm_name)
except KeyError:
# If it's not there, then our job is already done
pass
if not names:
continue
profile_details = self.opts["profiles"][profile]
alias, driver = profile_details["provider"].split(":")
for vm_name in names:
if alias not in interpolated_map:
interpolated_map[alias] = {}
if driver not in interpolated_map[alias]:
interpolated_map[alias][driver] = {}
interpolated_map[alias][driver][vm_name] = "Absent"
return interpolated_map
def delete_map(self, query=None):
query_map = self.interpolated_map(query=query)
for alias, drivers in query_map.copy().items():
if alias == "Errors":
continue
for driver, vms in drivers.copy().items():
for vm_name, vm_details in vms.copy().items():
if vm_details == "Absent":
query_map[alias][driver].pop(vm_name)
if not query_map[alias][driver]:
query_map[alias].pop(driver)
if not query_map[alias]:
query_map.pop(alias)
return query_map
def get_vmnames_by_action(self, action):
query_map = self.interpolated_map("list_nodes")
matching_states = {
"start": ["stopped"],
"stop": ["running", "active"],
"reboot": ["running", "active"],
}
vm_names = []
for alias, drivers in query_map.items():
for driver, vms in drivers.items():
for vm_name, vm_details in vms.items():
# Only certain actions are support in to use in this case. Those actions are the
# "Global" salt-cloud actions defined in the "matching_states" dictionary above.
# If a more specific action is passed in, we shouldn't stack-trace - exit gracefully.
try:
state_action = matching_states[action]
except KeyError:
log.error(
"The use of '%s' as an action is not supported "
"in this context. Only 'start', 'stop', and "
"'reboot' are supported options.",
action,
)
raise SaltCloudException()
if (
vm_details != "Absent"
and vm_details["state"].lower() in state_action
):
vm_names.append(vm_name)
return vm_names
def read(self):
"""
Read in the specified map and return the map structure
"""
map_ = None
if self.opts.get("map", None) is None:
if self.opts.get("map_data", None) is None:
if self.opts.get("map_pillar", None) is None:
pass
elif self.opts.get("map_pillar") not in self.opts.get("maps"):
log.error(
"The specified map not found in pillar at 'cloud:maps:%s'",
self.opts["map_pillar"],
)
raise SaltCloudNotFound()
else:
# 'map_pillar' is provided, try to use it
map_ = self.opts["maps"][self.opts.get("map_pillar")]
else:
# 'map_data' is provided, try to use it
map_ = self.opts["map_data"]
else:
# 'map' is provided, try to use it
local_minion_opts = copy.deepcopy(self.opts)
local_minion_opts["file_client"] = "local"
self.minion = salt.minion.MasterMinion(local_minion_opts)
if not os.path.isfile(self.opts["map"]):
if not (self.opts["map"]).startswith("salt://"):
log.error(
"The specified map file does not exist: '%s'", self.opts["map"]
)
raise SaltCloudNotFound()
if (self.opts["map"]).startswith("salt://"):
cached_map = self.minion.functions["cp.cache_file"](self.opts["map"])
else:
cached_map = self.opts["map"]
try:
renderer = self.opts.get("renderer", "jinja|yaml")
rend = salt.loader.render(self.opts, {})
blacklist = self.opts.get("renderer_blacklist")
whitelist = self.opts.get("renderer_whitelist")
map_ = compile_template(
cached_map, rend, renderer, blacklist, whitelist
)
except Exception as exc: # pylint: disable=broad-except
log.error(
"Rendering map %s failed, render error:\n%s",
self.opts["map"],
exc,
exc_info_on_loglevel=logging.DEBUG,
)
return {}
if "include" in map_:
map_ = salt.config.include_config(map_, self.opts["map"], verbose=False)
if not map_:
return {}
# Create expected data format if needed
for profile, mapped in map_.copy().items():
if isinstance(mapped, (list, tuple)):
entries = {}
for mapping in mapped:
if isinstance(mapping, str):
# Foo:
# - bar1
# - bar2
mapping = {mapping: None}
for name, overrides in mapping.items():
if overrides is None or isinstance(overrides, bool):
# Foo:
# - bar1:
# - bar2:
overrides = {}
try:
overrides.setdefault("name", name)
except AttributeError:
log.error(
"Cannot use 'name' as a minion id in a cloud map as it"
" is a reserved word. Please change 'name' to a"
" different minion id reference."
)
return {}
entries[name] = overrides
map_[profile] = entries
continue
if isinstance(mapped, dict):
# Convert the dictionary mapping to a list of dictionaries
# Foo:
# bar1:
# grains:
# foo: bar
# bar2:
# grains:
# foo: bar
entries = {}
for name, overrides in mapped.items():
overrides.setdefault("name", name)
entries[name] = overrides
map_[profile] = entries
continue
if isinstance(mapped, str):
# If it's a single string entry, let's make iterable because of
# the next step
mapped = [mapped]
map_[profile] = {}
for name in mapped:
map_[profile][name] = {"name": name}
return map_
def _has_loop(self, dmap, seen=None, val=None):
if seen is None:
for values in dmap["create"].values():
seen = []
try:
machines = values["requires"]
except KeyError:
machines = []
for machine in machines:
if self._has_loop(dmap, seen=list(seen), val=machine):
return True
else:
if val in seen:
return True
seen.append(val)
try:
machines = dmap["create"][val]["requires"]
except KeyError:
machines = []
for machine in machines:
if self._has_loop(dmap, seen=list(seen), val=machine):
return True
return False
def _calcdep(self, dmap, machine, data, level):
try:
deplist = data["requires"]
except KeyError:
return level
levels = []
for name in deplist:
try:
data = dmap["create"][name]
except KeyError:
try:
data = dmap["existing"][name]
except KeyError:
msg = "Missing dependency in cloud map"
log.error(msg)
raise SaltCloudException(msg)
levels.append(self._calcdep(dmap, name, data, level))
level = max(levels) + 1
return level
def map_data(self, cached=False):
"""
Create a data map of what to execute on
"""
ret = {"create": {}}
pmap = self.map_providers_parallel(cached=cached)
exist = set()
defined = set()
rendered_map = copy.deepcopy(self.rendered_map)
for profile_name, nodes in rendered_map.items():
if profile_name not in self.opts["profiles"]:
msg = (
"The required profile, '{}', defined in the map "
"does not exist. The defined nodes, {}, will not "
"be created.".format(
profile_name, ", ".join("'{}'".format(node) for node in nodes)
)
)
log.error(msg)
if "errors" not in ret:
ret["errors"] = {}
ret["errors"][profile_name] = msg
continue
profile_data = self.opts["profiles"].get(profile_name)
for nodename, overrides in nodes.items():
# Get associated provider data, in case something like size
# or image is specified in the provider file. See issue #32510.
if (
"provider" in overrides
and overrides["provider"] != profile_data["provider"]
):
alias, driver = overrides.get("provider").split(":")
else:
alias, driver = profile_data.get("provider").split(":")
provider_details = copy.deepcopy(self.opts["providers"][alias][driver])
del provider_details["profiles"]
# Update the provider details information with profile data
# Profile data and node overrides should override provider data, if defined.
# This keeps map file data definitions consistent with -p usage.
salt.utils.dictupdate.update(provider_details, profile_data)
nodedata = copy.deepcopy(provider_details)
# Update profile data with the map overrides
for setting in ("grains", "master", "minion", "volumes", "requires"):
deprecated = "map_{}".format(setting)
if deprecated in overrides:
log.warning(
"The use of '%s' on the '%s' mapping has "
"been deprecated. The preferred way now is to "
"just define '%s'. For now, salt-cloud will do "
"the proper thing and convert the deprecated "
"mapping into the preferred one.",
deprecated,
nodename,
setting,
)
overrides[setting] = overrides.pop(deprecated)
# merge minion grains from map file
if (
"minion" in overrides
and "minion" in nodedata
and "grains" in overrides["minion"]
and "grains" in nodedata["minion"]
):
nodedata["minion"]["grains"].update(overrides["minion"]["grains"])
del overrides["minion"]["grains"]
# remove minion key if now is empty dict
if not overrides["minion"]:
del overrides["minion"]
nodedata = salt.utils.dictupdate.update(nodedata, overrides)
# Add the computed information to the return data
ret["create"][nodename] = nodedata
# Add the node name to the defined set
alias, driver = nodedata["provider"].split(":")
defined.add((alias, driver, nodename))
def get_matching_by_name(name):
matches = {}
for alias, drivers in pmap.items():
for driver, vms in drivers.items():
for vm_name, details in vms.items():
if vm_name == name and driver not in matches:
matches[driver] = details["state"]
return matches
for alias, drivers in pmap.items():
for driver, vms in drivers.items():
for name, details in vms.items():
exist.add((alias, driver, name))
if name not in ret["create"]:
continue
# The machine is set to be created. Does it already exist?
matching = get_matching_by_name(name)
if not matching:
continue
# A machine by the same name exists
for item in matching:
if name not in ret["create"]:
# Machine already removed
break
log.warning(
"%r already exists, removing from the create map.", name
)
if "existing" not in ret:
ret["existing"] = {}
ret["existing"][name] = ret["create"].pop(name)
if "hard" in self.opts and self.opts["hard"]:
if self.opts["enable_hard_maps"] is False:
raise SaltCloudSystemExit(
"The --hard map can be extremely dangerous to use, "
"and therefore must explicitly be enabled in the main "
"configuration file, by setting 'enable_hard_maps' "
"to True"
)
# Hard maps are enabled, Look for the items to delete.
ret["destroy"] = exist.difference(defined)
return ret
def run_map(self, dmap):
"""
Execute the contents of the VM map
"""
if self._has_loop(dmap):
msg = "Uh-oh, that cloud map has a dependency loop!"
log.error(msg)
raise SaltCloudException(msg)
# Go through the create list and calc dependencies
for key, val in dmap["create"].items():
log.info("Calculating dependencies for %s", key)
level = 0
level = self._calcdep(dmap, key, val, level)
log.debug("Got execution order %s for %s", level, key)
dmap["create"][key]["level"] = level
try:
existing_list = dmap["existing"].items()
except KeyError:
existing_list = {}.items()
for key, val in existing_list:
log.info("Calculating dependencies for %s", key)
level = 0
level = self._calcdep(dmap, key, val, level)
log.debug("Got execution order %s for %s", level, key)
dmap["existing"][key]["level"] = level
# Now sort the create list based on dependencies
create_list = sorted(dmap["create"].items(), key=lambda x: x[1]["level"])
output = {}
if self.opts["parallel"]:
parallel_data = []
master_name = None
master_minion_name = None
master_host = None
master_finger = None
try:
master_name, master_profile = next(
(
(name, profile)
for name, profile in create_list
if profile.get("make_master", False) is True
)
)
master_minion_name = master_name
log.debug("Creating new master '%s'", master_name)
if (
salt.config.get_cloud_config_value("deploy", master_profile, self.opts)
is False
):
raise SaltCloudSystemExit(
"Cannot proceed with 'make_master' when salt deployment "
"is disabled(ex: --no-deploy)."
)
# Generate the master keys
log.debug("Generating master keys for '%s'", master_profile["name"])
priv, pub = salt.utils.cloud.gen_keys(
salt.config.get_cloud_config_value("keysize", master_profile, self.opts)
)
master_profile["master_pub"] = pub
master_profile["master_pem"] = priv
# Generate the fingerprint of the master pubkey in order to
# mitigate man-in-the-middle attacks
master_temp_pub = salt.utils.files.mkstemp()
with salt.utils.files.fopen(master_temp_pub, "w") as mtp:
mtp.write(pub)
master_finger = salt.utils.crypt.pem_finger(
master_temp_pub, sum_type=self.opts["hash_type"]
)
os.unlink(master_temp_pub)
if master_profile.get("make_minion", True) is True:
master_profile.setdefault("minion", {})
if "id" in master_profile["minion"]:
master_minion_name = master_profile["minion"]["id"]
# Set this minion's master as local if the user has not set it
if "master" not in master_profile["minion"]:
master_profile["minion"]["master"] = "127.0.0.1"
if master_finger is not None:
master_profile["master_finger"] = master_finger
# Generate the minion keys to pre-seed the master:
for name, profile in create_list:
make_minion = salt.config.get_cloud_config_value(
"make_minion", profile, self.opts, default=True
)
if make_minion is False:
continue
log.debug("Generating minion keys for '%s'", profile["name"])
priv, pub = salt.utils.cloud.gen_keys(
salt.config.get_cloud_config_value("keysize", profile, self.opts)
)
profile["pub_key"] = pub
profile["priv_key"] = priv
# Store the minion's public key in order to be pre-seeded in
# the master
master_profile.setdefault("preseed_minion_keys", {})
master_profile["preseed_minion_keys"].update({name: pub})
local_master = False
if (
master_profile["minion"].get("local_master", False)
and master_profile["minion"].get("master", None) is not None
):
# The minion is explicitly defining a master and it's
# explicitly saying it's the local one
local_master = True
out = self.create(master_profile, local_master=local_master)
if not isinstance(out, dict):
log.debug("Master creation details is not a dictionary: %s", out)
elif "Errors" in out:
raise SaltCloudSystemExit(
"An error occurred while creating the master, not "
"continuing: {}".format(out["Errors"])
)
deploy_kwargs = (
self.opts.get("show_deploy_args", False) is True
and
# Get the needed data
out.get("deploy_kwargs", {})
or
# Strip the deploy_kwargs from the returned data since we don't
# want it shown in the console.
out.pop("deploy_kwargs", {})
)
master_host = deploy_kwargs.get(
"salt_host", deploy_kwargs.get("host", None)
)
if master_host is None:
raise SaltCloudSystemExit(
"Host for new master {} was not found, aborting map".format(
master_name
)
)
output[master_name] = out
except StopIteration:
log.debug("No make_master found in map")
# Local master?
# Generate the fingerprint of the master pubkey in order to
# mitigate man-in-the-middle attacks
master_pub = os.path.join(self.opts["pki_dir"], "master.pub")
if os.path.isfile(master_pub):
master_finger = salt.utils.crypt.pem_finger(
master_pub, sum_type=self.opts["hash_type"]
)
opts = self.opts.copy()
if self.opts["parallel"]:
# Force display_ssh_output to be False since the console will
# need to be reset afterwards
log.info(
"Since parallel deployment is in use, ssh console output "
"is disabled. All ssh output will be logged though"
)
opts["display_ssh_output"] = False
local_master = master_name is None
for name, profile in create_list:
if name in (master_name, master_minion_name):
# Already deployed, it's the master's minion
continue
if (
"minion" in profile
and profile["minion"].get("local_master", False)
and profile["minion"].get("master", None) is not None
):
# The minion is explicitly defining a master and it's
# explicitly saying it's the local one
local_master = True
if master_finger is not None and local_master is False:
profile["master_finger"] = master_finger
if master_host is not None:
profile.setdefault("minion", {})
profile["minion"].setdefault("master", master_host)
if self.opts["parallel"]:
parallel_data.append(
{
"opts": opts,
"name": name,
"profile": profile,
"local_master": local_master,
}
)
continue
# Not deploying in parallel
try:
output[name] = self.create(profile, local_master=local_master)
if (
self.opts.get("show_deploy_args", False) is False
and "deploy_kwargs" in output
and isinstance(output[name], dict)
):
output[name].pop("deploy_kwargs", None)
except SaltCloudException as exc:
log.error(
"Failed to deploy '%s'. Error: %s",
name,
exc,
exc_info_on_loglevel=logging.DEBUG,
)
output[name] = {"Error": str(exc)}
for name in dmap.get("destroy", ()):
output[name] = self.destroy(name)
if self.opts["parallel"] and parallel_data:
if "pool_size" in self.opts:
pool_size = self.opts["pool_size"]
else:
pool_size = len(parallel_data)
log.info("Cloud pool size: %s", pool_size)
output_multip = enter_mainloop(
_create_multiprocessing, parallel_data, pool_size=pool_size
)
# We have deployed in parallel, now do start action in
# correct order based on dependencies.
if self.opts["start_action"]:
actionlist = []
grp = -1
for key, val in groupby(dmap["create"].values(), lambda x: x["level"]):
actionlist.append([])
grp += 1
for item in val:
actionlist[grp].append(item["name"])
out = {}
for group in actionlist:
log.info(
"Running %s on %s", self.opts["start_action"], ", ".join(group)
)
with salt.client.get_local_client() as client:
out.update(
client.cmd(
",".join(group),
self.opts["start_action"],
timeout=self.opts["timeout"] * 60,
tgt_type="list",
)
)
for obj in output_multip:
next(iter(obj.values()))["ret"] = out[next(iter(obj.keys()))]
output.update(obj)
else:
for obj in output_multip:
output.update(obj)
return output
def init_pool_worker():
"""
Make every worker ignore KeyboarInterrup's since it will be handled by the
parent process.
"""
signal.signal(signal.SIGINT, signal.SIG_IGN)
def create_multiprocessing(parallel_data, queue=None):
"""
This function will be called from another process when running a map in
parallel mode. The result from the create is always a json object.
"""
salt.utils.crypt.reinit_crypto()
parallel_data["opts"]["output"] = "json"
cloud = Cloud(parallel_data["opts"])
try:
output = cloud.create(
parallel_data["profile"], local_master=parallel_data["local_master"]
)
except SaltCloudException as exc:
log.error(
"Failed to deploy '%s'. Error: %s",
parallel_data["name"],
exc,
exc_info_on_loglevel=logging.DEBUG,
)
return {parallel_data["name"]: {"Error": str(exc)}}
if parallel_data["opts"].get("show_deploy_args", False) is False and isinstance(
output, dict
):
output.pop("deploy_kwargs", None)
return {parallel_data["name"]: salt.utils.data.simple_types_filter(output)}
def destroy_multiprocessing(parallel_data, queue=None):
"""
This function will be called from another process when running a map in
parallel mode. The result from the destroy is always a json object.
"""
salt.utils.crypt.reinit_crypto()
parallel_data["opts"]["output"] = "json"
clouds = salt.loader.clouds(parallel_data["opts"])
try:
fun = clouds["{}.destroy".format(parallel_data["driver"])]
with salt.utils.context.func_globals_inject(
fun,
__active_provider_name__=":".join(
[parallel_data["alias"], parallel_data["driver"]]
),
):
output = fun(parallel_data["name"])
except SaltCloudException as exc:
log.error(
"Failed to destroy %s. Error: %s",
parallel_data["name"],
exc,
exc_info_on_loglevel=logging.DEBUG,
)
return {parallel_data["name"]: {"Error": str(exc)}}
return {parallel_data["name"]: salt.utils.data.simple_types_filter(output)}
def run_parallel_map_providers_query(data, queue=None):
"""
This function will be called from another process when building the
providers map.
"""
salt.utils.crypt.reinit_crypto()
cloud = Cloud(data["opts"])
try:
with salt.utils.context.func_globals_inject(
cloud.clouds[data["fun"]],
__active_provider_name__=":".join([data["alias"], data["driver"]]),
):
return (
data["alias"],
data["driver"],
salt.utils.data.simple_types_filter(cloud.clouds[data["fun"]]()),
)
except Exception as err: # pylint: disable=broad-except
log.debug(
"Failed to execute '%s()' while querying for running nodes: %s",
data["fun"],
err,
exc_info_on_loglevel=logging.DEBUG,
)
# Failed to communicate with the provider, don't list any nodes
return data["alias"], data["driver"], ()
# for pickle and multiprocessing, we can't use directly decorators
def _run_parallel_map_providers_query(*args, **kw):
return communicator(run_parallel_map_providers_query)(*args[0], **kw)
def _destroy_multiprocessing(*args, **kw):
return communicator(destroy_multiprocessing)(*args[0], **kw)
def _create_multiprocessing(*args, **kw):
return communicator(create_multiprocessing)(*args[0], **kw)
|
run_experiment.py | import atexit
import sacred
import argparse
import time
import math
import subprocess
import shutil
import os
import json
import threading
import requests
import glob
from configs import fetch_model_params
import socket
import subprocess
import queue
import sys
import signal
parser = argparse.ArgumentParser()
parser.add_argument('--tpu', type=str, required=True) # Name of TPU to train on, if any
parser.add_argument('--model', type=str, required=True) # JSON file that contains model parameters
parser.add_argument('--experiment_name', type=str, required=True) # name of experiment (will show up in omniboard)
parser.add_argument('--steps_per_checkpoint', type=int, default=5000)
parser.add_argument('--autostack', action="store_false")
parser.add_argument('--auto_layout', action="store_true")
parser.add_argument('--auto_layout_and_mesh_shape', action="store_true")
parser.add_argument('--new', action='store_true')
parser.add_argument('--test', action='store_true')
parser.add_argument('--predict', action='store_true')
parser.add_argument('--no_delete_tpu', action='store_true')
parser.add_argument('--heartbeat_timeout', type=int, default=36000) # kill and restart if nothing logged to tensorboard in this many seconds
args = parser.parse_args()
params = fetch_model_params(args.model)
ex = sacred.Experiment(args.experiment_name)
ex.observers.append(sacred.observers.QueuedMongoObserver(url='127.0.0.1:27017', db_name='db', username='user', password='password'))
def get_open_port(lo=8000, hi=8100):
for i in range(lo, hi):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
if s.connect_ex(('localhost', i)) != 0:
return i
def train_thread(args, tpu, id, q):
print('starting training on', tpu)
# pass binary flags through
opts = ''
for flag in ['auto_layout', 'auto_layout_and_mesh_shape', 'new', 'test', 'predict', ]:
if args.__getattribute__(flag):
opts += ' --' + flag
for flag in ['autostack', ]:
if not args.__getattribute__(flag):
opts += ' --' + flag
cmd = "python3 main.py --tpu {tpu} --model run_configs/config_{id}.json --steps_per_checkpoint {steps_per_checkpoint} {opts} --sacred_id {run_id}".format(tpu=tpu, id=id, steps_per_checkpoint=args.steps_per_checkpoint, opts=opts, run_id=id)
print('Running:', cmd)
proc = subprocess.Popen(cmd, shell=True)
# poll until it's exited
while proc.poll() is None:
time.sleep(60)
try:
nq, *nargs = q.get_nowait()
if nq == 'kill':
print('train thread recieved kill signal from logging thread')
# first send SIGTERM
proc.terminate()
time.sleep(60)
# if it still hasn't exited, we send SIGKILL
if proc.poll() is None:
print('SIGTERM not successful, sending SIGKILL')
proc.kill()
except queue.Empty:
pass
print('exited training!')
if proc.returncode == 0:
print('exited gracefully')
os.kill(os.getpid(), signal.SIGINT)
if args.no_delete_tpu:
print('recreate done, exiting train_thread - not killing tpu!')
return
print("Recreating {} in 60sec...".format(tpu))
time.sleep(60)
os.system("pu recreate {} --yes --retry 3600 --retry-randomness 1.5".format(tpu))
print('recreate done, exiting train_thread')
# clear out queue
while True:
try:
q.get_nowait()
print('dropped request in queue after pu recreate')
except queue.Empty:
break
def get_json(uri, params=None, timeout=15):
resp = requests.get(uri, params=params, timeout=timeout)
resp.raise_for_status()
return resp.json()
def get_tag_sets(base_uri):
j = get_json(f'{base_uri}/data/plugin/scalars/tags', {'experiment': ''})
assert isinstance(j, dict)
return {
run: j[run].keys()
for run in j.keys()
}
def get_scalar_data(base_uri, run, tag):
j = get_json(f'{base_uri}/data/plugin/scalars/scalars', {'experiment': '', 'run': run, 'tag': tag})
assert isinstance(j, list)
return j
def get_run_data(port):
base_uri = f'http://localhost:{port}/'
r = {}
try:
tag_sets = get_tag_sets(base_uri)
runs = tag_sets.keys()
if '.' in runs:
if 'loss' in tag_sets['.']:
r['loss'] = get_scalar_data(base_uri, '.', 'loss')
if 'eval' in runs:
if 'loss' in tag_sets['eval']:
r['val_loss'] = get_scalar_data(base_uri, 'eval', 'loss')
if 'eval_lambada' in runs:
if 'lambada_acc' in tag_sets['eval_lambada']:
r['lambada_acc'] = get_scalar_data(base_uri, 'eval_lambada', 'lambada_acc')
if 'lambada_log_ppl' in tag_sets['eval_lambada']:
r['lambada_ppl'] = [
[t, s, math.exp(lp)]
for [t, s, lp] in get_scalar_data(base_uri, 'eval_lambada', 'lambada_log_ppl')
]
except:
import traceback
traceback.print_exc()
return r
@ex.main
def main(_run):
print('Starting run', _run._id)
print('experiment main invoked with argv:', " ".join(sys.argv))
print('WARNING: please remember to remove old metric log files from the model directory.')
os.makedirs('run_configs', exist_ok=True)
shutil.copy(args.model if args.model.endswith('.json') else 'configs/{}.json'.format(args.model), 'run_configs/config_{}.json'.format(_run._id))
tensorboard_port = get_open_port()
print('Tensorboard at port:', tensorboard_port)
print('Tensorboard url: ', 'http://eleutherai.bmk.sh:'+ str(tensorboard_port))
os.system("screen -S tensorboard_{} -d -m bash -c 'tensorboard --logdir {} --port {} --bind_all --reload_multifile=true || tensorboard --logdir {} --port {} --reload_multifile=true'".format(_run._id, params["model_path"], tensorboard_port,params["model_path"], tensorboard_port,))
atexit.register(goodbye, _run._id)
curr_step = {}
seen_predictions = set()
while True:
last_tb_log_time = time.time()
q = queue.Queue()
trainthd = threading.Thread(target=train_thread, args=(args, args.tpu, _run._id, q))
trainthd.start()
while trainthd.is_alive():
time.sleep(60)
print('Polling tensorboard for metrics...')
data = get_run_data(tensorboard_port)
for k in data.keys():
for ts, step, val in data[k]:
if step <= curr_step.get(k, -1):
continue
_run.log_scalar(k, val, step)
if k == 'loss':
_run.log_scalar('tb_ts', ts, step)
print('Logged to sacred: step={},loss={},tb_ts={}'.format(step, val, ts))
# found something new, so logging!
last_tb_log_time = time.time()
curr_step[k] = step
for f in glob.glob('predictions_{}_*'.format(_run._id)):
if f in seen_predictions:
continue
print('collecting prediction file', f)
ex.add_artifact(f)
seen_predictions.add(f)
# collect eval metrics from jsonl
if os.path.exists(f'eval_{_run._id}.jsonl'):
with open(f'eval_{_run._id}.jsonl') as fh:
for line in fh:
ob = json.loads(line)
val_step = ob['global_step']
val_task = ob['task']
for metr in ob.keys():
k = 'fs.' + val_task + '.' + metr
if metr in ['task', 'global_step']: continue
if val_step <= curr_step.get(k, -1): continue
_run.log_scalar(k, ob[metr], val_step)
curr_step[k] = val_step
if time.time() - last_tb_log_time > args.heartbeat_timeout:
# the run hasn't logged in a while, so we restart it
q.put(('kill',))
# give training thread some time to do its thing and recreate tpu
while trainthd.is_alive():
print('logging thread waiting for killing stalled run and for tpu recreate to finish')
time.sleep(60)
if args.no_delete_tpu:
break
def goodbye(id):
print("You are now leaving the Python sector.")
print("Sie verlassen den pythonischen Sektor.")
os.system("screen -S tensorboard_{} -X quit".format(id))
if __name__ == '__main__':
for file in glob.glob("**/*", recursive=True):
if file.split('.')[-1] in ['py']:
print('Adding', file, 'to sacred')
ex.add_source_file(file)
ex.add_config({
'tpu_name': args.tpu,
**params
})
ex.run()
|
utils.py | import logging
import os
import subprocess
import sys
import time
from multiprocessing import Process
import git
import yaml
from ms.config import Config
log = logging.getLogger(__name__)
# Config
BASE_DIR = os.path.abspath(os.path.expanduser(Config.get('BASE_DIR')))
DOCKER_COMPOSE_FILE = Config.get(
'DOCKER_COMPOSE_FILE', os.path.join(BASE_DIR, 'docker-compose-tmp.yml'))
SERVICE_MAPPING = Config.get('SERVICE_MAPPING', {})
SERVICE_CONSTELLATIONS = Config.get('SERVICE_CONSTELLATIONS', {})
SINGLETON_SERVICES = Config.get('SINGLETON_SERVICES', {})
KEEP_DOCKER_COMPOSE_FILE_ON_SHUTDOWN = Config.get('KEEP_DOCKER_COMPOSE_FILE_ON_SHUTDOWN', False)
def run_docker_compose_command(cmd, verbose=False, log_level=None):
"""
Run a Docker Compose command
e.g.:
run_docker_compose_command('up worker')
run_docker_compose_command('up')
"""
# Try to avoid docker-compose up read timeout error when starting a lot of containers
os.environ['COMPOSE_HTTP_TIMEOUT'] = '300'
args = ['docker-compose']
if verbose:
args += ['--verbose']
if log_level:
args += ['--log-level', log_level]
args += ['-f', DOCKER_COMPOSE_FILE]
if type(cmd) == list: # If passed as an array, use arguments grouped as passed
args += cmd
else:
args += cmd.split(' ')
subprocess.call(args)
def run_docker_command(cmd):
if type(cmd) == list: # If passed as an array, use arguments grouped as passed
subprocess.call(['docker'] + cmd)
else:
subprocess.call(['docker'] + cmd.split(' '))
def remove_docker_compose_file():
"""Removes the temporary docker-compose file"""
os.remove(DOCKER_COMPOSE_FILE)
def check_for_docker_compose_file():
"""
Check to see if a microservices CLI docker-compose file is present. The absence of one
suggests that the CLI is not currently running.
"""
return os.path.isfile(DOCKER_COMPOSE_FILE)
def should_remove_docker_compose_file():
keep_compose_file = not KEEP_DOCKER_COMPOSE_FILE_ON_SHUTDOWN and check_for_docker_compose_file()
log.debug(f'should keep docker-compose-tmp.yml: {keep_compose_file}')
return keep_compose_file
def docker_compose_attach(service):
"""Attempt to attach to a running docker service."""
try:
run_docker_compose_command('exec {} bash'.format(service))
except subprocess.CalledProcessError:
log.error('Could not attach to [{}] service, is it running?'.format(service))
sys.exit(1)
def docker_compose_restart(service):
"""Attempt to restart a running docker service."""
try:
run_docker_compose_command('restart {}'.format(service))
except subprocess.CalledProcessError:
log.error('Could not restart [{}] service, is it running?'.format(service))
sys.exit(1)
def get_list_of_services(services):
"""
Takes a list of services/constellation from the command line and maps them to the preferred names.
Also validates that these are directories and they have a docker-compose file in them.
"""
if not services: # If no services passed, get all folders with a docker-compose file
services = find_docker_compose_services()
# See if service passed in is a constellation, if so expand
if len(services) == 1 and services[0] in SERVICE_CONSTELLATIONS:
services = SERVICE_CONSTELLATIONS[services[0]]
# Check that each service is in the directory and has a docker-compose file
check_services(services)
return services
def start_docker_compose_services(args, mapped_services):
"""
Runs docker-compose up for services defined in the temporary docker-compose file,
remove the file when halted with Ctrl+C.
"""
try:
start_time = time.time()
mapped_services = list(mapped_services)
if args.ignore:
for service_to_ignore in args.ignore:
mapped_services.remove(service_to_ignore)
log.debug(f'mapped serviced: {mapped_services}')
log.debug(f'ignored: {args.ignore}')
run_docker_compose_command(['up'] + mapped_services, log_level=args.l, verbose=args.v)
log.debug(f'Started in {time.time() - start_time}')
except KeyboardInterrupt:
if should_remove_docker_compose_file():
remove_docker_compose_file()
def stop_down_docker_compose_services(args, mapped_services):
"""
Runs docker-compose up for services defined in the temporary docker-compose file,
remove the file when halted with Ctrl+C.
"""
if args.ignore:
for service_to_ignore in args.ignore:
mapped_services.remove(service_to_ignore)
log.debug(f'mapped serviced: {mapped_services}')
run_docker_compose_command(['down'] + mapped_services + ['--remove-orphans'], log_level=args.l, verbose=args.v)
if should_remove_docker_compose_file():
remove_docker_compose_file()
def top_docker_compose_services(services):
"""
Runs docker-compose top for services defined in the temporary docker-compose file,
or specified services.
"""
run_docker_compose_command(['top'] + services)
def dockerhub_pull(services):
"""
Pull DockerHub images for the passed services in parallel.
"""
docker_services = get_list_of_services(services)
service_list = construct_docker_compose_file(docker_services)
procs = []
for service in service_list:
process = Process(target=run_docker_compose_command, args=(['pull', service],))
process.start()
procs.append(process)
for p in procs:
p.join()
remove_docker_compose_file()
def git_clone_repo(remote_url, target_dir):
"""
Clones a remote repository into a local directory.
"""
log.info('Cloning [{}] into [{}]'.format(remote_url, target_dir))
git.Repo.clone_from(remote_url, target_dir)
def git_pull_master(service, keep_branch=False):
"""
Takes a service, switches to master, and pulls code. If the keep_branch argument
is passed, it will switch back to the original branch if it was on anything other
than master.
"""
log.info('[{}] pulling master'.format(service))
repo = git.Repo(os.path.join(BASE_DIR, service))
if repo.active_branch.name != 'master':
current_branch = repo.active_branch
try:
repo.git.checkout('master')
repo.remotes.origin.pull()
if keep_branch:
current_branch.checkout()
except git.exc.GitCommandError:
log.error(
'Could not checkout master for service [{}], try checking in or stashing changes'.format(service))
sys.exit(1)
else:
repo.remotes.origin.pull()
def get_full_service_name(service, s):
"""
Returns a properly formed service name based on the service and process names passed in.
Will look up services in the service mapping dictionary to see if there's a preferred name.
"""
service_alias = SERVICE_MAPPING[service] if service in SERVICE_MAPPING else service
# Don't suffix service type if it's a web worker or the same as the service (e.g. gateway, haproxy)
if s == 'web' or service_alias == s:
return service_alias
return '{}-{}'.format(service_alias, s)
def construct_docker_compose_file(services):
"""
Construct a temporary docker-compose file from the passed services.
"""
data = {
'version': '2',
'services': {},
}
for service in services:
docker_compose_path = os.path.join(BASE_DIR, service, 'docker-compose.yml')
if not os.path.isfile(docker_compose_path):
log.error('Could not find docker-compose file for service {} in the path {}'.format(service, docker_compose_path))
sys.exit(1)
with open(docker_compose_path, 'r') as infile:
individual_services = yaml.load(infile)['services'].keys()
# Check for env override file
# Waiting on an optional env file to obviate the need for this: https://github.com/docker/compose/pull/3955
local_env_path = os.path.join(BASE_DIR, service, '.env.local')
env_override = os.path.isfile(local_env_path)
if env_override:
with open(local_env_path) as f:
env_override_block = [line.strip() for line in f if line != '\n' and not line.startswith('#')]
for s in individual_services:
if s in SINGLETON_SERVICES:
if s not in data['services']: # Make sure we only add it once
service_name = s
else:
continue
else:
service_name = get_full_service_name(service, s)
# Construct the service entry in the docker-compose outfile
data['services'][service_name] = {
'extends': {
'file': docker_compose_path,
'service': s
}
}
# If there's an environment override, set environment block here
if env_override and s not in SINGLETON_SERVICES:
data['services'][service_name]['environment'] = env_override_block
# Write docker-compose file
with open(DOCKER_COMPOSE_FILE, 'w') as outfile:
outfile.write(yaml.safe_dump(data))
# Return list of services
return data['services'].keys()
def print_docker_compose_path():
log.info(f'DOCKER_COMPOSE_FILE: {DOCKER_COMPOSE_FILE}')
def check_services(services):
"""
Takes an array of services and checks to see if the directories exist in the base
directory and that there are docker-compose files in each of them.
"""
dir_list = os.listdir(BASE_DIR)
for service in services:
# Check to see if they are in the root directory
if service not in dir_list or not os.path.isdir(os.path.join(BASE_DIR, service)):
log.error('Could not find service [{}] folder in the root directory'.format(service))
sys.exit(1)
# Check to see if there's a docker-compose file in the directory
directory = os.path.join(BASE_DIR, service)
if 'docker-compose.yml' not in os.listdir(directory):
log.error('Could not find docker-compose.yml file in [{}] service directory'.format(service))
sys.exit(1)
def find_docker_compose_services():
"""Traverses a base directory and determines which of the directories contain a `docker-compose.yml` file."""
dir_list = os.listdir(BASE_DIR)
directories = [d for d in dir_list if os.path.isdir(os.path.join(BASE_DIR, d))]
return [d for d in directories if 'docker-compose.yml' in os.listdir(os.path.join(BASE_DIR, d))]
def run_one_off_command(directory, command, service=None):
"""
Run a one-off command through docker-compose
TODO: Add support for running a command even when docker-compose already running
"""
if check_for_docker_compose_file():
log.info('docker-compose already running, consider attaching to a running container')
sys.exit(0)
project_services = construct_docker_compose_file([directory])
project_services = list(filter(lambda x: x not in SINGLETON_SERVICES, project_services))
if service: # Always use passed in service if present
service_name = get_full_service_name(directory, service)
else:
if len(project_services) == 1: # If only one service in directory (like worker), use that
service_name = project_services[0]
else:
service = 'web' if not service else service # If no --service, default to web
service_name = get_full_service_name(directory, service)
run_docker_compose_command(['run', '--rm', service_name] + command)
remove_docker_compose_file()
def kill_all_docker_containers():
"""
Find all running Docker containers and kill them.
"""
running_container_ids = get_running_container_ids()
if running_container_ids:
start_time = time.time()
subprocess.call(['docker', '-D', '-l', 'debug', 'kill'] + running_container_ids)
log.debug(f'Killed in {time.time() - start_time}')
def stop_all_docker_containers():
"""
Find all running Docker containers and kill them.
"""
running_container_ids = get_running_container_ids()
if running_container_ids:
subprocess.call(['docker', 'stop'] + running_container_ids)
def get_running_container_ids():
running_container_ids = subprocess.check_output(['docker', 'ps', '-q'])
running_container_ids = running_container_ids.strip().split() # Remove trailing \n and convert to list
return running_container_ids
def show_logs_for_running_containers(services, tail, tail_count):
"""Run the docker-compose logs command for one or more running containers"""
if not check_for_docker_compose_file():
log.info('No running containers found')
sys.exit(1)
try:
args = ['logs']
if tail:
args.append('-f')
if tail_count:
args.append(f'--tail={tail_count}')
final_result = args + services
run_docker_compose_command(final_result)
except KeyboardInterrupt:
sys.exit(0)
def list_all_docker_containers(ps_filter):
"""
List all docker containers by their name, status, command and state.
Specified filter is passed along to 'docker ps'
"""
try:
args = ['ps', '--format', 'table {{.Names}}\t{{.Status}}\t{{.Command}}\t{{.State}}\t{{.ID}}']
if ps_filter:
args.extend(['--filter', f'name={ps_filter}'])
run_docker_command(args)
except KeyboardInterrupt:
sys.exit(0)
def print_config():
subprocess.call(['cat', f'{DOCKER_COMPOSE_FILE}'])
|
main.py | import argparse
import collections
import dataclasses
import enum
import heapq
import importlib
import importlib.util
import inspect
import linecache
import multiprocessing
import multiprocessing.queues
import os
import os.path
import queue
import re
import shutil
import signal
import sys
import textwrap
import time
import traceback
import types
from typing import *
from typing import TextIO
from crosshair.auditwall import engage_auditwall
from crosshair.auditwall import opened_auditwall
from crosshair.diff_behavior import diff_behavior
from crosshair.core_and_libs import analyze_any
from crosshair.core_and_libs import analyze_module
from crosshair.core_and_libs import run_checkables
from crosshair.core_and_libs import AnalysisMessage
from crosshair.core_and_libs import MessageType
from crosshair.fnutil import load_by_qualname
from crosshair.fnutil import load_files_or_qualnames
from crosshair.fnutil import walk_paths
from crosshair.fnutil import FunctionInfo
from crosshair.fnutil import NotFound
from crosshair.options import option_set_from_dict
from crosshair.options import AnalysisKind
from crosshair.options import AnalysisOptionSet
from crosshair.options import AnalysisOptions
from crosshair.options import DEFAULT_OPTIONS
from crosshair.util import debug
from crosshair.util import extract_module_from_file
from crosshair.util import load_file
from crosshair.util import set_debug
from crosshair.util import CrosshairInternal
from crosshair.util import ErrorDuringImport
import crosshair.core_and_libs
def analysis_kind(argstr: str) -> Sequence[AnalysisKind]:
try:
return [AnalysisKind[part.strip()] for part in argstr.split(",")]
except KeyError:
raise ValueError
def command_line_parser() -> argparse.ArgumentParser:
common = argparse.ArgumentParser(
add_help=False, formatter_class=argparse.RawTextHelpFormatter
)
common.add_argument(
"--verbose",
"-v",
action="store_true",
help="Output additional debugging information on stderr",
)
common.add_argument(
"--per_path_timeout",
type=float,
metavar="FLOAT",
help="Maximum seconds to spend checking one execution path",
)
common.add_argument(
"--per_condition_timeout",
type=float,
metavar="FLOAT",
help="Maximum seconds to spend checking execution paths for one condition",
)
parser = argparse.ArgumentParser(
prog="crosshair", description="CrossHair Analysis Tool"
)
subparsers = parser.add_subparsers(help="sub-command help", dest="action")
check_parser = subparsers.add_parser(
"check",
help="Analyze a file or function",
parents=[common],
formatter_class=argparse.RawTextHelpFormatter,
description=textwrap.dedent(
"""\
The check command looks for counterexamples that break contracts.
It outputs machine-readable messages in this format on stdout:
<filename>:<line number>: error: <error message>
It exits with one of the following codes:
0 : No counterexamples are found
1 : Counterexample(s) have been found
2 : Other error
"""
),
)
check_parser.add_argument(
"--report_all",
action="store_true",
help="Output analysis results for all postconditions (not just failing ones)",
)
check_parser.add_argument(
"--report_verbose",
dest="report_verbose",
action="store_true",
help="Output context and stack traces for counterexamples",
)
check_parser.add_argument(
"file",
metavar="FILE",
type=str,
nargs="+",
help="file/directory or fully qualified module, class, or function",
)
watch_parser = subparsers.add_parser(
"watch",
help="Continuously watch and analyze a directory",
parents=[common],
formatter_class=argparse.RawTextHelpFormatter,
description=textwrap.dedent(
"""\
The watch command continuously looks for contract counterexamples.
Type Ctrl-C to stop this command.
"""
),
)
watch_parser.add_argument(
"directory",
metavar="FILE",
type=str,
nargs="+",
help=textwrap.dedent(
"""\
File or directory to watch. Directories will be recursively analyzed.
"""
),
)
for subparser in (check_parser, watch_parser):
subparser.add_argument(
"--analysis_kind",
type=analysis_kind,
metavar="KIND",
default=(AnalysisKind.PEP316, AnalysisKind.icontract, AnalysisKind.asserts),
help=textwrap.dedent(
"""\
Kind of contract to check. By default, all kinds are checked.
See https://crosshair.readthedocs.io/en/latest/kinds_of_contracts.html
PEP316 : docstring-based contracts
icontract : decorator-based contracts
asserts : interpret asserts as contracts
"""
),
)
diffbehavior_parser = subparsers.add_parser(
"diffbehavior",
formatter_class=argparse.RawTextHelpFormatter,
help="Find differences in the behavior of two functions",
description=textwrap.dedent(
"""\
Find differences in the behavior of two functions.
See https://crosshair.readthedocs.io/en/latest/diff_behavior.html
"""
),
parents=[common],
)
diffbehavior_parser.add_argument(
"fn1",
metavar="FUNCTION1",
type=str,
help='first fully-qualified function to compare (e.g. "mymodule.myfunc")',
)
diffbehavior_parser.add_argument(
"fn2",
metavar="FUNCTION2",
type=str,
help="second fully-qualified function to compare",
)
return parser
def mtime(path: str) -> Optional[float]:
try:
return os.stat(path).st_mtime
except FileNotFoundError:
return None
@dataclasses.dataclass(init=False)
class WatchedMember:
qual_name: str # (just for debugging)
content_hash: int
last_modified: float
def __init__(self, qual_name: str, body: str) -> None:
self.qual_name = qual_name
self.content_hash = hash(body)
self.last_modified = time.time()
def consider_new(self, new_version: "WatchedMember") -> bool:
if self.content_hash != new_version.content_hash:
self.content_hash = new_version.content_hash
self.last_modified = time.time()
return True
return False
WorkItemInput = Tuple[
str, AnalysisOptionSet, float # (filename)
] # (float is a deadline)
WorkItemOutput = Tuple[WatchedMember, Counter[str], List[AnalysisMessage]]
def import_error_msg(err: ErrorDuringImport) -> AnalysisMessage:
orig, frame = err.args
return AnalysisMessage(
MessageType.IMPORT_ERR, str(orig), frame.filename, frame.lineno, 0, ""
)
def pool_worker_process_item(
item: WorkItemInput,
) -> Tuple[Counter[str], List[AnalysisMessage]]:
filename, options, deadline = item
stats: Counter[str] = Counter()
options.stats = stats
try:
module = load_file(filename)
except NotFound as e:
debug(f'Not analyzing "{filename}" because sub-module import failed: {e}')
return (stats, [])
except ErrorDuringImport as e:
debug(f'Not analyzing "{filename}" because import failed: {e}')
return (stats, [import_error_msg(e)])
messages = run_checkables(analyze_module(module, options))
return (stats, messages)
def pool_worker_main(item: WorkItemInput, output: multiprocessing.queues.Queue) -> None:
try:
# TODO figure out a more reliable way to suppress this. Redirect output?
# Ignore ctrl-c in workers to reduce noisy tracebacks (the parent will kill us):
signal.signal(signal.SIGINT, signal.SIG_IGN)
if hasattr(os, "nice"): # analysis should run at a low priority
os.nice(10)
set_debug(False)
engage_auditwall()
(stats, messages) = pool_worker_process_item(item)
filename = item[0]
output.put((filename, stats, messages))
except BaseException as e:
raise CrosshairInternal("Worker failed while analyzing " + filename) from e
class Pool:
_workers: List[Tuple[multiprocessing.Process, WorkItemInput]]
_work: List[WorkItemInput]
_results: multiprocessing.queues.Queue
_max_processes: int
def __init__(self, max_processes: int) -> None:
self._workers = []
self._work = []
self._results = multiprocessing.Queue()
self._max_processes = max_processes
def _spawn_workers(self):
work_list = self._work
workers = self._workers
while work_list and len(self._workers) < self._max_processes:
work_item = work_list.pop()
with opened_auditwall():
process = multiprocessing.Process(
target=pool_worker_main, args=(work_item, self._results)
)
workers.append((process, work_item))
process.start()
def _prune_workers(self, curtime):
for worker, item in self._workers:
(_, _, deadline) = item
if worker.is_alive() and curtime > deadline:
debug("Killing worker over deadline", worker)
with opened_auditwall():
worker.terminate()
time.sleep(0.5)
if worker.is_alive():
worker.kill()
worker.join()
self._workers = [(w, i) for w, i in self._workers if w.is_alive()]
def terminate(self):
self._prune_workers(float("+inf"))
self._work = []
self._results.close()
def garden_workers(self):
self._prune_workers(time.time())
self._spawn_workers()
def is_working(self):
return self._workers or self._work
def submit(self, item: WorkItemInput) -> None:
self._work.append(item)
def has_result(self):
return not self._results.empty()
def get_result(self, timeout: float) -> Optional[WorkItemOutput]:
try:
return self._results.get(timeout=timeout)
except queue.Empty:
return None
def worker_initializer():
"""Ignore CTRL+C in the worker process."""
signal.signal(signal.SIGINT, signal.SIG_IGN)
class Watcher:
_paths: Set[str]
_pool: Pool
_modtimes: Dict[str, float]
_options: AnalysisOptionSet
_next_file_check: float = 0.0
_change_flag: bool = False
def __init__(self, options: AnalysisOptionSet, files: Iterable[str]):
self._paths = set(files)
self._pool = self.startpool()
self._modtimes = {}
self._options = options
try:
# just to force an exit if we can't find a path:
list(walk_paths(self._paths))
except FileNotFoundError as exc:
print(f'Watch path "{exc.args[0]}" does not exist.', file=sys.stderr)
sys.exit(2)
def startpool(self) -> Pool:
return Pool(multiprocessing.cpu_count() - 1)
def run_iteration(
self, max_condition_timeout=0.5
) -> Iterator[Tuple[Counter[str], List[AnalysisMessage]]]:
debug(f"starting pass " f"with a condition timeout of {max_condition_timeout}")
debug("Files:", self._modtimes.keys())
pool = self._pool
for filename in self._modtimes.keys():
worker_timeout = max(10.0, max_condition_timeout * 20.0)
iter_options = AnalysisOptionSet(
per_condition_timeout=max_condition_timeout,
per_path_timeout=max_condition_timeout / 4,
)
options = self._options.overlay(iter_options)
pool.submit((filename, options, time.time() + worker_timeout))
pool.garden_workers()
while pool.is_working():
result = pool.get_result(timeout=1.0)
if result is not None:
(_, counters, messages) = result
yield (counters, messages)
if pool.has_result():
continue
change_detected = self.check_changed()
if change_detected:
self._change_flag = True
debug("Aborting iteration on change detection")
pool.terminate()
self._pool = self.startpool()
return
pool.garden_workers()
debug("Worker pool tasks complete")
yield (Counter(), [])
def run_watch_loop(self, max_watch_iterations=sys.maxsize) -> None:
restart = True
stats: Counter[str] = Counter()
active_messages: Dict[Tuple[str, int], AnalysisMessage]
for itr_num in range(max_watch_iterations):
if restart:
clear_screen()
clear_line("-")
line = f" Analyzing {len(self._modtimes)} files. \r"
sys.stdout.write(color(line, AnsiColor.OKBLUE))
max_condition_timeout = 0.5
restart = False
stats = Counter()
active_messages = {}
else:
time.sleep(0.5)
max_condition_timeout *= 2
for curstats, messages in self.run_iteration(max_condition_timeout):
debug("stats", curstats, messages)
stats.update(curstats)
if messages_merged(active_messages, messages):
linecache.checkcache()
clear_screen()
options = DEFAULT_OPTIONS.overlay(self._options)
for message in active_messages.values():
lines = long_describe_message(message, options)
if lines is None:
continue
clear_line("-")
print(lines, end="")
clear_line("-")
line = f' Analyzed {stats["num_paths"]} paths in {len(self._modtimes)} files. \r'
sys.stdout.write(color(line, AnsiColor.OKBLUE))
if self._change_flag:
self._change_flag = False
restart = True
line = f" Restarting analysis over {len(self._modtimes)} files. \r"
sys.stdout.write(color(line, AnsiColor.OKBLUE))
def check_changed(self) -> bool:
if time.time() < self._next_file_check:
return False
modtimes = self._modtimes
changed = False
for curfile in walk_paths(self._paths):
cur_mtime = mtime(curfile)
if cur_mtime == modtimes.get(curfile):
continue
changed = True
if cur_mtime is None:
del modtimes[curfile]
else:
modtimes[curfile] = cur_mtime
self._next_file_check = time.time() + 1.0
if not changed:
return False
return True
def clear_screen():
print("\n" * shutil.get_terminal_size().lines, end="")
def clear_line(ch=" "):
sys.stdout.write(ch * shutil.get_terminal_size().columns)
class AnsiColor(enum.Enum):
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
def color(text: str, *effects: AnsiColor) -> str:
return "".join(e.value for e in effects) + text + AnsiColor.ENDC.value
def messages_merged(
messages: MutableMapping[Tuple[str, int], AnalysisMessage],
new_messages: Iterable[AnalysisMessage],
) -> bool:
any_change = False
for message in new_messages:
key = (message.filename, message.line)
if key not in messages or messages[key] != message:
messages[key] = message
any_change = True
return any_change
def watch(
args: argparse.Namespace,
options: AnalysisOptionSet,
max_watch_iterations=sys.maxsize,
) -> int:
# Avoid fork() because we've already imported the code we're watching:
multiprocessing.set_start_method("spawn")
if not args.directory:
print("No files or directories given to watch", file=sys.stderr)
return 2
try:
watcher = Watcher(options, args.directory)
watcher.check_changed()
watcher.run_watch_loop(max_watch_iterations)
except KeyboardInterrupt:
pass
watcher._pool.terminate()
print()
print("I enjoyed working with you today!")
return 0
def format_src_context(filename: str, lineno: int) -> str:
amount = 3
line_numbers = range(max(1, lineno - amount), lineno + amount + 1)
output = [f"{filename}:{lineno}:\n"]
for curline in line_numbers:
text = linecache.getline(filename, curline)
if text == "": # (actual empty lines have a newline)
continue
output.append(
">" + color(text, AnsiColor.WARNING) if lineno == curline else "|" + text
)
return "".join(output)
def describe_message(
message: AnalysisMessage, options: AnalysisOptions
) -> Optional[str]:
if options.report_verbose:
return long_describe_message(message, options)
else:
return short_describe_message(message, options)
def long_describe_message(
message: AnalysisMessage, options: AnalysisOptions
) -> Optional[str]:
tb, desc, state = message.traceback, message.message, message.state
desc = desc.replace(" when ", "\nwhen ")
context = format_src_context(message.filename, message.line)
intro = ""
if not options.report_all:
if message.state <= MessageType.PRE_UNSAT: # type: ignore
return None
if state == MessageType.CONFIRMED:
intro = "I was able to confirm your postcondition over all paths."
elif state == MessageType.CANNOT_CONFIRM:
intro = "I wasn't able to find a counterexample."
elif message.state == MessageType.PRE_UNSAT:
intro = "I am having trouble finding any inputs that meet your preconditions."
elif message.state == MessageType.POST_ERR:
intro = "I got an error while checking your postcondition."
elif message.state == MessageType.EXEC_ERR:
intro = "I found an exception while running your function."
elif message.state == MessageType.POST_FAIL:
intro = "I was able to make your postcondition return False."
elif message.state == MessageType.SYNTAX_ERR:
intro = "One of your conditions isn't a valid python expression."
elif message.state == MessageType.IMPORT_ERR:
intro = "I couldn't import a file."
if message.state <= MessageType.CANNOT_CONFIRM: # type: ignore
intro = color(intro, AnsiColor.OKGREEN)
else:
intro = color(intro, AnsiColor.FAIL)
return f"{tb}\n{intro}\n{context}\n{desc}\n"
def short_describe_message(
message: AnalysisMessage, options: AnalysisOptions
) -> Optional[str]:
desc = message.message
if message.state <= MessageType.PRE_UNSAT: # type: ignore
if options.report_all:
return "{}:{}: {}: {}".format(message.filename, message.line, "info", desc)
return None
if message.state == MessageType.POST_ERR:
desc = "Error while evaluating post condition: " + desc
return "{}:{}: {}: {}".format(message.filename, message.line, "error", desc)
def diffbehavior(
args: argparse.Namespace, options: AnalysisOptions, stdout: TextIO, stderr: TextIO
) -> int:
def checked_load(qualname: str) -> Optional[FunctionInfo]:
try:
objs = list(load_files_or_qualnames([qualname]))
except Exception as exc:
print(f'Unable to load "{qualname}": {exc}', file=stderr)
return None
obj = objs[0]
if not isinstance(obj, FunctionInfo):
print(f'"{qualname}" does not target a function.', file=stderr)
return None
return obj
(fn_name1, fn_name2) = (args.fn1, args.fn2)
fn1 = checked_load(fn_name1)
fn2 = checked_load(fn_name2)
if fn1 is None or fn2 is None:
return 2
options.stats = collections.Counter()
diffs = diff_behavior(fn1, fn2, options)
debug("stats", options.stats)
if isinstance(diffs, str):
print(diffs, file=stderr)
return 2
elif len(diffs) == 0:
num_paths = options.stats["num_paths"]
exhausted = options.stats["exhaustion"] > 0
stdout.write(f"No differences found. (attempted {num_paths} iterations)\n")
if exhausted:
stdout.write("All paths exhausted, functions are likely the same!\n")
else:
stdout.write(
"Consider trying longer with: --per_condition_timeout=<seconds>\n"
)
return 0
else:
width = max(len(fn_name1), len(fn_name2)) + 2
for diff in diffs:
inputs = ", ".join(f"{k}={v}" for k, v in diff.args.items())
stdout.write(f"Given: ({inputs}),\n")
result1, result2 = diff.result1, diff.result2
differing_args = result1.get_differing_arg_mutations(result2)
stdout.write(
f"{fn_name1.rjust(width)} : {result1.describe(differing_args)}\n"
)
stdout.write(
f"{fn_name2.rjust(width)} : {result2.describe(differing_args)}\n"
)
return 1
def check(
args: argparse.Namespace, options: AnalysisOptionSet, stdout: TextIO, stderr: TextIO
) -> int:
any_problems = False
try:
entities = list(load_files_or_qualnames(args.file))
except FileNotFoundError as exc:
print(f'File not found: "{exc.args[0]}"', file=stderr)
return 2
except ErrorDuringImport as exc:
print(exc.args[0], file=stderr)
return 2
full_options = DEFAULT_OPTIONS.overlay(report_verbose=False).overlay(options)
for entity in entities:
debug("Check ", getattr(entity, "__name__", str(entity)))
for message in run_checkables(analyze_any(entity, options)):
line = describe_message(message, full_options)
if line is None:
continue
stdout.write(line + "\n")
debug("Traceback for output message:\n", message.traceback)
if message.state > MessageType.PRE_UNSAT:
any_problems = True
return 1 if any_problems else 0
def unwalled_main(cmd_args: Union[List[str], argparse.Namespace]) -> None:
if isinstance(cmd_args, argparse.Namespace):
args = cmd_args
else:
args = command_line_parser().parse_args(cmd_args)
set_debug(args.verbose)
options = option_set_from_dict(args.__dict__)
if sys.path and sys.path[0] != "":
# fall back to current directory to look up modules
sys.path.append("")
if args.action == "check":
exitcode = check(args, options, sys.stdout, sys.stderr)
elif args.action == "diffbehavior":
defaults = DEFAULT_OPTIONS.overlay(
AnalysisOptionSet(
per_condition_timeout=2.5,
per_path_timeout=30.0, # mostly, we don't want to time out paths
)
)
exitcode = diffbehavior(args, defaults.overlay(options), sys.stdout, sys.stderr)
elif args.action == "watch":
exitcode = watch(args, options)
else:
print(f'Unknown action: "{args.action}"', file=sys.stderr)
exitcode = 2
sys.exit(exitcode)
def mypy_and_check(cmd_args: Optional[List[str]] = None) -> None:
if cmd_args is None:
cmd_args = sys.argv[1:]
cmd_args = ["check"] + cmd_args
check_args, mypy_args = command_line_parser().parse_known_args(cmd_args)
set_debug(check_args.verbose)
mypy_cmd_args = mypy_args + check_args.file
debug("Running mypy with the following arguments:", " ".join(mypy_cmd_args))
try:
from mypy import api
except ModuleNotFoundError:
print("Unable to find mypy; skipping", file=sys.stderr)
else:
_mypy_out, mypy_err, mypy_ret = api.run(mypy_cmd_args)
print(mypy_err, file=sys.stderr)
if mypy_ret != 0:
sys.exit(mypy_ret)
engage_auditwall()
debug("Running crosshair with these args:", check_args)
unwalled_main(check_args)
def main(cmd_args: Optional[List[str]] = None) -> None:
if cmd_args is None:
cmd_args = sys.argv[1:]
engage_auditwall()
unwalled_main(cmd_args)
if __name__ == "__main__":
main()
|
server.py | import threading
import socket
import sys
import ssl
from sirup import var, logger, handler
def deamon(proto, port):
if proto == "tcp":
try:
print("{} {} Starting TCP SIP deamon on Port {}".format(
var.info, var.ts(), var.tcp_port))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0", port))
s.listen()
except:
print("{} {} An error occurred with TCP SIP deamon".format(
var.error, var.ts()))
proto = None
if proto == "udp":
try:
print("{} {} Starting UDP SIP deamon on Port {}".format(
var.info, var.ts(), var.udp_port))
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("0.0.0.0", port))
except:
print("{} {} An error occurred with UDP SIP deamon".format(
var.error, var.ts()))
proto = None
if proto == "tls":
try:
print("{} {} Starting TLS SIP deamon on Port {}".format(
var.info, var.ts(), var.tls_port))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLS,
keyfile=var.key_path, certfile=var.cert_path)
s.bind(("0.0.0.0", port))
s.listen()
except:
print("{} {} An error occurred with TLS SIP deamon".format(
var.error,
var.ts()))
proto = None
while True:
if proto == "tcp" or proto == "tls":
try:
connection, client_address = s.accept()
except:
connection = None
pass
if connection:
session = threading.Thread(
target=tcp_session,
args=(connection, client_address, proto))
session.deamon = True
session.start()
elif proto == "udp":
connection, client_address = s.recvfrom(1024)
data = connection
logger.log(client_address[0])
payload = handler.handler(client_address, data, proto)
if payload:
s.sendto(payload, client_address)
else:
print("{} {} Stopping deamon".format(var.error, var.ts()))
break
def tcp_session(connection, client_address, proto):
try:
while True:
try:
data = connection.recv(1024)
except:
break
if not data:
break
logger.log(client_address[0])
payload = handler.handler(client_address, data, proto)
if payload:
connection.send(payload)
finally:
connection.close()
def start_server(proto, port):
port = int(port)
t = threading.Thread(target=deamon, args=(proto, port,))
t.deamon = True
t.start()
def init():
print("{} {} Inititalize SIruP".format(var.info, var.ts()))
print("{} {} Inititalize database".format(var.info, var.ts()))
try:
logger.db_init()
except:
print("{} {} Database error".format(var.error, var.ts()))
sys.exit(1)
if var.udp_enable == "True":
start_server("udp", var.udp_port)
if var.tcp_enable == "True":
start_server("tcp", var.tcp_port)
if var.tls_enable == "True":
start_server("tls", var.tls_port)
print("{} {} Inititalization completed".format(var.info, var.ts()))
|
build-all.py | import os
import csv
import shutil
import subprocess
import threading
class RunSubprocess(object):
"""
a generic class to control a subprocess with threads
"""
def __init__(self, cmd):
"""
constructor
"""
self.cmd = cmd
self.process, self.thread = None, None
self.stdout, self.stderr = None, None
def run(self, src, timeout=100):
# move into src directory
cwd = os.getcwd()
os.chdir(src)
def target():
self.process = subprocess.Popen(self.cmd, shell=True, stderr=subprocess.PIPE,
stdout=subprocess.PIPE, universal_newlines=True, bufsize=4096)
self.stdout, self.stderr = self.process.communicate()
self.thread = threading.Thread(target=target)
self.thread.start()
# wait a specified amount of time before terminating
if timeout:
self.thread.join(timeout)
if self.thread.is_alive():
print('The subprocess was auto-terminated due to timeout')
print("...", self.process.poll())
self.process.terminate()
self.thread.join()
os.chdir(cwd)
return self.process.returncode
return None
def terminate(self):
if self.thread.is_alive():
self.process.terminate()
self.thread.join()
def fetch_dirs():
"""
determine the relative paths of necessary directories
"""
dirs = {'config': os.path.join("..", "config"),
'src': os.path.join(".."),
'static': os.path.join("..", "static")}
if not os.path.exists(dirs['config']):
dirs['src'] = os.path.join(".")
dirs['config'] = os.path.join(".", "config")
dirs['static'] = os.path.join(".", "static")
if not os.path.exists(dirs['config']):
raise Exception("cannot find config dir -- check your current working directory")
if not os.path.isdir(dirs['static']):
os.mkdir(dirs['static'])
return (dirs)
def fetch_lesson_status(dirs):
"""
load the config lesson data with some error checking
"""
lesson_config_file = os.path.join(dirs['config'], "lessons.csv")
lesson_status = {}
with open(lesson_config_file) as csvfile:
reader = csv.reader(csvfile)
reader.__next__()
for row in reader:
if row[0] in lesson_status:
raise Exception("A duplicate entry was identified in lesson.csv: '{}'".format(row[0]))
if row[0] not in os.listdir(dirs['src']):
raise Exception("The src for lesson '{}' cannot be found".format(row[0]))
lesson_status[row[0]] = int(row[1])
return (lesson_status)
def build_lesson(lesson, dirs, timeout=20):
"""
build a specific lesson
"""
print("... building {}".format(lesson))
src = os.path.join(dirs['src'], lesson)
target = os.path.join(dirs['static'], lesson)
# clean static dir
if os.path.isdir(target):
print("...... removing old")
shutil.rmtree(target)
# run subprocess
cmd = "make clean"
sp_clean = RunSubprocess(cmd)
return_code = sp_clean.run(src, timeout=timeout)
cmd = "make html"
sp_build = RunSubprocess(cmd)
return_code = sp_build.run(src, timeout=timeout)
if return_code != 0:
raise Exception("build failed\n", sp_build.stderr)
else:
print("...... build successful")
shutil.copytree(os.path.join(src, "_build", "html"), target)
def build_all(lesson_status, dirs):
"""
build all lessons
"""
for lesson, status in lesson_status.items():
if status > 1:
build_lesson(lesson, dirs)
print("all lessons built")
if __name__ == "__main__":
dirs = fetch_dirs()
lesson_status = fetch_lesson_status(dirs)
build_all(lesson_status, dirs)
|
conftest.py | # pylint: skip-file
import pytest
import shlex
import os
import py.path
import sys
import tempfile
import textwrap
import subprocess
import traceback
from gitrevise.odb import Repository
from contextlib import contextmanager
from threading import Thread, Event
from http.server import HTTPServer, BaseHTTPRequestHandler
import dummy_editor
@pytest.fixture(autouse=True)
def hermetic_seal(tmp_path_factory, monkeypatch):
# Lock down user git configuration
home = tmp_path_factory.mktemp("home")
xdg_config_home = home / ".config"
monkeypatch.setenv("HOME", str(home))
monkeypatch.setenv("XDG_CONFIG_HOME", str(xdg_config_home))
monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "true")
# Lock down commit/authoring time
monkeypatch.setenv("GIT_AUTHOR_DATE", "1500000000 -0500")
monkeypatch.setenv("GIT_COMMITTER_DATE", "1500000000 -0500")
# Install known configuration
gitconfig = home / ".gitconfig"
gitconfig.write_bytes(
textwrap.dedent(
"""\
[core]
eol = lf
autocrlf = input
[user]
email = test@example.com
name = Test User
"""
).encode()
)
# If we are not expecting an editor to be launched, abort immediately.
# (The `false` command always exits with failure).
# This is overridden in editor_main.
monkeypatch.setenv("GIT_EDITOR", "false")
# Switch into a test workdir, and init our repo
workdir = tmp_path_factory.mktemp("workdir")
monkeypatch.chdir(workdir)
bash("git init -q")
@pytest.fixture
def repo(hermetic_seal):
with Repository() as repo:
yield repo
@pytest.fixture
def short_tmpdir():
with tempfile.TemporaryDirectory() as tdir:
yield py.path.local(tdir)
@contextmanager
def in_parallel(func, *args, **kwargs):
class HelperThread(Thread):
exception = None
def run(self):
try:
func(*args, **kwargs)
except Exception as exc:
traceback.print_exc()
self.exception = exc
raise
thread = HelperThread()
thread.start()
try:
yield
finally:
thread.join()
if thread.exception:
raise thread.exception
def bash(command):
# Use a custom environment for bash commands so commits with those commands
# have unique names and emails.
env = dict(
os.environ,
GIT_AUTHOR_NAME="Bash Author",
GIT_AUTHOR_EMAIL="bash_author@example.com",
GIT_COMMITTER_NAME="Bash Committer",
GIT_COMMITTER_EMAIL="bash_committer@example.com",
)
subprocess.run(["bash", "-ec", textwrap.dedent(command)], check=True, env=env)
def changeline(path, lineno, newline):
with open(path, "rb") as f:
lines = f.readlines()
lines[lineno] = newline
with open(path, "wb") as f:
f.write(b"".join(lines))
# Run the main entry point for git-revise in a subprocess.
def main(args, **kwargs):
kwargs.setdefault("check", True)
cmd = [sys.executable, "-m", "gitrevise", *args]
print("Running", cmd, kwargs)
return subprocess.run(cmd, **kwargs)
@contextmanager
def editor_main(args, **kwargs):
with pytest.MonkeyPatch().context() as m, Editor() as ed:
editor_cmd = " ".join(
shlex.quote(p)
for p in (
sys.executable,
dummy_editor.__file__,
"http://{0}:{1}/".format(*ed.server_address[:2]),
)
)
m.setenv("GIT_EDITOR", editor_cmd)
with in_parallel(main, args, **kwargs):
yield ed
class EditorFile(BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
self.response_ready = Event()
self.indata = None
self.outdata = None
super().__init__(*args, **kwargs)
def do_POST(self):
length = int(self.headers.get("content-length"))
self.indata = self.rfile.read(length)
self.outdata = b""
# The request is ready, tell our server, and wait for a reply.
assert self.server.current is None
self.server.current = self
try:
self.server.request_ready.set()
if not self.response_ready.wait(timeout=self.server.timeout):
raise Exception("timed out waiting for reply")
finally:
self.server.current = None
def send_editor_reply(self, status, data):
assert not self.response_ready.is_set(), "already replied?"
self.send_response(status)
self.send_header("content-length", len(data))
self.end_headers()
self.wfile.write(data)
self.response_ready.set()
# Ensure the handle thread has shut down
self.server.handle_thread.join()
self.server.handle_thread = None
assert self.server.current is None
def startswith(self, text):
return self.indata.startswith(text)
def startswith_dedent(self, text):
return self.startswith(textwrap.dedent(text).encode())
def equals(self, text):
return self.indata == text
def equals_dedent(self, text):
return self.equals(textwrap.dedent(text).encode())
def replace_dedent(self, text):
if isinstance(text, str):
text = textwrap.dedent(text).encode()
self.outdata = text
def __enter__(self):
return self
def __exit__(self, etype, evalue, tb):
if etype is None:
self.send_editor_reply(200, self.outdata)
else:
exc = "".join(traceback.format_exception(etype, evalue, tb)).encode()
try:
self.send_editor_reply(500, exc)
except:
pass
def __repr__(self):
return f"<EditorFile {self.indata!r}>"
class Editor(HTTPServer):
def __init__(self):
# Bind to a randomly-allocated free port.
super().__init__(("127.0.0.1", 0), EditorFile)
self.request_ready = Event()
self.handle_thread = None
self.current = None
self.timeout = 10
def next_file(self):
assert self.handle_thread is None
assert self.current is None
# Spawn a thread to handle the single request.
self.request_ready.clear()
self.handle_thread = Thread(target=self.handle_request)
self.handle_thread.start()
if not self.request_ready.wait(timeout=self.timeout):
raise Exception("timeout while waiting for request")
# Return the request we received and were notified about.
assert self.current
return self.current
def is_idle(self):
return self.handle_thread is None and self.current is None
def __enter__(self):
return self
def __exit__(self, etype, value, tb):
try:
# Only assert if we're not already raising an exception.
if etype is None:
assert self.is_idle()
finally:
self.server_close()
if self.current:
self.current.send_editor_reply(500, b"editor server was shut down")
|
myBlockChain.py | import hashlib
import time
import csv
import random
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import json
import re
from urllib.parse import parse_qs
from urllib.parse import urlparse
import threading
import cgi
import uuid
from tempfile import NamedTemporaryFile
import shutil
import requests # for sending new block to other nodes
# 20190605 /(YuRim Kim, HaeRi Kim, JongSun Park, BohKuk Suh , HyeongSeob Lee, JinWoo Song)
from multiprocessing import Process, Lock # for using Lock method(acquire(), release())
# for Put Lock objects into variables(lock)
lock = Lock()
PORT_NUMBER = 8666
g_txFileName = "txData.csv"
g_bcFileName = "blockchain.csv"
g_nodelstFileName = "nodelst.csv"
g_receiveNewBlock = "/node/receiveNewBlock"
g_difficulty = 5
g_maximumTry = 100
g_nodeList = {'127.0.0.1':'8668'} # trusted server list, should be checked manually
class Block:
def __init__(self, index, previousHash, timestamp, data, currentHash, proof ):
self.index = index # 블록의 높이
self.previousHash = previousHash # 이전 블록의 해시값(이전 블록의 연결고리, 스냅샷)
self.timestamp = timestamp # 블록 생성 시점
self.data = data # 거래 데이터
self.currentHash = currentHash # 현재 블록의 해시값
self.proof = proof # 작업 증명값(채굴 횟수)
def toJSON(self):
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)
class txData:
def __init__(self, commitYN, sender, amount, receiver, uuid):
self.commitYN = commitYN # 블록 포함 여부(확증 여부)
self.sender = sender # 송신자
self.amount = amount # 금액
self.receiver = receiver # 수신자
self.uuid = uuid # 거래 고유 번호
def generateGenesisBlock():
print("generateGenesisBlock is called")
timestamp = time.time()
print("time.time() => %f \n" % timestamp)
tempHash = calculateHash(0, '0', timestamp, "Genesis Block", 0)
print(tempHash)
return Block(0, '0', timestamp, "Genesis Block", tempHash,0)
def calculateHash(index, previousHash, timestamp, data, proof):
value = str(index) + str(previousHash) + str(timestamp) + str(data) + str(proof)
sha = hashlib.sha256(value.encode('utf-8'))
return str(sha.hexdigest())
def calculateHashForBlock(block):
return calculateHash(block.index, block.previousHash, block.timestamp, block.data, block.proof)
def getLatestBlock(blockchain):
return blockchain[len(blockchain) - 1]
# 블록 채굴
def generateNextBlock(blockchain, blockData, timestamp, proof):
previousBlock = getLatestBlock(blockchain) # 블록체인의 가장 마지막 블록정보를 조회
nextIndex = int(previousBlock.index) + 1 # 채굴할 블록의 번호는 마지막 블록 번호 + 1
nextTimestamp = timestamp
nextHash = calculateHash(nextIndex, previousBlock.currentHash, nextTimestamp, blockData, proof)
# index, previousHash, timestamp, data, currentHash, proof
return Block(nextIndex, previousBlock.currentHash, nextTimestamp, blockData, nextHash,proof)
# 20190605 / (YuRim Kim, HaeRi Kim, JongSun Park, BohKuk Suh , HyeongSeob Lee, JinWoo Song)
# /* WriteBlockchain function Update */
# If the 'blockchain.csv' file is already open, make it inaccessible via lock.acquire()
# After executing the desired operation, changed to release the lock.(lock.release())
# Reason for time.sleep ():
# prevents server overload due to repeated error message output and gives 3 seconds of delay to allow time for other users to wait without opening file while editing and saving csv file.
# 2_2 블록체인 조회 및 추가
def writeBlockchain(blockchain):
blockchainList = []
for block in blockchain:
blockList = [block.index, block.previousHash, str(block.timestamp), block.data, block.currentHash,block.proof ]
blockchainList.append(blockList)
#[STARAT] check current db(csv) if broadcasted block data has already been updated
try:
with open(g_bcFileName, 'r', newline='') as file:
blockReader = csv.reader(file)
last_line_number = row_count(g_bcFileName)
for line in blockReader:
if blockReader.line_num == last_line_number:
lastBlock = Block(line[0], line[1], line[2], line[3], line[4], line[5])
if int(lastBlock.index) + 1 != int(blockchainList[-1][0]):
print("index sequence mismatch")
if int(lastBlock.index) == int(blockchainList[-1][0]):
print("db(csv) has already been updated")
return
except:
print("file open error in check current db(csv) \n or maybe there's some other reason")
pass
#return
# [END] check current db(csv)
openFile = False
while not openFile:
if blockchainList != []:
try:
lock.acquire()
with open(g_bcFileName, "w", newline='') as file:
writer = csv.writer(file)
writer.writerows(blockchainList)
blockchainList.clear()
print("write ok")
openFile = True
for block in blockchain:
updateTx(block)
print('Blockchain written to blockchain.csv.')
print('Broadcasting new block to other nodes')
broadcastNewBlock(blockchain)
lock.release()
except:
time.sleep(3)
print("writeBlockchain file open error")
lock.release()
else:
print("Blockchain is empty")
# 블록체인 조회 및 추가
def readBlockchain(blockchainFilePath, mode = 'internal'):
print("readBlockchain")
importedBlockchain = []
try:
with open(blockchainFilePath, 'r', newline='') as file: # 기존 블록체인 조회
blockReader = csv.reader(file)
for line in blockReader: # 파일 조회하여 리스트형 변수에 담기
block = Block(line[0], line[1], line[2], line[3], line[4], line[5])
importedBlockchain.append(block)
print("Pulling blockchain from csv...")
return importedBlockchain
except: # 파일이 없거나 읽기 오류 발생한 경우 예외 처리
if mode == 'internal' :
blockchain = generateGenesisBlock()
importedBlockchain.append(blockchain)
writeBlockchain(importedBlockchain)
return importedBlockchain
else :
return None
def updateTx(blockData) :
# 정규 표현식을 이용하여 거래 번호를 찾는다.
phrase = re.compile(r"\w+[-]\w+[-]\w+[-]\w+[-]\w+") # [6b3b3c1e-858d-4e3b-b012-8faac98b49a8]UserID hwang sent 333 bitTokens to UserID kim.
matchList = phrase.findall(blockData.data)
if len(matchList) == 0 : # 매칭되는 거래 고유 번호가 없는 경우
print ("No Match Found! " + str(blockData.data) + "block idx: " + str(blockData.index))
return
tempfile = NamedTemporaryFile(mode='w', newline='', delete=False)
with open(g_txFileName, 'r') as csvfile, tempfile:
reader = csv.reader(csvfile)
writer = csv.writer(tempfile)
for row in reader:
# 거래 데이터 중 블록에 확증된 거래 번호와 일치하는 경우
if row[4] in matchList:
print('updating row : ', row[4])
row[0] = 1 # 해당 거래의 확증 여부 값을 1로 설정
writer.writerow(row)
# 기존 거래 데이터 파일을 거래 번호를 업데이트한 파일로 교체
shutil.move(tempfile.name, g_txFileName)
csvfile.close()
tempfile.close()
print('txData updated')
# 20190605 /(YuRim Kim, HaeRi Kim, JongSun Park, BohKuk Suh , HyeongSeob Lee, JinWoo Song)
# /* writeTx function Update */
# If the 'txData.csv' file is already open, make it inaccessible via lock.acquire()
# After executing the desired operation, changed to release the lock.(lock.release())
# Reason for time.sleep ():
# prevents server overload due to repeated error message output and gives 3 seconds of delay to allow time for other users to wait without opening file while editing and saving csv file.
# Removed temp files to reduce memory usage and increase work efficiency.
def writeTx(txRawData):
print(g_txFileName)
txDataList = []
txOriginalList = []
for txDatum in txRawData:
txList = [txDatum.commitYN, txDatum.sender, txDatum.amount, txDatum.receiver, txDatum.uuid]
txDataList.append(txList)
try:
with open(g_txFileName, 'r', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
txOriginalList.append(row)
openWriteTx = False
while not openWriteTx:
lock.acquire()
try:
print("NewTxData lock.acquire")
with open(g_txFileName, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
# adding new tx
writer.writerows(txOriginalList)
writer.writerows(txDataList)
print("writeTx write ok")
csvfile.close()
openWriteTx = True
lock.release()
except Exception as e:
print(e)
time.sleep(3)
print("file open error")
lock.release()
except:
# this is 1st time of creating txFile
try:
with open(g_txFileName, "w", newline='') as file:
writer = csv.writer(file)
writer.writerows(txDataList)
except:
return 0
return 1
print('txData written to txData.csv.')
def readTx(txFilePath):
print("readTx")
importedTx = []
try:
with open(txFilePath, 'r', newline='') as file:
txReader = csv.reader(file)
for row in txReader:
if row[0] == '0': # find unmined txData # 채굴 되지 않은 거래 데이터를 조회
line = txData(row[0],row[1],row[2],row[3],row[4])
importedTx.append(line)
print("Pulling txData from csv...")
return importedTx
except:
return []
def getTxData():
strTxData = ''
importedTx = readTx(g_txFileName)
if len(importedTx) > 0 :
for i in importedTx:
print(i.__dict__)
transaction = "["+ i.uuid + "]" "UserID " + i.sender + " sent " + i.amount + " bitTokens to UserID " + i.receiver + ". " #
print(transaction)
strTxData += transaction
return strTxData
def mineNewBlock(difficulty=g_difficulty, blockchainPath=g_bcFileName):
blockchain = readBlockchain(blockchainPath) # 최신 블록체인 조회
strTxData = getTxData() # 거래 데이터 조회
if strTxData == '' : # 거래 데이터가 없을 경우 리턴
print('No TxData Found. Mining aborted')
return
timestamp = time.time()
proof = 0
newBlockFound = False
print('Mining a block...')
while not newBlockFound: # 작업 증명
newBlockAttempt = generateNextBlock(blockchain, strTxData, timestamp, proof)
if newBlockAttempt.currentHash[0:difficulty] == '0' * difficulty: # 난이도 만족 여부
stopTime = time.time()
timer = stopTime - timestamp
print('New block found with proof', proof, 'in', round(timer, 2), 'seconds.')
newBlockFound = True # 난이도 만족시 반복문 종료
else:
proof += 1 # 난이도 불충족시 작업 증명 횟수 1 증가
blockchain.append(newBlockAttempt)
writeBlockchain(blockchain) # 난이도를 만족하는 블록 채굴시 블록체인에 추가
def mine():
mineNewBlock()
def isSameBlock(block1, block2):
if str(block1.index) != str(block2.index):
return False
elif str(block1.previousHash) != str(block2.previousHash):
return False
elif str(block1.timestamp) != str(block2.timestamp):
return False
elif str(block1.data) != str(block2.data):
return False
elif str(block1.currentHash) != str(block2.currentHash):
return False
elif str(block1.proof) != str(block2.proof):
return False
return True
def isValidNewBlock(newBlock, previousBlock):
if int(previousBlock.index) + 1 != int(newBlock.index):
print('Indices Do Not Match Up')
return False
elif previousBlock.currentHash != newBlock.previousHash:
print("Previous hash does not match")
return False
elif calculateHashForBlock(newBlock) != newBlock.currentHash:
print("Hash is invalid")
return False
elif newBlock.currentHash[0:g_difficulty] != '0' * g_difficulty:
print("Hash difficulty is invalid")
return False
return True
def newtx(txToMining):
newtxData = []
# transform given data to txData object
for line in txToMining:
tx = txData(0, line['sender'], line['amount'], line['receiver'], uuid.uuid4())
newtxData.append(tx)
# limitation check : max 5 tx
if len(newtxData) > 5 :
print('number of requested tx exceeds limitation')
return -1
if writeTx(newtxData) == 0:
print("file write error on txData")
return -2
return 1
def isValidChain(bcToValidate):
genesisBlock = []
bcToValidateForBlock = []
# Read GenesisBlock
try:
with open(g_bcFileName, 'r', newline='') as file:
blockReader = csv.reader(file)
for line in blockReader:
block = Block(line[0], line[1], line[2], line[3], line[4], line[5])
genesisBlock.append(block)
# break
except:
print("file open error in isValidChain")
return False
# transform given data to Block object
for line in bcToValidate:
# print(type(line))
# index, previousHash, timestamp, data, currentHash, proof
block = Block(line['index'], line['previousHash'], line['timestamp'], line['data'], line['currentHash'], line['proof'])
bcToValidateForBlock.append(block)
#if it fails to read block data from db(csv)
if not genesisBlock:
print("fail to read genesisBlock")
return False
# compare the given data with genesisBlock
if not isSameBlock(bcToValidateForBlock[0], genesisBlock[0]):
print('Genesis Block Incorrect')
return False
# tempBlocks = [bcToValidateForBlock[0]]
# for i in range(1, len(bcToValidateForBlock)):
# if isValidNewBlock(bcToValidateForBlock[i], tempBlocks[i - 1]):
# tempBlocks.append(bcToValidateForBlock[i])
# else:
# return False
for i in range(0, len(bcToValidateForBlock)):
if isSameBlock(genesisBlock[i], bcToValidateForBlock[i]) == False:
return False
return True
# 20190605 / (YuRim Kim, HaeRi Kim, JongSun Park, BohKuk Suh , HyeongSeob Lee, JinWoo Song)
# /* addNode function Update */
# If the 'nodeList.csv' file is already open, make it inaccessible via lock.acquire()
# After executing the desired operation, changed to release the lock.(lock.release())
# Reason for time.sleep ():
# prevents server overload due to repeated error message output and gives 3 seconds of delay to allow time for other users to wait without opening file while editing and saving csv file.
# Removed temp files to reduce memory usage and increase work efficiency.
def addNode(queryStr):
# save
previousList = []
nodeList = []
nodeList.append([queryStr[0],queryStr[1],0]) # ip, port, # of connection fail
try:
with open(g_nodelstFileName, 'r', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if row:
if row[0] == queryStr[0] and row[1] == queryStr[1]:
print("requested node is already exists")
csvfile.close()
nodeList.clear()
return -1
else:
previousList.append(row)
openFile3 = False
while not openFile3:
lock.acquire()
try:
with open(g_nodelstFileName, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(nodeList)
writer.writerows(previousList)
csvfile.close()
nodeList.clear()
lock.release()
print('new node written to nodelist.csv.')
return 1
except Exception as ex:
print(ex)
time.sleep(3)
print("file open error")
lock.release()
except:
# this is 1st time of creating node list
try:
with open(g_nodelstFileName, "w", newline='') as file:
writer = csv.writer(file)
writer.writerows(nodeList)
nodeList.clear()
print('new node written to nodelist.csv.')
return 1
except Exception as ex:
print(ex)
return 0
def readNodes(filePath):
print("read Nodes")
importedNodes = []
try:
with open(filePath, 'r', newline='') as file:
txReader = csv.reader(file)
for row in txReader:
line = [row[0],row[1]]
importedNodes.append(line)
print("Pulling txData from csv...")
return importedNodes
except:
return []
def broadcastNewBlock(blockchain):
#newBlock = getLatestBlock(blockchain) # get the latest block
importedNodes = readNodes(g_nodelstFileName) # get server node ip and port
reqHeader = {'Content-Type': 'application/json; charset=utf-8'}
reqBody = []
for i in blockchain:
reqBody.append(i.__dict__)
if len(importedNodes) > 0 :
for node in importedNodes:
try:
URL = "http://" + node[0] + ":" + node[1] + g_receiveNewBlock # http://ip:port/node/receiveNewBlock
res = requests.post(URL, headers=reqHeader, data=json.dumps(reqBody))
if res.status_code == 200:
print(URL + " sent ok.")
print("Response Message " + res.text)
else:
print(URL + " responding error " + res.status_code)
except:
print(URL + " is not responding.")
# write responding results
tempfile = NamedTemporaryFile(mode='w', newline='', delete=False)
try:
with open(g_nodelstFileName, 'r', newline='') as csvfile, tempfile:
reader = csv.reader(csvfile)
writer = csv.writer(tempfile)
for row in reader:
if row:
if row[0] == node[0] and row[1] ==node[1]:
print("connection failed "+row[0]+":"+row[1]+", number of fail "+row[2])
tmp = row[2]
# too much fail, delete node
if int(tmp) > g_maximumTry:
print(row[0]+":"+row[1]+" deleted from node list because of exceeding the request limit")
else:
row[2] = int(tmp) + 1
writer.writerow(row)
else:
writer.writerow(row)
shutil.move(tempfile.name, g_nodelstFileName)
csvfile.close()
tempfile.close()
except:
print("caught exception while updating node list")
def row_count(filename):
try:
with open(filename) as in_file:
return sum(1 for _ in in_file)
except:
return 0
def compareMerge(bcDict):
heldBlock = []
bcToValidateForBlock = []
# Read GenesisBlock
try:
with open(g_bcFileName, 'r', newline='') as file:
blockReader = csv.reader(file)
#last_line_number = row_count(g_bcFileName)
for line in blockReader:
block = Block(line[0], line[1], line[2], line[3], line[4], line[5])
heldBlock.append(block)
#if blockReader.line_num == 1:
# block = Block(line[0], line[1], line[2], line[3], line[4], line[5])
# heldBlock.append(block)
#elif blockReader.line_num == last_line_number:
# block = Block(line[0], line[1], line[2], line[3], line[4], line[5])
# heldBlock.append(block)
except:
print("file open error in compareMerge or No database exists")
print("call initSvr if this server has just installed")
return -1
#if it fails to read block data from db(csv)
if len(heldBlock) == 0 :
print("fail to read")
return -2
# transform given data to Block object
for line in bcDict:
# print(type(line))
# index, previousHash, timestamp, data, currentHash, proof
block = Block(line['index'], line['previousHash'], line['timestamp'], line['data'], line['currentHash'], line['proof'])
bcToValidateForBlock.append(block)
# compare the given data with genesisBlock
if not isSameBlock(bcToValidateForBlock[0], heldBlock[0]):
print('Genesis Block Incorrect')
return -1
# check if broadcasted new block,1 ahead than > last held block
if isValidNewBlock(bcToValidateForBlock[-1],heldBlock[-1]) == False:
# latest block == broadcasted last block
if isSameBlock(heldBlock[-1], bcToValidateForBlock[-1]) == True:
print('latest block == broadcasted last block, already updated')
return 2
# select longest chain
elif len(bcToValidateForBlock) > len(heldBlock):
# validation
if isSameBlock(heldBlock[0],bcToValidateForBlock[0]) == False:
print("Block Information Incorrect #1")
return -1
tempBlocks = [bcToValidateForBlock[0]]
for i in range(1, len(bcToValidateForBlock)):
if isValidNewBlock(bcToValidateForBlock[i], tempBlocks[i - 1]):
tempBlocks.append(bcToValidateForBlock[i])
else:
return -1
# [START] save it to csv
# 20190605 / (kyuin Park, jiweon Lim, sunghoon Oh, sol Han )
# TODO: append 정상여부 검증 필요
blockchainList = []
lengthGap = len(bcToValidateForBlock) - len(heldBlock) # 받을 블록과 내 블록의 길이 차이
for block in bcToValidateForBlock[-lengthGap:]:
blockList = [block.index, block.previousHash, str(block.timestamp), block.data,
block.currentHash, block.proof]
blockchainList.append(blockList) # blockchainList에 타노드의 block을 list 형태로 담아줌
with open(g_bcFileName, "a", newline='') as file:
writer = csv.writer(file)
writer.writerows(blockchainList)
# [END] save it to csv
return 1
elif len(bcToValidateForBlock) < len(heldBlock):
# validation
#for i in range(0,len(bcToValidateForBlock)):
# if isSameBlock(heldBlock[i], bcToValidateForBlock[i]) == False:
# print("Block Information Incorrect #1")
# return -1
tempBlocks = [bcToValidateForBlock[0]]
for i in range(1, len(bcToValidateForBlock)):
if isValidNewBlock(bcToValidateForBlock[i], tempBlocks[i - 1]):
tempBlocks.append(bcToValidateForBlock[i])
else:
return -1
print("We have a longer chain")
return 3
else:
print("Block Information Incorrect #2")
return -1
else: # very normal case (ex> we have index 100 and receive index 101 ...)
tempBlocks = [bcToValidateForBlock[0]]
for i in range(1, len(bcToValidateForBlock)):
if isValidNewBlock(bcToValidateForBlock[i], tempBlocks[i - 1]):
tempBlocks.append(bcToValidateForBlock[i])
else:
print("Block Information Incorrect #2 "+tempBlocks.__dict__)
return -1
print("new block good")
# validation
for i in range(0, len(heldBlock)):
if isSameBlock(heldBlock[i], bcToValidateForBlock[i]) == False:
print("Block Information Incorrect #1")
return -1
# [START] save it to csv
blockchainList = []
for block in bcToValidateForBlock:
blockList = [block.index, block.previousHash, str(block.timestamp), block.data, block.currentHash, block.proof]
blockchainList.append(blockList)
with open(g_bcFileName, "w", newline='') as file:
writer = csv.writer(file)
writer.writerows(blockchainList)
# [END] save it to csv
return 1
def initSvr():
print("init Server")
# 1. check if we have a node list file
last_line_number = row_count(g_nodelstFileName)
# if we don't have, let's request node list
if last_line_number == 0:
# get nodes...
for key, value in g_nodeList.items():
URL = 'http://'+key+':'+value+'/node/getNode'
try:
res = requests.get(URL)
except requests.exceptions.ConnectionError:
continue
if res.status_code == 200 :
print(res.text)
tmpNodeLists = json.loads(res.text)
for node in tmpNodeLists:
addNode(node)
# 2. check if we have a blockchain data file
last_line_number = row_count(g_bcFileName)
blockchainList=[]
if last_line_number == 0:
# get Block Data...
for key, value in g_nodeList.items():
URL = 'http://'+key+':'+value+'/block/getBlockData'
try:
res = requests.get(URL)
except requests.exceptions.ConnectionError:
continue
if res.status_code == 200 :
print(res.text)
tmpbcData = json.loads(res.text)
for line in tmpbcData:
# print(type(line))
# index, previousHash, timestamp, data, currentHash, proof
block = [line['index'], line['previousHash'], line['timestamp'], line['data'],line['currentHash'], line['proof']]
blockchainList.append(block)
try:
with open(g_bcFileName, "w", newline='') as file:
writer = csv.writer(file)
writer.writerows(blockchainList)
except Exception as e:
print("file write error in initSvr() "+e)
return 1
# This class will handle any incoming request from
# a browser
class myHandler(BaseHTTPRequestHandler):
#def __init__(self, request, client_address, server):
# BaseHTTPRequestHandler.__init__(self, request, client_address, server)
# Handler for the GET requests
def do_GET(self):
data = [] # response json data
if None != re.search('/block/*', self.path):
if None != re.search('/block/getBlockData', self.path):
# 20190605 / (kyuin Park, jiweon Lim, sunghoon Oh, sol Han )
# TODO : http://localhost:8666/block/getBlockData?from=1&end=10 -> from, end 문자열 검사
# 블록체인 갯수와 맞지 않는 경우 예외 처리 (예> 블록이 4개 존재, 요청은 10개)
# 블록 요청 from에 음수값, 0값 예외 처리
queryString = urlparse(self.path).query.split('&')
startPoint = int(queryString[0].split('=')[1]) - 1
endPoint = int(queryString[1].split('=')[1])
try:
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
block = readBlockchain(g_bcFileName, mode = 'external')
if block == None:
print("No Block Exists")
data.append("no data exists")
else:
for i in range(startPoint, endPoint):
print(block[i].__dict__)
data.append(block[i].__dict__)
except:
self.send_response(500)
self.send_header('Content-type', 'application/json')
self.end_headers()
data.append("error")
finally:
self.wfile.write(bytes(json.dumps(data, sort_keys=True, indent=4), "utf-8"))
elif None != re.search('/block/generateBlock', self.path):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
t = threading.Thread(target=mine) # 쓰레드로 mine 함수를 호출
t.start() # 쓰레드 시작
data.append("{mining is underway:check later by calling /block/getBlockData}")
self.wfile.write(bytes(json.dumps(data, sort_keys=True, indent=4), "utf-8"))
else:
self.send_response(404)
self.send_header('Content-type', 'application/json')
self.end_headers()
data.append("{info:no such api}")
self.wfile.write(bytes(json.dumps(data, sort_keys=True, indent=4), "utf-8"))
elif None != re.search('/node/*', self.path):
if None != re.search('/node/addNode', self.path):
queryStr = urlparse(self.path).query.split(':')
print("client ip : "+self.client_address[0]+" query ip : "+queryStr[0])
if self.client_address[0] != queryStr[0]:
self.send_response(500)
self.send_header('Content-type', 'application/json')
self.end_headers()
data.append("your ip address doesn't match with the requested parameter")
else:
try:
res = addNode(queryStr)
except:
pass
finally:
if res == 1:
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
importedNodes = readNodes(g_nodelstFileName)
data =importedNodes
print("node added okay")
elif res == 0 :
self.send_response(500)
self.send_header('Content-type', 'application/json')
self.end_headers()
data.append("caught exception while saving")
elif res == -1 :
self.send_response(500)
self.send_header('Content-type', 'application/json')
self.end_headers()
importedNodes = readNodes(g_nodelstFileName)
data = importedNodes
data.append("requested node is already exists")
self.wfile.write(bytes(json.dumps(data, sort_keys=True, indent=4), "utf-8"))
elif None != re.search('/node/getNode', self.path):
try:
importedNodes = readNodes(g_nodelstFileName)
data = importedNodes
except:
data.append("error")
self.send_response(500)
self.send_header('Content-type', 'application/json')
self.end_headers()
else:
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
finally:
self.wfile.write(bytes(json.dumps(data, sort_keys=True, indent=4), "utf-8"))
else:
self.send_response(404)
self.send_header('Content-type', 'application/json')
self.end_headers()
# ref : https://mafayyaz.wordpress.com/2013/02/08/writing-simple-http-server-in-python-with-rest-and-json/
def do_POST(self):
if None != re.search('/block/*', self.path):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
if None != re.search('/block/validateBlock/*', self.path):
ctype, pdict = cgi.parse_header(self.headers['content-type'])
#print(ctype) #print(pdict)
if ctype == 'application/json':
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
receivedData = post_data.decode('utf-8')
print(type(receivedData))
tempDict = json.loads(receivedData) # load your str into a list #print(type(tempDict))
if isValidChain(tempDict) == True :
tempDict.append("validationResult:normal")
self.wfile.write(bytes(json.dumps(tempDict), "utf-8"))
else :
tempDict.append("validationResult:abnormal")
self.wfile.write(bytes(json.dumps(tempDict), "utf-8"))
elif None != re.search('/block/newtx', self.path):
ctype, pdict = cgi.parse_header(self.headers['content-type'])
if ctype == 'application/json':
content_length = int(self.headers['Content-Length']) # 본문의 크기 확인
post_data = self.rfile.read(content_length) # 본문 읽어 들이기
receivedData = post_data.decode('utf-8') # utf-8로 디코딩
print(type(receivedData)) # 딕셔너리 형식으로 자료형 변환
tempDict = json.loads(receivedData) # 거래 데이터 추가
res = newtx(tempDict) # 거래 데이터 정상 추가된 경우
if res == 1 :
tempDict.append("accepted : it will be mined later")
self.wfile.write(bytes(json.dumps(tempDict), "utf-8"))
elif res == -1 :
tempDict.append("declined : number of request txData exceeds limitation")
self.wfile.write(bytes(json.dumps(tempDict), "utf-8"))
elif res == -2 :
tempDict.append("declined : error on data read or write")
self.wfile.write(bytes(json.dumps(tempDict), "utf-8"))
else :
tempDict.append("error : requested data is abnormal")
self.wfile.write(bytes(json.dumps(tempDict), "utf-8"))
elif None != re.search('/node/*', self.path):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
if None != re.search(g_receiveNewBlock, self.path): # /node/receiveNewBlock
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
receivedData = post_data.decode('utf-8')
tempDict = json.loads(receivedData) # load your str into a list
print(tempDict)
res = compareMerge(tempDict)
if res == -1: # internal error
tempDict.append("internal server error")
elif res == -2 : # block chain info incorrect
tempDict.append("block chain info incorrect")
elif res == 1: #normal
tempDict.append("accepted")
elif res == 2: # identical
tempDict.append("already updated")
elif res == 3: # we have a longer chain
tempDict.append("we have a longer chain")
self.wfile.write(bytes(json.dumps(tempDict), "utf-8"))
else:
self.send_response(404)
self.send_header('Content-Type', 'application/json')
self.end_headers()
return
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
try:
# Create a web server and define the handler to manage the
# incoming request
# server = HTTPServer(('', PORT_NUMBER), myHandler)
server = ThreadedHTTPServer(('', PORT_NUMBER), myHandler)
print('Started httpserver on port ', PORT_NUMBER)
initSvr()
# Wait forever for incoming http requests
server.serve_forever()
except (KeyboardInterrupt, Exception) as e:
print('^C received, shutting down the web server')
print(e)
server.socket.close()
|
load.py | # coding=utf-8
"""The actual loading of SNOMED data into the database"""
from __future__ import absolute_import
import multiprocessing
import os
import shutil
import logging
import contextlib
import wrapt
from sqlalchemy import text
from sil_snomed_server.app import db
from sil_snomed_server.config.config import basedir
from sarge import run
from collections import Iterable
from datetime import datetime
LOGGER = logging.getLogger(__name__)
MULTIPROCESSING_POOL_SIZE = multiprocessing.cpu_count()
def _sqlalchemy_connection():
return db.session.connection().connection
@contextlib.contextmanager
def time_execution(fn):
"""Measure the execution time fn ( a supplied function )"""
try:
start_time = datetime.now()
yield
finally:
secs = (datetime.now() - start_time).total_seconds()
LOGGER.debug('EXECUTED {}, took {}s'.format(fn.func_name, secs))
@wrapt.decorator
def instrument(wrapped, instance, args, kwargs):
"""Central place to do instrumentation e.g log calls, profile runtime"""
with time_execution(wrapped):
return wrapped(*args, **kwargs)
def _strip_first_line(source_file_path):
"""
Discard the header row before loading the data.
Makes a backup file 'source_file_path.bak'.
"""
run("sed -i.bak -e '1d' {}".format(source_file_path))
run("head -1 {}".format(source_file_path))
return source_file_path # Should exist from here
# Exiting from here is a bug
raise Exception('Unable to rewrite %s' % source_file_path)
def _confirm_param_is_an_iterable(param):
"""Used below to enforce the invariant that the param should be a list"""
if not isinstance(param, Iterable):
raise Exception('Expected an iterable')
def _load(table_name, file_path_list, cols):
"""The actual worker method that reads the data into the database"""
_confirm_param_is_an_iterable(file_path_list)
conn = _sqlalchemy_connection()
cursor = conn.cursor()
for file_path in file_path_list:
rewritten_file = _strip_first_line(file_path)
try:
with open(rewritten_file) as rewrite:
cursor.copy_from(
rewrite, table_name, size=32768, columns=cols)
cursor.execute('ANALYZE {};'.format(table_name))
conn.commit()
# Now restore the file (reduces space used by half!)
os.rename(file_path + '.bak', file_path)
except Exception as exception:
os.rename(file_path + '.bak', file_path)
print("Unable to load data from file: {}. Exception: {}".
format(file_path, exception))
def _execute_and_commit(statement, view_name=None):
"""Execute an SQL statement; used to parallelize view refereshes"""
with _sqlalchemy_connection() as conn:
with conn.begin() as trans:
trans.execute(statement)
if view_name:
cur.execute('ANALYZE {};'.format(view_name))
trans.commit()
def execute_map_on_pool(callable_input_map,
process_count=MULTIPROCESSING_POOL_SIZE):
"""The obvious choice ( Pool ) has not been used because it does not play
well with our performance measuring decorator
:param: callable_input_map
"""
processes = [
multiprocessing.Process(target=fn, args=(inp,) if inp is not None else ())
for fn, inp in iter(callable_input_map.items())
]
for p in processes:
p.start()
for p in processes:
p.join()
def load_concepts(file_path_list):
"""Load concepts from RF2 distribution file
:param file_path_list:
"""
_load('curr_concept_f', file_path_list,
['id', 'effective_time', 'active',
'module_id', 'definition_status_id'])
def load_descriptions(file_path_list):
"""Load descriptions from RF2 distribution file
:param file_path_list:
"""
_load('curr_description_f', file_path_list,
['id', 'effective_time', 'active', 'module_id',
'concept_id', 'language_code', 'type_id', 'term',
'case_significance_id'])
def load_relationships(file_path_list):
"""Load relationships from RF2 distribution file
:param file_path_list:
"""
_load('curr_relationship_f', file_path_list,
['id', 'effective_time', 'active', 'module_id',
'source_id', 'destination_id', 'relationship_group', 'type_id',
'characteristic_type_id', 'modifier_id'])
def load_text_definitions(file_path_list):
"""Delegate to the description loading logic
:param file_path_list:
"""
load_descriptions(file_path_list)
def load_simple_reference_sets(file_path_list):
"""Load simple reference sets from RF2 distribution file
:param file_path_list:
"""
_load('curr_simplerefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id'])
def load_ordered_reference_sets(file_path_list):
"""Load ordered reference sets from RF2 distribution file
:param file_path_list:
"""
_load('curr_orderedrefset_full', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', '"order"', 'linked_to_id'])
def load_attribute_value_reference_sets(file_path_list):
"""Load attribute value reference set from RF2 distribution file
:param file_path_list:
"""
_load('curr_attributevaluerefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', 'value_id'])
def load_simple_map_reference_sets(file_path_list):
"""Load simple map reference sets from RF2 distribution file
:param file_path_list:
"""
_load('curr_simplemaprefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', 'map_target'])
def load_complex_map_int_reference_sets(file_path_list):
"""Load complex map reference sets from RF2 distribution files
:param file_path_list:
"""
_load('curr_complexmaprefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', 'map_group', 'map_priority', 'map_rule',
'map_advice', 'map_target', 'correlation_id'])
def load_complex_map_gb_reference_sets(file_path_list):
"""Like for INTernational above, but with an extra map_block column
For United Kingdom SNOMED->OPCS and SNOMED->ICD 10 maps
"""
_load('curr_complexmaprefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', 'map_group', 'map_priority', 'map_rule',
'map_advice', 'map_target', 'correlation_id', 'map_block'])
def load_extended_map_reference_sets(file_path_list):
"""Load extended map reference sets from the RF2 distribution file
:param file_path_list:
"""
_load('curr_extendedmaprefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', 'map_group', 'map_priority', 'map_rule',
'map_advice', 'map_target', 'correlation_id', 'map_category_id'])
def load_language_reference_sets(file_path_list):
"""Load language reference sets from the RF2 distribution file
:param file_path_list:
"""
_load('curr_langrefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', 'acceptability_id'])
def load_query_specification_reference_sets(file_path_list):
"""
Load query specification reference sets from the RF2 distribution file
:param file_path_list:
"""
_load('curr_queryspecificationrefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', 'query'])
def load_annotation_reference_sets(file_path_list):
"""Load annotation reference sets from the RF2 distribution file
:param file_path_list:
"""
_load('curr_annotationrefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', 'annotation'])
def load_association_reference_sets(file_path_list):
"""Load association reference sets from the RF2 distribution file
:param file_path_list:
"""
_load('curr_associationrefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', 'target_component_id'])
def load_module_dependency_reference_sets(file_path_list):
"""Load module dependency reference sets from the RF2 distribution file
:param file_path_list:
"""
_load('curr_moduledependencyrefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', 'source_effective_time',
'target_effective_time'])
def load_description_format_reference_sets(file_path_list):
"""Load description format reference sets from the RF2 distribution file
:param file_path_list:
"""
_load('curr_descriptionformatrefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', 'description_format_id',
'description_length'])
def load_refset_descriptor_reference_sets(file_path_list):
"""Load refset descriptor refsets from the RF2 distribution file
:param file_path_list:
"""
_load('curr_referencesetdescriptorrefset_f', file_path_list,
['id', 'effective_time', 'active', 'module_id', 'refset_id',
'referenced_component_id', 'attribute_description_id',
'attribute_type_id', 'attribute_order'])
def load_description_type_reference_sets(file_path_list):
"""Delegate to the description format reference set loader
:param file_path_list:
"""
load_description_format_reference_sets(file_path_list)
def run_file(filename):
"""
Run sql statements in a file
:param filename of the file with sql statements
:return a list of ResultProxy objects (results from each of
the sql statements being run)
"""
conn = _sqlalchemy_connection()
cursor = conn.cursor()
with open(filename, "r") as query_file:
queries = query_file.read().replace("\n", "").split(";")
queries = [q.strip() for q in queries]
queries = [q for q in queries if q != '']
for query in queries:
print(">> {}".format(query))
cursor.execute(query)
conn.commit()
def make_current_snapshot():
snapshot_script = os.path.join(basedir, 'migrations/sql/snapshot.sql')
run_file(snapshot_script)
def load_release_files(path_dict):
"""Take a dict from discover.py->enumerate_release_files & trigger db load
As an entry point method, it is not "intrumented" for performance
measurement; that would simply make the console output less readable
:param path_dict:
"""
execute_map_on_pool({
load_concepts: path_dict["CONCEPTS"],
load_descriptions: path_dict["DESCRIPTIONS"],
load_relationships: path_dict["RELATIONSHIPS"],
load_text_definitions: path_dict["TEXT_DEFINITIONS"],
load_language_reference_sets: path_dict["LANGUAGE_REFERENCE_SET"],
load_simple_reference_sets: path_dict["SIMPLE_REFERENCE_SET"],
load_ordered_reference_sets: path_dict["ORDERED_REFERENCE_SET"],
load_attribute_value_reference_sets:
path_dict["ATTRIBUTE_VALUE_REFERENCE_SET"],
load_simple_map_reference_sets: path_dict["SIMPLE_MAP_REFERENCE_SET"],
load_complex_map_int_reference_sets:
path_dict["COMPLEX_MAP_INT_REFERENCE_SET"],
load_complex_map_gb_reference_sets:
path_dict["COMPLEX_MAP_GB_REFERENCE_SET"],
load_extended_map_reference_sets:
path_dict["EXTENDED_MAP_REFERENCE_SET"],
load_query_specification_reference_sets:
path_dict["QUERY_SPECIFICATION_REFERENCE_SET"],
load_annotation_reference_sets: path_dict["ANNOTATION_REFERENCE_SET"],
load_association_reference_sets: path_dict["ASSOCIATION_REFERENCE_SET"],
load_module_dependency_reference_sets:
path_dict["MODULE_DEPENDENCY_REFERENCE_SET"],
load_description_format_reference_sets:
path_dict["DESCRIPTION_FORMAT_REFERENCE_SET"],
load_refset_descriptor_reference_sets: path_dict["REFSET_DESCRIPTOR"],
load_description_type_reference_sets: path_dict["DESCRIPTION_TYPE"]
})
make_current_snapshot()
|
test_thruster_manager_proportional_correct.test.py | #!/usr/bin/env python3
# Copyright (c) 2020 The Plankton Authors.
# All rights reserved.
#
# This source code is derived from UUV Simulator
# (https://github.com/uuvsimulator/uuv_simulator)
# Copyright (c) 2016-2019 The UUV Simulator Authors
# licensed under the Apache license, Version 2.0
# cf. 3rd-party-licenses.txt file in the root directory of this source tree.
#
# 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
import numpy as np
import rclpy
from uuv_thrusters import ThrusterManager
import launch
from launch import LaunchDescription
import launch_testing.actions
import launch_ros
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import os
import pathlib
import xacro
import pytest
import threading
import time
REFERENCE_TAM = np.array([
[1, 0, 0, 0, 0, 0],
[0.87758256, 0, -0.47942554, 0.47942554, 0.47942554, 0.87758256],
[0.87758256, 0.47942554, 0, -0.47942554, 0.87758256, -0.87758256]
]).T
def ensure_path_exists(full_path):
dir_name = os.path.dirname(full_path)
if dir_name:
try:
os.makedirs(dir_name)
except OSError:
print ("Creation of the directory %s failed" % dir_name)
class TestThrusterManagerProportionalCorrect(unittest.TestCase):
_manager = None
@classmethod
def setUpClass(cls):
parent_file_path = pathlib.Path(__file__).parent
thruster_manager_yaml = os.path.join(
str(parent_file_path),
'test_vehicle_thruster_manager_proportional.yaml'
)
xacro_file = os.path.join(
str(parent_file_path),
'test_vehicle_x_axis.urdf.xacro'
)
output = os.path.join(
str(parent_file_path),
'robot_description_x_axis.urdf'
)
#TODO Change in foxy
if not pathlib.Path(output).exists():
doc = xacro.process(xacro_file)
try:
with open(output, 'w') as file_out:
file_out.write(doc)
except IOError as e:
print("Failed to open output:", exc=e)
# Initialize the ROS context for the test node
# FIXME Temp workaround TF for listener subscribing to relative topic
rclpy.init(args=['--ros-args', '--params-file', thruster_manager_yaml,
'-r', '__ns:=/test_vehicle', '-r', 'tf:=/tf', '-p', 'urdf_file:=%s' % output])
# Name alias...why cls is not working ?
_class = TestThrusterManagerProportionalCorrect
_class._manager = ThrusterManager('test_thruster_manager_proportional_correct')
_class._thread = threading.Thread(target=rclpy.spin, args=(_class._manager,), daemon=True)
_class._thread.start()
# Wait for the async initialization of the manager to finish
while not _class._manager.ready:
time.sleep(0.1)
# =========================================================================
@classmethod
def tearDownClass(cls):
_class = TestThrusterManagerProportionalCorrect
_class._manager.destroy_node()
# Shutdown the ROS context
rclpy.shutdown()
_class._thread.join()
# =========================================================================
# def setUp(self):
# # =========================================================================
# def tearDown(self):
# # self.MANAGER.destroy_node()
# # self.thread.join()
# =========================================================================
def test_initialization(self):
_class = TestThrusterManagerProportionalCorrect
self.assertEqual(_class._manager.namespace, '/test_vehicle/')
self.assertEqual(_class._manager.config['tf_prefix'].value, 'test_vehicle')
self.assertEqual(_class._manager.config['base_link'].value, 'base_link')
self.assertEqual(_class._manager.config['thruster_topic_prefix'].value, 'thrusters/')
self.assertEqual(_class._manager.config['thruster_frame_base'].value, 'thruster_')
self.assertEqual(_class._manager.config['thruster_topic_suffix'].value, '/input')
self.assertEqual(_class._manager.config['timeout'].value, -1)
self.assertEqual(_class._manager.config['max_thrust'].value, 1000.0)
self.assertEqual(_class._manager.config['update_rate'].value, 50)
self.assertEqual(_class._manager.n_thrusters, 3)
self.assertEqual(REFERENCE_TAM.shape, _class._manager.configuration_matrix.shape)
self.assertTrue(np.isclose(REFERENCE_TAM, _class._manager.configuration_matrix).all())
# =========================================================================
def test_thrusters(self):
_class = TestThrusterManagerProportionalCorrect
self.assertEqual(len(_class._manager.thrusters), 3)
for i in range(len(_class._manager.thrusters)):
self.assertEqual(_class._manager.thrusters[i].index, i)
self.assertEqual(_class._manager.thrusters[i].topic, 'thrusters/id_{}/input'.format(i))
self.assertEqual(_class._manager.thrusters[i].LABEL, 'proportional')
self.assertTrue(np.isclose(REFERENCE_TAM[:, i].flatten(), _class._manager.thrusters[i].tam_column).all())
# =========================================================================
def test_processing_gen_forces(self):
_class = TestThrusterManagerProportionalCorrect
for _ in range(10):
gen_force = np.random.rand(6) * 100
thrust_forces = _class._manager.compute_thruster_forces(gen_force)
ref_thrust_forces = np.linalg.pinv(REFERENCE_TAM).dot(gen_force)
self.assertTrue(np.isclose(ref_thrust_forces, thrust_forces).all())
# =============================================================================
@pytest.mark.rostest
def generate_test_description():
#path_to_test = os.path.dirname(__file__)
file_path = pathlib.Path(__file__)
# Here, parent first removes the file name
parent_file_path = pathlib.Path(__file__).parent
thruster_manager_launch = os.path.join(
get_package_share_directory('uuv_thruster_manager'),
'launch',
'thruster_manager.launch'
)
thruster_manager_yaml = os.path.join(
str(parent_file_path),
'test_vehicle_thruster_manager_proportional.yaml'
)
xacro_file = os.path.join(
str(parent_file_path),
'test_vehicle_x_axis.urdf.xacro'
)
output = os.path.join(
str(parent_file_path),
'robot_description_x_axis.urdf'
)
doc = xacro.process(xacro_file)
ensure_path_exists(output)
try:
with open(output, 'w') as file_out:
file_out.write(doc)
except IOError as e:
print("Failed to open output:", exc=e)
args = output.split()
joint_state_publisher = launch_ros.actions.Node(
node_namespace = 'test_vehicle',
package="joint_state_publisher",
node_executable="joint_state_publisher",
node_name="joint_state_publisher",
arguments=args,
output='screen',
parameters=[{'use_sim_time':False}, {'rate': 100}],
)
robot_state_description = launch_ros.actions.Node(
node_namespace = 'test_vehicle',
package='robot_state_publisher',
node_executable='robot_state_publisher',
# TODO To replace in foxy with parameters=[{'robot_description', Command('ros2 run xacro...')}]
arguments=args,
output='screen',
parameters=[{'use_sim_time':False}], # Use subst here
)
return (
launch.LaunchDescription([
joint_state_publisher,
robot_state_description,
launch_testing.actions.ReadyToTest(),
])
)
|
SocketServer1.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import socket
from multiprocessing import Process
# 买手机
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 重用地址,防止
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 绑卡
server.bind(('127.0.0.1',8080))
# 监听客户端的上限
server.listen(4)
def talk(conn,addr):
while True: # 通信循环
try:
print("连接中……")
msg = conn.recv(1024)
if not msg: break
conn.send(msg.upper())
except Exception:
break
if __name__ == '__main__':
# 链接循环
while True:
conn,addr = server.accept()
p = Process(target=talk,args=(conn,addr))
p.start() |
btdownloadgui.py | #!/usr/bin/env python
# Written by Bram Cohen and Myers Carpenter
# Modifications by various people
# see LICENSE.txt for license information
import sys
import os
import re
import time
import random
import socket
import hashlib
import threading
import traceback
from binascii import hexlify
from webbrowser import open_new
from StringIO import StringIO
from BitTornado.download_bt1 import BT1Download, parse_params, get_usage, \
get_response
from BitTornado.RawServer import RawServer
from BitTornado.SocketHandler import UPnP_ERROR
from BitTornado.ConnChoice import connChoices, connChoiceList
from BitTornado.ConfigReader import configReader
from BitTornado.bencode import bencode
from BitTornado.natpunch import UPnP_test
from BitTornado.clock import clock
from BitTornado import version, createPeerID, report_email
try:
from wxPython import wx
except:
print 'wxPython is not installed or has not been installed properly.'
sys.exit(1)
PROFILER = False
WXPROFILER = False
try:
wx.wxFULL_REPAINT_ON_RESIZE
except:
wx.wxFULL_REPAINT_ON_RESIZE = 0 # fix for wx pre-2.5
# Note to packagers: edit OLDICONPATH in BitTornado/ConfigDir.py
def hours(n):
if n == 0:
return 'download complete'
try:
n = int(n)
assert n >= 0 and n < 5184000 # 60 days
except:
return '<unknown>'
m, s = divmod(n, 60)
h, m = divmod(m, 60)
if h > 0:
return '%d hour(s) %02d min %02d sec' % (h, m, s)
else:
return '%d min %02d sec' % (m, s)
def size_format(s):
if (s < 1024):
r = '{:d}B'.format(s)
elif (s < 1048576):
r = '{:d}KiB'.format(s / 1024)
elif (s < 1073741824L):
r = '{:d}MiB'.format(s / (1 << 20))
elif (s < 1099511627776L):
r = '{:.2f}GiB'.format(float(s) / (1 << 30))
else:
r = '{:.2f}TiB'.format(float(s) / (1 << 40))
return(r)
def comma_format(s):
r = str(s)
for i in range(len(r) - 3, 0, -3):
r = r[:i] + ',' + r[i:]
return(r)
wxEVT_INVOKE = wx.wxNewEventType()
def EVT_INVOKE(win, func):
win.Connect(-1, -1, wxEVT_INVOKE, func)
class InvokeEvent(wx.wxPyEvent):
def __init__(self, func=None, args=None, kwargs=None):
super(InvokeEvent, self).__init__()
self.SetEventType(wxEVT_INVOKE)
self.func = func
self.args = args
self.kwargs = kwargs
class DownloadInfoFrame:
def __init__(self, flag, configfile):
self._errorwindow = None
try:
self.FONT = configfile.config['gui_font']
self.default_font = wx.wxFont(self.FONT, wx.wxDEFAULT, wx.wxNORMAL,
wx.wxNORMAL, False)
frame = wx.wxFrame(None, -1, 'BitTorrent ' + version + ' download',
style=wx.wxDEFAULT_FRAME_STYLE |
wx.wxFULL_REPAINT_ON_RESIZE)
self.flag = flag
self.configfile = configfile
self.configfileargs = configfile.config
self.uiflag = threading.Event()
self.fin = False
self.aboutBox = None
self.detailBox = None
self.advBox = None
self.creditsBox = None
self.statusIconHelpBox = None
self.reannouncelast = 0
self.spinlock = 0
self.scrollock = 0
self.lastError = 0
self.spewwait = clock()
self.config = None
self.updateSpinnerFlag = 0
self.updateSliderFlag = 0
self.statusIconValue = ' '
self.iconized = 0
self.taskbaricon = False
self.checking = None
self.activity = 'Starting up...'
self.firstupdate = True
self.shuttingdown = False
self.ispaused = False
self.bgalloc_periods = 0
self.gui_fractiondone = None
self.fileList = None
self.lastexternalannounce = ''
self.refresh_details = False
self.lastuploadsettings = 0
self.old_download = 0
self.old_upload = 0
self.old_ratesettings = None
self.current_ratesetting = None
self.gaugemode = None
self.autorate = False
self.filename = None
self.dow = None
if sys.platform == 'win32':
self.invokeLaterEvent = InvokeEvent()
self.invokeLaterList = []
wx.wxInitAllImageHandlers()
self.basepath = self.configfile.getIconDir()
self.icon = wx.wxIcon(os.path.join(self.basepath, 'icon_bt.ico'),
wx.wxBITMAP_TYPE_ICO)
self.finicon = wx.wxIcon(os.path.join(self.basepath,
'icon_done.ico'),
wx.wxBITMAP_TYPE_ICO)
self.statusIconFiles = {
'startup': os.path.join(self.basepath, 'white.ico'),
'disconnected': os.path.join(self.basepath, 'black.ico'),
'noconnections': os.path.join(self.basepath, 'red.ico'),
'nocompletes': os.path.join(self.basepath, 'blue.ico'),
'noincoming': os.path.join(self.basepath, 'yellow.ico'),
'allgood': os.path.join(self.basepath, 'green.ico'),
}
self.statusIcons = {}
self.filestatusIcons = wx.wxImageList(16, 16)
self.filestatusIcons.Add(wx.wxBitmap(os.path.join(self.basepath,
'black1.ico'), wx.wxBITMAP_TYPE_ICO))
self.filestatusIcons.Add(wx.wxBitmap(os.path.join(self.basepath,
'yellow1.ico'), wx.wxBITMAP_TYPE_ICO))
self.filestatusIcons.Add(wx.wxBitmap(os.path.join(self.basepath,
'green1.ico'), wx.wxBITMAP_TYPE_ICO))
self.allocbuttonBitmap = wx.wxBitmap(
os.path.join(self.basepath, 'alloc.gif'), wx.wxBITMAP_TYPE_GIF)
self.starttime = clock()
self.frame = frame
try:
self.frame.SetIcon(self.icon)
except:
pass
panel = wx.wxPanel(frame, -1)
self.bgcolor = panel.GetBackgroundColour()
def StaticText(text, font=self.FONT - 1, underline=False,
color=None, panel=panel):
x = wx.wxStaticText(panel, -1, text, style=wx.wxALIGN_LEFT)
x.SetFont(wx.wxFont(font, wx.wxDEFAULT, wx.wxNORMAL,
wx.wxNORMAL, underline))
if color is not None:
x.SetForegroundColour(color)
return x
colSizer = wx.wxFlexGridSizer(cols=1, vgap=3)
border = wx.wxBoxSizer(wx.wxHORIZONTAL)
border.Add(colSizer, 1, wx.wxEXPAND | wx.wxALL, 4)
panel.SetSizer(border)
panel.SetAutoLayout(True)
topboxsizer = wx.wxFlexGridSizer(cols=3, vgap=0)
topboxsizer.AddGrowableCol(0)
fnsizer = wx.wxFlexGridSizer(cols=1, vgap=0)
fnsizer.AddGrowableCol(0)
fnsizer.AddGrowableRow(1)
fileNameText = StaticText('', self.FONT + 4)
fnsizer.Add(fileNameText, 1, wx.wxALIGN_BOTTOM | wx.wxEXPAND)
self.fileNameText = fileNameText
fnsizer2 = wx.wxFlexGridSizer(cols=8, vgap=0)
fnsizer2.AddGrowableCol(0)
fileSizeText = StaticText('')
fnsizer2.Add(fileSizeText, 1, wx.wxALIGN_BOTTOM | wx.wxEXPAND)
self.fileSizeText = fileSizeText
fileDetails = StaticText('Details', self.FONT, True, 'Blue')
fnsizer2.Add(fileDetails, 0, wx.wxALIGN_BOTTOM)
fnsizer2.Add(StaticText(' '))
advText = StaticText('Advanced', self.FONT, True, 'Blue')
fnsizer2.Add(advText, 0, wx.wxALIGN_BOTTOM)
fnsizer2.Add(StaticText(' '))
prefsText = StaticText('Prefs', self.FONT, True, 'Blue')
fnsizer2.Add(prefsText, 0, wx.wxALIGN_BOTTOM)
fnsizer2.Add(StaticText(' '))
aboutText = StaticText('About', self.FONT, True, 'Blue')
fnsizer2.Add(aboutText, 0, wx.wxALIGN_BOTTOM)
fnsizer2.Add(StaticText(' '))
fnsizer.Add(fnsizer2, 0, wx.wxEXPAND)
topboxsizer.Add(fnsizer, 0, wx.wxEXPAND)
topboxsizer.Add(StaticText(' '))
self.statusIcon = wx.wxEmptyBitmap(32, 32)
statidata = wx.wxMemoryDC()
statidata.SelectObject(self.statusIcon)
statidata.SetPen(wx.wxTRANSPARENT_PEN)
statidata.SetBrush(wx.wxBrush(self.bgcolor, wx.wxSOLID))
statidata.DrawRectangle(0, 0, 32, 32)
self.statusIconPtr = wx.wxStaticBitmap(panel, -1, self.statusIcon)
topboxsizer.Add(self.statusIconPtr)
self.fnsizer = fnsizer
self.fnsizer2 = fnsizer2
self.topboxsizer = topboxsizer
colSizer.Add(topboxsizer, 0, wx.wxEXPAND)
self.gauge = wx.wxGauge(panel, -1, range=1000,
style=wx.wxGA_SMOOTH)
colSizer.Add(self.gauge, 0, wx.wxEXPAND)
timeSizer = wx.wxFlexGridSizer(cols=2)
timeSizer.Add(StaticText('Time elapsed / estimated : '))
self.timeText = StaticText(self.activity + ' ' * 20)
timeSizer.Add(self.timeText)
timeSizer.AddGrowableCol(1)
colSizer.Add(timeSizer)
destSizer = wx.wxFlexGridSizer(cols=2, hgap=8)
self.fileDestLabel = StaticText('Download to:')
destSizer.Add(self.fileDestLabel)
self.fileDestText = StaticText('')
destSizer.Add(self.fileDestText, flag=wx.wxEXPAND)
destSizer.AddGrowableCol(1)
colSizer.Add(destSizer, flag=wx.wxEXPAND)
self.destSizer = destSizer
statSizer = wx.wxFlexGridSizer(cols=3, hgap=8)
self.ratesSizer = wx.wxFlexGridSizer(cols=2)
self.infoSizer = wx.wxFlexGridSizer(cols=2)
self.ratesSizer.Add(StaticText(' Download rate: '))
self.downRateText = StaticText('0 kB/s ')
self.ratesSizer.Add(self.downRateText, flag=wx.wxEXPAND)
self.downTextLabel = StaticText('Downloaded: ')
self.infoSizer.Add(self.downTextLabel)
self.downText = StaticText('0.00 MiB ')
self.infoSizer.Add(self.downText, flag=wx.wxEXPAND)
self.ratesSizer.Add(StaticText(' Upload rate: '))
self.upRateText = StaticText('0 kB/s ')
self.ratesSizer.Add(self.upRateText, flag=wx.wxEXPAND)
self.upTextLabel = StaticText('Uploaded: ')
self.infoSizer.Add(self.upTextLabel)
self.upText = StaticText('0.00 MiB ')
self.infoSizer.Add(self.upText, flag=wx.wxEXPAND)
shareSizer = wx.wxFlexGridSizer(cols=2, hgap=8)
shareSizer.Add(StaticText('Share rating:'))
self.shareRatingText = StaticText('')
shareSizer.AddGrowableCol(1)
shareSizer.Add(self.shareRatingText, flag=wx.wxEXPAND)
statSizer.Add(self.ratesSizer)
statSizer.Add(self.infoSizer)
statSizer.Add(shareSizer, flag=wx.wxALIGN_CENTER_VERTICAL)
colSizer.Add(statSizer)
torrentSizer = wx.wxFlexGridSizer(cols=1)
self.peerStatusText = StaticText('')
torrentSizer.Add(self.peerStatusText, 0, wx.wxEXPAND)
self.seedStatusText = StaticText('')
torrentSizer.Add(self.seedStatusText, 0, wx.wxEXPAND)
torrentSizer.AddGrowableCol(0)
colSizer.Add(torrentSizer, 0, wx.wxEXPAND)
self.torrentSizer = torrentSizer
self.errorTextSizer = wx.wxFlexGridSizer(cols=1)
self.errorText = StaticText('', self.FONT, False, 'Red')
self.errorTextSizer.Add(self.errorText, 0, wx.wxEXPAND)
colSizer.Add(self.errorTextSizer, 0, wx.wxEXPAND)
cancelSizer = wx.wxGridSizer(cols=2, hgap=40)
self.pauseButton = wx.wxButton(panel, -1, 'Pause')
cancelSizer.Add(self.pauseButton, 0, wx.wxALIGN_CENTER)
self.cancelButton = wx.wxButton(panel, -1, 'Cancel')
cancelSizer.Add(self.cancelButton, 0, wx.wxALIGN_CENTER)
colSizer.Add(cancelSizer, 0, wx.wxALIGN_CENTER)
# Setting options
slideSizer = wx.wxFlexGridSizer(cols=7, hgap=0, vgap=5)
# dropdown
self.connChoiceLabel = StaticText('Settings for ')
slideSizer.Add(self.connChoiceLabel, 0,
wx.wxALIGN_LEFT | wx.wxALIGN_CENTER_VERTICAL)
self.connChoice = wx.wxChoice(panel, -1, (-1, -1),
(self.FONT * 12, -1),
choices=connChoiceList)
self.connChoice.SetFont(self.default_font)
self.connChoice.SetSelection(0)
slideSizer.Add(self.connChoice, 0, wx.wxALIGN_CENTER)
self.rateSpinnerLabel = StaticText(' Upload rate (kB/s) ')
slideSizer.Add(self.rateSpinnerLabel, 0,
wx.wxALIGN_RIGHT | wx.wxALIGN_CENTER_VERTICAL)
# max upload rate
self.rateSpinner = wx.wxSpinCtrl(panel, -1, "", (-1, -1), (50, -1))
self.rateSpinner.SetFont(self.default_font)
self.rateSpinner.SetRange(0, 5000)
self.rateSpinner.SetValue(0)
slideSizer.Add(self.rateSpinner, 0,
wx.wxALIGN_CENTER | wx.wxALIGN_CENTER_VERTICAL)
self.rateLowerText = StaticText('%7d' % 0)
self.rateUpperText = StaticText('%5d' % 5000)
self.rateslider = wx.wxSlider(panel, -1, 0, 0, 5000, (-1, -1),
(80, -1))
slideSizer.Add(self.rateLowerText, 0,
wx.wxALIGN_RIGHT | wx.wxALIGN_CENTER_VERTICAL)
slideSizer.Add(self.rateslider, 0,
wx.wxALIGN_CENTER | wx.wxALIGN_CENTER_VERTICAL)
slideSizer.Add(self.rateUpperText, 0,
wx.wxALIGN_LEFT | wx.wxALIGN_CENTER_VERTICAL)
slideSizer.Add(StaticText(''), 0, wx.wxALIGN_LEFT)
self.bgallocText = StaticText('', self.FONT + 2, False, 'Red')
slideSizer.Add(self.bgallocText, 0, wx.wxALIGN_LEFT)
# max uploads
self.connSpinnerLabel = StaticText(' Max uploads ')
slideSizer.Add(self.connSpinnerLabel, 0,
wx.wxALIGN_RIGHT | wx.wxALIGN_CENTER_VERTICAL)
self.connSpinner = wx.wxSpinCtrl(panel, -1, "", (-1, -1), (50, -1))
self.connSpinner.SetFont(self.default_font)
self.connSpinner.SetRange(4, 100)
self.connSpinner.SetValue(4)
slideSizer.Add(self.connSpinner, 0,
wx.wxALIGN_CENTER | wx.wxALIGN_CENTER_VERTICAL)
self.connLowerText = StaticText('%7d' % 4)
self.connUpperText = StaticText('%5d' % 100)
self.connslider = wx.wxSlider(panel, -1, 4, 4, 100, (-1, -1),
(80, -1))
slideSizer.Add(self.connLowerText, 0,
wx.wxALIGN_RIGHT | wx.wxALIGN_CENTER_VERTICAL)
slideSizer.Add(self.connslider, 0,
wx.wxALIGN_CENTER | wx.wxALIGN_CENTER_VERTICAL)
slideSizer.Add(self.connUpperText, 0,
wx.wxALIGN_LEFT | wx.wxALIGN_CENTER_VERTICAL)
colSizer.Add(slideSizer, 1,
wx.wxALL | wx.wxALIGN_CENTER | wx.wxEXPAND, 0)
self.unlimitedLabel = StaticText('0 kB/s means unlimited. Tip: '
'your download rate is '
'proportional to your upload '
'rate', self.FONT - 2)
colSizer.Add(self.unlimitedLabel, 0, wx.wxALIGN_CENTER)
self.priorityIDs = [wx.wxNewId() for i in xrange(4)]
self.prioritycolors = [wx.wxColour(160, 160, 160),
wx.wxColour(255, 64, 0),
wx.wxColour(0, 0, 0),
wx.wxColour(64, 64, 255)]
wx.EVT_LEFT_DOWN(aboutText, self.about)
wx.EVT_LEFT_DOWN(fileDetails, self.details)
wx.EVT_LEFT_DOWN(self.statusIconPtr, self.statusIconHelp)
wx.EVT_LEFT_DOWN(advText, self.advanced)
wx.EVT_LEFT_DOWN(prefsText, self.openConfigMenu)
wx.EVT_CLOSE(frame, self.done)
wx.EVT_BUTTON(frame, self.pauseButton.GetId(), self.pause)
wx.EVT_BUTTON(frame, self.cancelButton.GetId(), self.done)
EVT_INVOKE(frame, self.onInvoke)
wx.EVT_SCROLL(self.rateslider, self.onRateScroll)
wx.EVT_SCROLL(self.connslider, self.onConnScroll)
wx.EVT_CHOICE(self.connChoice, -1, self.onConnChoice)
wx.EVT_SPINCTRL(self.connSpinner, -1, self.onConnSpinner)
wx.EVT_SPINCTRL(self.rateSpinner, -1, self.onRateSpinner)
if (sys.platform == 'win32'):
self.frame.tbicon = wx.wxTaskBarIcon()
wx.EVT_ICONIZE(self.frame, self.onIconify)
wx.EVT_TASKBAR_LEFT_DCLICK(self.frame.tbicon,
self.onTaskBarActivate)
wx.EVT_TASKBAR_RIGHT_UP(self.frame.tbicon, self.onTaskBarMenu)
wx.EVT_MENU(self.frame.tbicon, self.TBMENU_RESTORE,
self.onTaskBarActivate)
wx.EVT_MENU(self.frame.tbicon, self.TBMENU_CLOSE, self.done)
colSizer.AddGrowableCol(0)
colSizer.AddGrowableRow(6)
self.frame.Show()
border.Fit(panel)
self.frame.Fit()
self.panel = panel
self.border = border
self.addwidth = aboutText.GetBestSize().GetWidth() + \
fileDetails.GetBestSize().GetWidth() + (self.FONT * 16)
self.fnsizer = fnsizer
self.colSizer = colSizer
minsize = self.colSizer.GetSize()
minsize.SetWidth(minsize.GetWidth())
minsize.SetHeight(minsize.GetHeight())
self.colSizer.SetMinSize(minsize)
self.colSizer.Fit(self.frame)
colSizer.Fit(frame)
except:
self.exception()
if sys.platform == 'win32': # windows-only optimization
def onInvoke(self, event):
while self.invokeLaterList:
func, args, kwargs = self.invokeLaterList[0]
if self.uiflag.isSet():
return
try:
apply(func, args, kwargs)
except:
self.exception()
del self.invokeLaterList[0]
def invokeLater(self, func, args=[], kwargs={}):
if not self.uiflag.isSet():
self.invokeLaterList.append((func, args, kwargs))
if len(self.invokeLaterList) == 1:
wx.wxPostEvent(self.frame, self.invokeLaterEvent)
else:
def onInvoke(self, event):
if not self.uiflag.isSet():
try:
apply(event.func, event.args, event.kwargs)
except:
self.exception()
def invokeLater(self, func, args=[], kwargs={}):
if not self.uiflag.isSet():
wx.wxPostEvent(self.frame, InvokeEvent(func, args, kwargs))
def getStatusIcon(self, name, bitmap=False):
if name in self.statusIcons:
i = self.statusIcons[name]
if isinstance(i, wx.wxIcon) and not bitmap:
return i
if bitmap:
i = wx.wxBitmap(self.statusIconFiles[name], wx.wxBITMAP_TYPE_ICO)
else:
i = wx.wxIcon(self.statusIconFiles[name], wx.wxBITMAP_TYPE_ICO)
self.statusIcons[name] = i
return i
def setStatusIcon(self, name):
if name == self.statusIconValue:
return
self.statusIconValue = name
statidata = wx.wxMemoryDC()
statidata.SelectObject(self.statusIcon)
statidata.BeginDrawing()
try:
statidata.DrawIcon(self.getStatusIcon(name), 0, 0)
except:
statidata.DrawBitmap(self.getStatusIcon(name, True), 0, 0, True)
statidata.EndDrawing()
statidata.SelectObject(wx.wxNullBitmap)
self.statusIconPtr.Refresh()
def createStatusIcon(self, name):
iconbuffer = wx.wxEmptyBitmap(32, 32)
bbdata = wx.wxMemoryDC()
bbdata.SelectObject(iconbuffer)
bbdata.SetPen(wx.wxTRANSPARENT_PEN)
bbdata.SetBrush(wx.wxBrush(self.bgcolor, wx.wxSOLID))
bbdata.DrawRectangle(0, 0, 32, 32)
try:
bbdata.DrawIcon(self.getStatusIcon(name), 0, 0)
except:
bbdata.DrawBitmap(self.getStatusIcon(name, True), 0, 0, True)
return iconbuffer
def setgaugemode(self, selection):
if selection is None:
selection = self.gaugemode
elif selection == self.gaugemode:
return
else:
self.gaugemode = selection
if selection < 0:
self.gauge.SetForegroundColour(self.configfile.getcheckingcolor())
self.gauge.SetBackgroundColour(
wx.wxSystemSettings_GetColour(wx.wxSYS_COLOUR_MENU))
elif selection == 0:
self.gauge.SetForegroundColour(self.configfile.getdownloadcolor())
self.gauge.SetBackgroundColour(
wx.wxSystemSettings_GetColour(wx.wxSYS_COLOUR_MENU))
else:
self.gauge.SetForegroundColour(self.configfile.getseedingcolor())
self.gauge.SetBackgroundColour(self.configfile.getdownloadcolor())
def onIconify(self, evt):
try:
if self.configfileargs['win32_taskbar_icon']:
if self.fin:
self.frame.tbicon.SetIcon(self.finicon, "BitTorrent")
else:
self.frame.tbicon.SetIcon(self.icon, "BitTorrent")
self.frame.Hide()
self.taskbaricon = True
else:
return
except:
self.exception()
def onTaskBarActivate(self, evt):
try:
if self.frame.IsIconized():
self.frame.Iconize(False)
if not self.frame.IsShown():
self.frame.Show(True)
self.frame.Raise()
self.frame.tbicon.RemoveIcon()
self.taskbaricon = False
except wx.wxPyDeadObjectError:
pass
except:
self.exception()
TBMENU_RESTORE = 1000
TBMENU_CLOSE = 1001
def onTaskBarMenu(self, evt):
menu = wx.wxMenu()
menu.Append(self.TBMENU_RESTORE, "Restore BitTorrent")
menu.Append(self.TBMENU_CLOSE, "Close")
self.frame.tbicon.PopupMenu(menu)
menu.Destroy()
def _try_get_config(self):
if self.config is None:
try:
self.config = self.dow.getConfig()
except:
pass
return self.config is not None
def onRateScroll(self, event):
try:
if self.autorate:
return
if not self._try_get_config():
return
if (self.scrollock == 0):
self.scrollock = 1
self.updateSpinnerFlag = 1
self.dow.setUploadRate(self.rateslider.GetValue() *
connChoices[
self.connChoice.GetSelection()
]['rate'].get('div', 1))
self.scrollock = 0
except:
self.exception()
def onConnScroll(self, event):
try:
if self.autorate:
return
if not self._try_get_config():
return
self.connSpinner.SetValue(self.connslider.GetValue())
self.dow.setConns(self.connslider.GetValue())
except:
self.exception()
def onRateSpinner(self, event=None):
try:
if self.autorate:
return
if not self._try_get_config():
return
if (self.spinlock == 0):
self.spinlock = 1
spinnerValue = self.rateSpinner.GetValue()
div = connChoices[self.connChoice.GetSelection()]['rate'].get(
'div', 1)
if div > 1:
if spinnerValue > (self.config['max_upload_rate']):
round_up = div - 1
else:
round_up = 0
newValue = int((spinnerValue + round_up) / div) * div
if newValue != spinnerValue:
self.rateSpinner.SetValue(newValue)
else:
newValue = spinnerValue
self.dow.setUploadRate(newValue)
self.updateSliderFlag = 1
self.spinlock = 0
except:
self.exception()
def onDownRateSpinner(self, event=None):
try:
if not self._try_get_config():
return
self.dow.setDownloadRate(self.downrateSpinner.GetValue())
except:
self.exception()
def onConnSpinner(self, event=None):
try:
if self.autorate:
return
if not self._try_get_config():
return
self.connslider.SetValue(self.connSpinner.GetValue())
self.dow.setConns(self.connslider.GetValue())
except:
self.exception()
def onConnChoice(self, event, cons=None, rate=None):
try:
if not self._try_get_config():
return
num = self.connChoice.GetSelection()
choice = connChoices[num]
if 'super-seed' in choice: # selecting super-seed is now a toggle
self.dow.set_super_seed() # one way change, don't go back
self.connChoice.SetSelection(self.lastuploadsettings)
return
self.lastuploadsettings = num
self.current_ratesetting = self.connChoice.GetStringSelection()
if rate is None:
rate = choice['rate']['def']
self.rateSpinner.SetRange(choice['rate']['min'],
choice['rate']['max'])
self.rateSpinner.SetValue(rate)
self.rateslider.SetRange(
choice['rate']['min'] / choice['rate'].get('div', 1),
choice['rate']['max'] / choice['rate'].get('div', 1))
self.rateslider.SetValue(rate / choice['rate'].get('div', 1))
self.rateLowerText.SetLabel(' %d' % choice['rate']['min'])
self.rateUpperText.SetLabel('%d' % choice['rate']['max'])
if cons is None:
cons = choice['conn']['def']
self.connSpinner.SetRange(choice['conn']['min'],
choice['conn']['max'])
self.connSpinner.SetValue(cons)
self.connslider.SetRange(choice['conn']['min'],
choice['conn']['max'])
self.connslider.SetValue(cons)
self.connLowerText.SetLabel(' %d' % choice['conn']['min'])
self.connUpperText.SetLabel('%d' % choice['conn']['max'])
self.onConnScroll(0)
self.onRateScroll(0)
self.dow.setInitiate(choice.get('initiate', 40))
if 'automatic' in choice:
if not self.autorate:
self.autorate = True
self.rateSpinner.Enable(False)
self.connSpinner.Enable(False)
self.dow.setUploadRate(-1)
else:
if self.autorate:
self.autorate = False
self.rateSpinner.Enable(True)
self.connSpinner.Enable(True)
self.onRateSpinner()
self.onConnSpinner()
except:
self.exception()
def about(self, event):
try:
if (self.aboutBox is not None):
try:
self.aboutBox.Close()
except wx.wxPyDeadObjectError:
self.aboutBox = None
self.aboutBox = wx.wxFrame(
None, -1, 'About BitTorrent', size=(1, 1),
style=wx.wxDEFAULT_FRAME_STYLE | wx.wxFULL_REPAINT_ON_RESIZE)
try:
self.aboutBox.SetIcon(self.icon)
except:
pass
panel = wx.wxPanel(self.aboutBox, -1)
def StaticText(text, font=self.FONT, underline=False, color=None,
panel=panel):
x = wx.wxStaticText(panel, -1, text, style=wx.wxALIGN_LEFT)
x.SetFont(wx.wxFont(font, wx.wxDEFAULT, wx.wxNORMAL,
wx.wxNORMAL, underline))
if color is not None:
x.SetForegroundColour(color)
return x
colSizer = wx.wxFlexGridSizer(cols=1, vgap=3)
titleSizer = wx.wxBoxSizer(wx.wxHORIZONTAL)
aboutTitle = StaticText('BitTorrent {} '.format(version),
self.FONT + 4)
titleSizer.Add(aboutTitle)
linkDonate = StaticText('Donate to Bram', self.FONT, True, 'Blue')
titleSizer.Add(linkDonate, 1, wx.wxALIGN_BOTTOM & wx.wxEXPAND)
colSizer.Add(titleSizer, 0, wx.wxEXPAND)
colSizer.Add(StaticText('created by Bram Cohen, Copyright '
'2001-2003,'))
colSizer.Add(StaticText('experimental version maintained by John'
' Hoffman 2003'))
colSizer.Add(StaticText('modified from experimental version by '
'Eike Frost 2003'))
credits = StaticText('full credits\n', self.FONT, True, 'Blue')
colSizer.Add(credits)
si = '\n'.join(('exact Version String: ' + version,
'Python version: ' + sys.version,
'wxPython version: ' + wx.wxVERSION_STRING))
colSizer.Add(StaticText(si))
babble1 = StaticText(
'This is an experimental, unofficial build of BitTorrent.\n' +
'It is Free Software under an MIT-Style license.')
babble2 = StaticText('BitTorrent Homepage (link)', self.FONT, True,
'Blue')
babble3 = StaticText("TheSHAD0W's Client Homepage (link)",
self.FONT, True, 'Blue')
babble4 = StaticText("Eike Frost's Client Homepage (link)",
self.FONT, True, 'Blue')
babble6 = StaticText('License Terms (link)', self.FONT, True,
'Blue')
colSizer.Add(babble1)
colSizer.Add(babble2)
colSizer.Add(babble3)
colSizer.Add(babble4)
colSizer.Add(babble6)
okButton = wx.wxButton(panel, -1, 'Ok')
colSizer.Add(okButton, 0, wx.wxALIGN_RIGHT)
colSizer.AddGrowableCol(0)
border = wx.wxBoxSizer(wx.wxHORIZONTAL)
border.Add(colSizer, 1, wx.wxEXPAND | wx.wxALL, 4)
panel.SetSizer(border)
panel.SetAutoLayout(True)
def donatelink(self):
threading.Thread(
target=open_new('https://www.paypal.com/cgi-bin/webscr?'
'cmd=_xclick&business=bram@bitconjurer.'
'org&item_name=BitTorrent&amount=5.00&'
'submit=donate')).start()
wx.EVT_LEFT_DOWN(linkDonate, donatelink)
def aboutlink(self):
threading.Thread(
target=open_new('http://bitconjurer.org/BitTorrent/')
).start()
wx.EVT_LEFT_DOWN(babble2, aboutlink)
def shadlink(self):
threading.Thread(
target=open_new('http://www.bittornado.com/')).start()
wx.EVT_LEFT_DOWN(babble3, shadlink)
def explink(self):
threading.Thread(
target=open_new('http://ei.kefro.st/projects/btclient/')
).start()
wx.EVT_LEFT_DOWN(babble4, explink)
def licenselink(self):
threading.Thread(
target=open_new('http://ei.kefro.st/projects/btclient/'
'LICENSE.TXT')).start()
wx.EVT_LEFT_DOWN(babble6, licenselink)
wx.EVT_LEFT_DOWN(credits, self.credits)
def closeAbout(e, self=self):
if self.aboutBox:
self.aboutBox.Close()
wx.EVT_BUTTON(self.aboutBox, okButton.GetId(), closeAbout)
def kill(e, self=self):
try:
self.aboutBox.RemoveIcon()
except:
pass
self.aboutBox.Destroy()
self.aboutBox = None
wx.EVT_CLOSE(self.aboutBox, kill)
self.aboutBox.Show()
border.Fit(panel)
self.aboutBox.Fit()
except:
self.exception()
def details(self, event):
try:
if not self.dow or not self.filename:
return
metainfo = self.dow.getResponse()
if metainfo is None:
return
announce = metainfo.get('announce')
announce_list = metainfo.get('announce-list')
info = metainfo['info']
info_hash = self.dow.infohash
piece_length = info['piece length']
fileselector = self.dow.fileselector
if (self.detailBox is not None):
try:
self.detailBox.Close()
except wx.wxPyDeadObjectError:
self.detailBox = None
self.detailBox = wx.wxFrame(
None, -1, 'Torrent Details ', size=wx.wxSize(405, 230),
style=wx.wxDEFAULT_FRAME_STYLE | wx.wxFULL_REPAINT_ON_RESIZE)
try:
self.detailBox.SetIcon(self.icon)
except:
pass
panel = wx.wxPanel(self.detailBox, -1, size=wx.wxSize(400, 220))
def StaticText(text, font=self.FONT - 1, underline=False,
color=None, panel=panel):
x = wx.wxStaticText(panel, -1, text,
style=wx.wxALIGN_CENTER_VERTICAL)
x.SetFont(wx.wxFont(font, wx.wxDEFAULT, wx.wxNORMAL,
wx.wxNORMAL, underline))
if color is not None:
x.SetForegroundColour(color)
return x
colSizer = wx.wxFlexGridSizer(cols=1, vgap=3)
colSizer.AddGrowableCol(0)
titleSizer = wx.wxBoxSizer(wx.wxHORIZONTAL)
aboutTitle = StaticText('Details about ' + self.filename,
self.FONT + 4)
titleSizer.Add(aboutTitle)
colSizer.Add(titleSizer)
detailSizer = wx.wxFlexGridSizer(cols=2, vgap=6)
if 'length' in info:
fileListID = None
detailSizer.Add(StaticText('file name :'))
detailSizer.Add(StaticText(info['name']))
if 'md5sum' in info:
detailSizer.Add(StaticText('MD5 hash :'))
detailSizer.Add(StaticText(info['md5sum']))
file_length = info['length']
name = "file size"
else:
detail1Sizer = wx.wxFlexGridSizer(cols=1, vgap=6)
detail1Sizer.Add(StaticText('directory name : {}'.format(
info['name'])))
colSizer.Add(detail1Sizer)
bgallocButton = wx.wxBitmapButton(
panel, -1, self.allocbuttonBitmap, size=(52, 20))
def bgalloc(self, frame=self):
if frame.dow.storagewrapper is not None:
frame.dow.storagewrapper.bgalloc()
wx.EVT_BUTTON(self.detailBox, bgallocButton.GetId(), bgalloc)
bgallocbuttonSizer = wx.wxFlexGridSizer(cols=4, hgap=4, vgap=0)
bgallocbuttonSizer.Add(
StaticText('(right-click to set priority)', self.FONT - 1),
0, wx.wxALIGN_BOTTOM)
bgallocbuttonSizer.Add(StaticText('(finish allocation)'), -1,
wx.wxALIGN_CENTER_VERTICAL)
bgallocbuttonSizer.Add(bgallocButton, -1, wx.wxALIGN_CENTER)
bgallocbuttonSizer.AddGrowableCol(0)
colSizer.Add(bgallocbuttonSizer, -1, wx.wxEXPAND)
file_length = 0
fileListID = wx.wxNewId()
fileList = wx.wxListCtrl(panel, fileListID, wx.wxPoint(-1, -1),
(325, 100), wx.wxLC_REPORT)
self.fileList = fileList
fileList.SetImageList(self.filestatusIcons,
wx.wxIMAGE_LIST_SMALL)
fileList.SetAutoLayout(True)
fileList.InsertColumn(0, "file")
fileList.InsertColumn(1, "", format=wx.wxLIST_FORMAT_RIGHT,
width=55)
fileList.InsertColumn(2, "")
for i in xrange(len(info['files'])):
x = wx.wxListItem()
fileList.InsertItem(x)
x = 0
for file in info['files']:
path = ' '
for item in file['path']:
if (path != ''):
path = path + "/"
path = path + item
path += ' (' + str(file['length']) + ')'
fileList.SetStringItem(x, 0, path)
if 'md5sum' in file:
fileList.SetStringItem(x, 2, ' [{:s}]'.format(
file['md5sum']))
if fileselector:
p = fileselector[x]
item = self.fileList.GetItem(x)
item.SetTextColour(self.prioritycolors[p + 1])
fileList.SetItem(item)
x += 1
file_length += file['length']
fileList.SetColumnWidth(0, wx.wxLIST_AUTOSIZE)
fileList.SetColumnWidth(2, wx.wxLIST_AUTOSIZE)
name = 'archive size'
colSizer.Add(fileList, 1, wx.wxEXPAND)
colSizer.AddGrowableRow(3)
detailSizer.Add(StaticText('info_hash :'), 0,
wx.wxALIGN_CENTER_VERTICAL)
detailSizer.Add(wx.wxTextCtrl(panel, -1, hexlify(info_hash),
size=(325, -1), style=wx.wxTE_READONLY))
num_pieces = int((file_length + piece_length - 1) / piece_length)
detailSizer.Add(StaticText(name + ' : '))
detailSizer.Add(StaticText('{} ({} bytes)'.format(
size_format(file_length), comma_format(file_length))))
detailSizer.Add(StaticText('pieces : '))
if num_pieces > 1:
detailSizer.Add(StaticText('{:i} ({} bytes each)'.format(
num_pieces, comma_format(piece_length))))
else:
detailSizer.Add(StaticText('1'))
if announce_list is None:
detailSizer.Add(StaticText('announce url : '), 0,
wx.wxALIGN_CENTER_VERTICAL)
detailSizer.Add(wx.wxTextCtrl(panel, -1, announce,
size=(325, -1), style=wx.wxTE_READONLY))
else:
detailSizer.Add(StaticText(''))
trackerList = wx.wxListCtrl(panel, -1, wx.wxPoint(-1, -1),
(325, 75), wx.wxLC_REPORT)
trackerList.SetAutoLayout(True)
trackerList.InsertColumn(0, "")
trackerList.InsertColumn(1, "announce urls")
for tier in range(len(announce_list)):
for t in range(len(announce_list[tier])):
i = wx.wxListItem()
trackerList.InsertItem(i)
if announce is not None:
for l in [1, 2]:
i = wx.wxListItem()
trackerList.InsertItem(i)
x = 0
for tier in range(len(announce_list)):
for t in range(len(announce_list[tier])):
if t == 0:
trackerList.SetStringItem(x, 0, 'tier {}:'.format(
tier))
trackerList.SetStringItem(x, 1, announce_list[tier][t])
x += 1
if announce is not None:
trackerList.SetStringItem(x + 1, 0, 'single:')
trackerList.SetStringItem(x + 1, 1, announce)
trackerList.SetColumnWidth(0, wx.wxLIST_AUTOSIZE)
trackerList.SetColumnWidth(1, wx.wxLIST_AUTOSIZE)
detailSizer.Add(trackerList)
if announce is None and announce_list is not None:
announce = announce_list[0][0]
if announce is not None:
detailSizer.Add(StaticText('likely tracker :'))
p = re.compile('(.*/)[^/]+')
turl = p.sub(r'\1', announce)
trackerUrl = StaticText(turl, self.FONT, True, 'Blue')
detailSizer.Add(trackerUrl)
if 'comment' in metainfo:
detailSizer.Add(StaticText('comment :'))
detailSizer.Add(StaticText(metainfo['comment']))
if 'creation date' in metainfo:
detailSizer.Add(StaticText('creation date :'))
try:
detailSizer.Add(StaticText(time.strftime(
'%x %X', time.localtime(metainfo['creation date']))))
except:
try:
detailSizer.Add(StaticText(metainfo['creation date']))
except:
detailSizer.Add(StaticText('<cannot read date>'))
detailSizer.AddGrowableCol(1)
colSizer.Add(detailSizer, 1, wx.wxEXPAND)
okButton = wx.wxButton(panel, -1, 'Ok')
colSizer.Add(okButton, 0, wx.wxALIGN_RIGHT)
colSizer.AddGrowableCol(0)
if not self.configfileargs['gui_stretchwindow']:
aboutTitle.SetSize((400, -1))
else:
panel.SetAutoLayout(True)
border = wx.wxBoxSizer(wx.wxHORIZONTAL)
border.Add(colSizer, 1, wx.wxEXPAND | wx.wxALL, 4)
panel.SetSizer(border)
panel.SetAutoLayout(True)
if fileselector and fileListID:
def onRightClick(evt, self=self):
s = []
i = -1
while True:
i = self.fileList.GetNextItem(
i, state=wx.wxLIST_STATE_SELECTED)
if i == -1:
break
s.append(i)
if not s: # just in case
return
oldstate = self.dow.fileselector[s[0]]
kind = wx.wxITEM_RADIO
for i in s[1:]:
if self.dow.fileselector[i] != oldstate:
oldstate = None
kind = wx.wxITEM_NORMAL
break
menu = wx.wxMenu()
menu.Append(self.priorityIDs[1], "download first",
kind=kind)
menu.Append(self.priorityIDs[2], "download normally",
kind=kind)
menu.Append(self.priorityIDs[3], "download later",
kind=kind)
menu.Append(
self.priorityIDs[0], "download never (deletes)",
kind=kind)
if oldstate is not None:
menu.Check(self.priorityIDs[oldstate + 1], True)
def onSelection(evt, self=self, s=s):
p = evt.GetId()
priorities = self.dow.fileselector.get_priorities()
for i in xrange(len(self.priorityIDs)):
if p == self.priorityIDs[i]:
for ss in s:
priorities[ss] = i - 1
item = self.fileList.GetItem(ss)
item.SetTextColour(self.prioritycolors[i])
self.fileList.SetItem(item)
self.dow.fileselector.set_priorities(
priorities)
self.fileList.Refresh()
self.refresh_details = True
break
for id in self.priorityIDs:
wx.EVT_MENU(self.detailBox, id, onSelection)
self.detailBox.PopupMenu(menu, evt.GetPoint())
wx.EVT_LIST_ITEM_RIGHT_CLICK(self.detailBox, fileListID,
onRightClick)
def closeDetail(evt, self=self):
if self.detailBox:
self.detailBox.Close()
wx.EVT_BUTTON(self.detailBox, okButton.GetId(), closeDetail)
def kill(evt, self=self):
try:
self.detailBox.RemoveIcon()
except:
pass
self.detailBox.Destroy()
self.detailBox = None
self.fileList = None
self.dow.filedatflag.clear()
wx.EVT_CLOSE(self.detailBox, kill)
def trackerurl(self, turl=turl):
try:
threading.Thread(target=open_new(turl)).start()
except:
pass
wx.EVT_LEFT_DOWN(trackerUrl, trackerurl)
self.detailBox.Show()
border.Fit(panel)
self.detailBox.Fit()
self.refresh_details = True
self.dow.filedatflag.set()
except:
self.exception()
def credits(self, event):
try:
if (self.creditsBox is not None):
try:
self.creditsBox.Close()
except wx.wxPyDeadObjectError:
self.creditsBox = None
self.creditsBox = wx.wxFrame(
None, -1, 'Credits', size=(1, 1),
style=wx.wxDEFAULT_FRAME_STYLE | wx.wxFULL_REPAINT_ON_RESIZE)
try:
self.creditsBox.SetIcon(self.icon)
except:
pass
panel = wx.wxPanel(self.creditsBox, -1)
def StaticText(text, font=self.FONT, underline=False, color=None,
panel=panel):
x = wx.wxStaticText(panel, -1, text, style=wx.wxALIGN_LEFT)
x.SetFont(wx.wxFont(font, wx.wxDEFAULT, wx.wxNORMAL,
wx.wxNORMAL, underline))
if color is not None:
x.SetForegroundColour(color)
return x
colSizer = wx.wxFlexGridSizer(cols=1, vgap=3)
titleSizer = wx.wxBoxSizer(wx.wxHORIZONTAL)
aboutTitle = StaticText('Credits', self.FONT + 4)
titleSizer.Add(aboutTitle)
colSizer.Add(titleSizer)
colSizer.Add(StaticText(
'The following people have all helped with this\nversion of'
'BitTorrent in some way (in no particular order) -\n'))
creditSizer = wx.wxFlexGridSizer(cols=3)
creditSizer.Add(StaticText(
'Bill Bumgarner\n'
'David Creswick\n'
'Andrew Loewenstern\n'
'Ross Cohen\n'
'Jeremy Avnet\n'
'Greg Broiles\n'
'Barry Cohen\n'
'Bram Cohen\n'
'sayke\n'
'Steve Jenson\n'
'Myers Carpenter\n'
'Francis Crick\n'
'Petru Paler\n'
'Jeff Darcy\n'
'John Gilmore\n'
'Xavier Bassery\n'
'Pav Lucistnik'))
creditSizer.Add(StaticText(' '))
creditSizer.Add(StaticText(
'Yann Vernier\n'
'Pat Mahoney\n'
'Boris Zbarsky\n'
'Eric Tiedemann\n'
'Henry "Pi" James\n'
'Loring Holden\n'
'Robert Stone\n'
'Michael Janssen\n'
'Eike Frost\n'
'Andrew Todd\n'
'otaku\n'
'Edward Keyes\n'
'John Hoffman\n'
'Uoti Urpala\n'
'Jon Wolf\n'
'Christoph Hohmann\n'
'Micah Anderson'))
colSizer.Add(creditSizer, flag=wx.wxALIGN_CENTER_HORIZONTAL)
okButton = wx.wxButton(panel, -1, 'Ok')
colSizer.Add(okButton, 0, wx.wxALIGN_RIGHT)
colSizer.AddGrowableCol(0)
border = wx.wxBoxSizer(wx.wxHORIZONTAL)
border.Add(colSizer, 1, wx.wxEXPAND | wx.wxALL, 4)
panel.SetSizer(border)
panel.SetAutoLayout(True)
def closeCredits(e, self=self):
if self.creditsBox:
self.creditsBox.Close()
wx.EVT_BUTTON(self.creditsBox, okButton.GetId(), closeCredits)
def kill(e, self=self):
try:
self.creditsBox.RemoveIcon()
except:
pass
self.creditsBox.Destroy()
self.creditsBox = None
wx.EVT_CLOSE(self.creditsBox, kill)
self.creditsBox.Show()
border.Fit(panel)
self.creditsBox.Fit()
except:
self.exception()
def statusIconHelp(self, event):
try:
if (self.statusIconHelpBox is not None):
try:
self.statusIconHelpBox.Close()
except wx.wxPyDeadObjectError:
self.statusIconHelpBox = None
self.statusIconHelpBox = wx.wxFrame(
None, -1, 'Help with the BitTorrent Status Light', size=(1, 1),
style=wx.wxDEFAULT_FRAME_STYLE | wx.wxFULL_REPAINT_ON_RESIZE)
try:
self.statusIconHelpBox.SetIcon(self.icon)
except:
pass
panel = wx.wxPanel(self.statusIconHelpBox, -1)
def StaticText(text, font=self.FONT, underline=False, color=None,
panel=panel):
x = wx.wxStaticText(panel, -1, text, style=wx.wxALIGN_LEFT)
x.SetFont(wx.wxFont(font, wx.wxDEFAULT, wx.wxNORMAL,
wx.wxNORMAL, underline))
if color is not None:
x.SetForegroundColour(color)
return x
fullsizer = wx.wxFlexGridSizer(cols=1, vgap=13)
colsizer = wx.wxFlexGridSizer(cols=2, hgap=13, vgap=13)
disconnectedicon = self.createStatusIcon('disconnected')
colsizer.Add(wx.wxStaticBitmap(panel, -1, disconnectedicon))
colsizer.Add(StaticText(
'Waiting to connect to the tracker.\n'
'If the status light stays black for a long time the tracker\n'
'you are trying to connect to may not be working. Unless you\n'
'are receiving a message telling you otherwise, please wait,\n'
'and BitTorrent will automatically try to reconnect for you.'),
1, wx.wxALIGN_CENTER_VERTICAL)
noconnectionsicon = self.createStatusIcon('noconnections')
colsizer.Add(wx.wxStaticBitmap(panel, -1, noconnectionsicon))
colsizer.Add(StaticText(
'You have no connections with other clients.\n'
'Please be patient. If after several minutes the status\n'
'light remains red, this torrent may be old and abandoned.'),
1, wx.wxALIGN_CENTER_VERTICAL)
noincomingicon = self.createStatusIcon('noincoming')
colsizer.Add(wx.wxStaticBitmap(panel, -1, noincomingicon))
colsizer.Add(StaticText(
'You have not received any incoming connections from others.\n'
'It may only be because no one has tried. If you never see\n'
'the status light turn green, it may indicate your system\n'
'is behind a firewall or proxy server. Please look into\n'
'routing BitTorrent through your firewall in order to '
'receive\nthe best possible download rate.'), 1,
wx.wxALIGN_CENTER_VERTICAL)
nocompletesicon = self.createStatusIcon('nocompletes')
colsizer.Add(wx.wxStaticBitmap(panel, -1, nocompletesicon))
colsizer.Add(StaticText(
'There are no complete copies among the clients you are\n' +
'connected to. Don\'t panic, other clients in the torrent\n' +
"you can't see may have the missing data.\n" +
'If the status light remains blue, you may have problems\n' +
'completing your download.'), 1, wx.wxALIGN_CENTER_VERTICAL)
allgoodicon = self.createStatusIcon('allgood')
colsizer.Add(wx.wxStaticBitmap(panel, -1, allgoodicon))
colsizer.Add(StaticText('The torrent is operating properly.'), 1,
wx.wxALIGN_CENTER_VERTICAL)
fullsizer.Add(colsizer, 0, wx.wxALIGN_CENTER)
colsizer2 = wx.wxFlexGridSizer(cols=1, hgap=13)
colsizer2.Add(StaticText(
'Please note that the status light is not omniscient, and that'
'it may\nbe wrong in many instances. A torrent with a blue '
'light may complete\nnormally, and an occasional yellow light '
"doesn't mean your computer\nhas suddenly become firewalled."),
1, wx.wxALIGN_CENTER_VERTICAL)
colspacer = StaticText(' ')
colsizer2.Add(colspacer)
okButton = wx.wxButton(panel, -1, 'Ok')
colsizer2.Add(okButton, 0, wx.wxALIGN_CENTER)
fullsizer.Add(colsizer2, 0, wx.wxALIGN_CENTER)
border = wx.wxBoxSizer(wx.wxHORIZONTAL)
border.Add(fullsizer, 1, wx.wxEXPAND | wx.wxALL, 4)
panel.SetSizer(border)
panel.SetAutoLayout(True)
def closeHelp(self, frame=self):
frame.statusIconHelpBox.Close()
wx.EVT_BUTTON(self.statusIconHelpBox, okButton.GetId(), closeHelp)
self.statusIconHelpBox.Show()
border.Fit(panel)
self.statusIconHelpBox.Fit()
except:
self.exception()
def openConfigMenu(self, event):
try:
self.configfile.configMenu(self)
except:
self.exception()
def advanced(self, event):
try:
if not self.dow or not self.filename:
return
if (self.advBox is not None):
try:
self.advBox.Close()
except wx.wxPyDeadObjectError:
self.advBox = None
self.advBox = wx.wxFrame(
None, -1, 'BitTorrent Advanced', size=wx.wxSize(200, 200),
style=wx.wxDEFAULT_FRAME_STYLE | wx.wxFULL_REPAINT_ON_RESIZE)
try:
self.advBox.SetIcon(self.icon)
except:
pass
panel = wx.wxPanel(self.advBox, -1, size=wx.wxSize(200, 200))
def StaticText(text, font=self.FONT - 1, underline=False,
color=None, panel=panel):
x = wx.wxStaticText(panel, -1, text, style=wx.wxALIGN_LEFT)
x.SetFont(wx.wxFont(font, wx.wxDEFAULT, wx.wxNORMAL,
wx.wxNORMAL, underline))
if color is not None:
x.SetForegroundColour(color)
return x
colSizer = wx.wxFlexGridSizer(cols=1, vgap=1)
colSizer.Add(StaticText('Advanced Info for ' + self.filename,
self.FONT + 4))
try: # get system font width
fw = wx.wxSystemSettings_GetFont(
wx.wxSYS_DEFAULT_GUI_FONT
).GetPointSize() + 1
except:
fw = wx.wxSystemSettings_GetFont(
wx.wxSYS_SYSTEM_FONT
).GetPointSize() + 1
spewList = wx.wxListCtrl(
panel, -1, wx.wxPoint(-1, -1), (fw * 66, 350),
wx.wxLC_REPORT | wx.wxLC_HRULES | wx.wxLC_VRULES)
self.spewList = spewList
spewList.SetAutoLayout(True)
colSizer.Add(spewList, -1, wx.wxEXPAND)
colSizer.Add(StaticText(''))
self.storagestats1 = StaticText('')
self.storagestats2 = StaticText('')
colSizer.Add(self.storagestats1, -1, wx.wxEXPAND)
colSizer.Add(self.storagestats2, -1, wx.wxEXPAND)
spinnerSizer = wx.wxFlexGridSizer(cols=4, vgap=0, hgap=0)
cstats = ' Listening on '
if self.connection_stats['interfaces']:
cstats += ', '.join(self.connection_stats['interfaces']) + \
' on '
cstats += 'port ' + str(self.connection_stats['port'])
if self.connection_stats['upnp']:
cstats += ', UPnP port forwarded'
spinnerSizer.Add(StaticText(cstats), -1, wx.wxEXPAND)
spinnerSizer.AddGrowableCol(0)
spinnerSizer.Add(StaticText('Max download rate (kB/s) '), 0,
wx.wxALIGN_CENTER_VERTICAL)
self.downrateSpinner = wx.wxSpinCtrl(panel, -1, "", (-1, -1)
(50, -1))
self.downrateSpinner.SetFont(self.default_font)
self.downrateSpinner.SetRange(0, 5000)
self.downrateSpinner.SetValue(self.config['max_download_rate'])
spinnerSizer.Add(self.downrateSpinner, 0)
wx.EVT_SPINCTRL(self.downrateSpinner, -1, self.onDownRateSpinner)
spinnerSizer.Add(StaticText(' (0 = unlimited) '), 0,
wx.wxALIGN_CENTER_VERTICAL)
colSizer.Add(spinnerSizer, 0, wx.wxEXPAND)
colSizer.Add(StaticText(''))
buttonSizer = wx.wxFlexGridSizer(cols=5, hgap=20)
reannounceButton = wx.wxButton(panel, -1, 'Manual Announce')
buttonSizer.Add(reannounceButton)
extannounceButton = wx.wxButton(panel, -1, 'External Announce')
buttonSizer.Add(extannounceButton)
bgallocButton = wx.wxButton(panel, -1, 'Finish Allocation')
buttonSizer.Add(bgallocButton)
buttonSizer.Add(StaticText(''))
okButton = wx.wxButton(panel, -1, 'Ok')
buttonSizer.Add(okButton)
colSizer.Add(buttonSizer, 0, wx.wxALIGN_CENTER)
colSizer.AddGrowableCol(0)
colSizer.AddGrowableRow(1)
panel.SetSizer(colSizer)
panel.SetAutoLayout(True)
spewList.InsertColumn(0, "Optimistic Unchoke",
format=wx.wxLIST_FORMAT_CENTER, width=fw * 2)
spewList.InsertColumn(1, "Peer ID", width=0)
spewList.InsertColumn(2, "IP", width=fw * 11)
spewList.InsertColumn(3, "Local/Remote",
format=wx.wxLIST_FORMAT_CENTER, width=fw * 3)
spewList.InsertColumn(4, "Up", format=wx.wxLIST_FORMAT_RIGHT,
width=fw * 6)
spewList.InsertColumn(5, "Interested",
format=wx.wxLIST_FORMAT_CENTER, width=fw * 2)
spewList.InsertColumn(6, "Choking", format=wx.wxLIST_FORMAT_CENTER,
width=fw * 2)
spewList.InsertColumn(7, "Down", format=wx.wxLIST_FORMAT_RIGHT,
width=fw * 6)
spewList.InsertColumn(8, "Interesting",
format=wx.wxLIST_FORMAT_CENTER, width=fw * 2)
spewList.InsertColumn(9, "Choked", format=wx.wxLIST_FORMAT_CENTER,
width=fw * 2)
spewList.InsertColumn(10, "Snubbed",
format=wx.wxLIST_FORMAT_CENTER, width=fw * 2)
spewList.InsertColumn(11, "Downloaded",
format=wx.wxLIST_FORMAT_RIGHT, width=fw * 7)
spewList.InsertColumn(12, "Uploaded",
format=wx.wxLIST_FORMAT_RIGHT, width=fw * 7)
spewList.InsertColumn(13, "Completed",
format=wx.wxLIST_FORMAT_RIGHT, width=fw * 6)
spewList.InsertColumn(14, "Peer Download Speed",
format=wx.wxLIST_FORMAT_RIGHT, width=fw * 6)
def reannounce(self, frame=self):
if (clock() - frame.reannouncelast > 60):
frame.reannouncelast = clock()
frame.dow.reannounce()
wx.EVT_BUTTON(self.advBox, reannounceButton.GetId(), reannounce)
self.advextannouncebox = None
def reannounce_external(self, frame=self):
if (frame.advextannouncebox is not None):
try:
frame.advextannouncebox.Close()
except wx.wxPyDeadObjectError:
frame.advextannouncebox = None
frame.advextannouncebox = wx.wxFrame(
None, -1, 'External Announce', size=(1, 1),
style=wx.wxDEFAULT_FRAME_STYLE |
wx.wxFULL_REPAINT_ON_RESIZE)
try:
frame.advextannouncebox.SetIcon(frame.icon)
except:
pass
panel = wx.wxPanel(frame.advextannouncebox, -1)
fullsizer = wx.wxFlexGridSizer(cols=1, vgap=13)
msg = wx.wxStaticText(panel, -1, "Enter tracker anounce URL:")
msg.SetFont(frame.default_font)
fullsizer.Add(msg)
frame.advexturl = wx.wxTextCtrl(
parent=panel, id=-1, value='', size=(255, 20),
style=wx.wxTE_PROCESS_TAB)
frame.advexturl.SetFont(frame.default_font)
frame.advexturl.SetValue(frame.lastexternalannounce)
fullsizer.Add(frame.advexturl)
buttonSizer = wx.wxFlexGridSizer(cols=2, hgap=10)
okButton = wx.wxButton(panel, -1, 'OK')
buttonSizer.Add(okButton)
cancelButton = wx.wxButton(panel, -1, 'Cancel')
buttonSizer.Add(cancelButton)
fullsizer.Add(buttonSizer, 0, wx.wxALIGN_CENTER)
border = wx.wxBoxSizer(wx.wxHORIZONTAL)
border.Add(fullsizer, 1, wx.wxEXPAND | wx.wxALL, 4)
panel.SetSizer(border)
panel.SetAutoLayout(True)
def ok(self, frame=frame):
special = frame.advexturl.GetValue()
if special:
frame.lastexternalannounce = special
if (clock() - frame.reannouncelast > 60):
frame.reannouncelast = clock()
frame.dow.reannounce(special)
frame.advextannouncebox.Close()
wx.EVT_BUTTON(frame.advextannouncebox, okButton.GetId(), ok)
def cancel(self, frame=frame):
frame.advextannouncebox.Close()
wx.EVT_BUTTON(frame.advextannouncebox, cancelButton.GetId(),
cancel)
frame.advextannouncebox.Show()
fullsizer.Fit(panel)
frame.advextannouncebox.Fit()
wx.EVT_BUTTON(self.advBox, extannounceButton.GetId(),
reannounce_external)
def bgalloc(self, frame=self):
if frame.dow.storagewrapper is not None:
frame.dow.storagewrapper.bgalloc()
wx.EVT_BUTTON(self.advBox, bgallocButton.GetId(), bgalloc)
def closeAdv(evt, self=self):
self.advBox.Close()
def killAdv(evt, self=self):
try:
self.advBox.RemoveIcon()
except:
pass
self.onDownRateSpinner()
self.dow.spewflag.clear()
self.advBox.Destroy()
self.advBox = None
if (self.advextannouncebox is not None):
try:
self.advextannouncebox.Close()
except wx.wxPyDeadObjectError:
pass
self.advextannouncebox = None
wx.EVT_BUTTON(self.advBox, okButton.GetId(), closeAdv)
wx.EVT_CLOSE(self.advBox, killAdv)
self.advBox.Show()
colSizer.Fit(panel)
self.advBox.Fit()
if self.dow:
self.dow.spewflag.set()
except:
self.exception()
def displayUsage(self, text):
self.invokeLater(self.onDisplayUsage, [text])
def onDisplayUsage(self, text):
try:
self.done(None)
w = wx.wxFrame(
None, -1, 'BITTORRENT USAGE',
style=wx.wxDEFAULT_FRAME_STYLE | wx.wxFULL_REPAINT_ON_RESIZE)
panel = wx.wxPanel(w, -1)
sizer = wx.wxFlexGridSizer(cols=1)
sizer.Add(wx.wxTextCtrl(panel, -1, text, size=(500, 300),
style=wx.wxTE_READONLY | wx.wxTE_MULTILINE))
okButton = wx.wxButton(panel, -1, 'Ok')
def closeUsage(self, frame=self):
frame.usageBox.Close()
wx.EVT_BUTTON(w, okButton.GetId(), closeUsage)
def kill(self, frame=self):
frame.usageBox.Destroy()
frame.usageBox = None
wx.EVT_CLOSE(w, kill)
sizer.Add(okButton, 0, wx.wxALIGN_RIGHT)
border = wx.wxBoxSizer(wx.wxHORIZONTAL)
border.Add(sizer, 1, wx.wxEXPAND | wx.wxALL, 4)
panel.SetSizer(border)
panel.SetAutoLayout(True)
border.Fit(panel)
w.Fit()
w.Show()
self.usageBox = w
except:
self.exception()
def updateStatus(self, dpflag=threading.Event(), fractionDone=None,
timeEst=None, downRate=None, upRate=None, activity=None,
statistics=None, spew=None, sizeDone=None, **kws):
if activity is not None:
self.activity = activity
self.gui_fractiondone = fractionDone
self.invokeLater(
self.onUpdateStatus,
[dpflag, timeEst, downRate, upRate, statistics, spew, sizeDone])
def onUpdateStatus(self, dpflag, timeEst, downRate, upRate, statistics,
spew, sizeDone):
if self.firstupdate:
if not self.old_ratesettings:
self.old_ratesettings = {}
self.connChoice.SetStringSelection(self.old_ratesettings.get(
'rate setting',
self.configfileargs['gui_ratesettingsdefault']))
self.onConnChoice(
0, self.old_ratesettings.get('uploads'),
self.old_ratesettings.get('max upload rate'))
if 'max download rate' in self.old_ratesettings:
self.dow.setDownloadRate(
self.old_ratesettings['max download rate'])
if self.advBox:
self.downrateSpinner.SetValue(
self.old_ratesettings['max download rate'])
self.firstupdate = False
if self.advBox:
self.dow.spewflag.set()
if self.ispaused or statistics is None:
self.setStatusIcon('startup')
elif statistics.numPeers + statistics.numSeeds + \
statistics.numOldSeeds == 0:
if statistics.last_failed:
self.setStatusIcon('disconnected')
else:
self.setStatusIcon('noconnections')
elif not (statistics.external_connection_made or
self.configfileargs['gui_forcegreenonfirewall']):
self.setStatusIcon('noincoming')
elif ((statistics.numSeeds + statistics.numOldSeeds == 0)
and (self.fin and statistics.numCopies < 1 or
not self.fin and statistics.numCopies2 < 1)):
self.setStatusIcon('nocompletes')
elif timeEst == 0 and sizeDone < self.torrentsize:
self.setStatusIcon('nocompletes')
else:
self.setStatusIcon('allgood')
if statistics is None:
self.setgaugemode(-1)
elif self.gui_fractiondone is None or self.gui_fractiondone == 1.0:
self.setgaugemode(1)
else:
self.setgaugemode(0)
if self.updateSliderFlag == 1:
self.updateSliderFlag = 0
newValue = (self.rateSpinner.GetValue() /
connChoices[
self.connChoice.GetSelection()
]['rate'].get('div', 1))
if self.rateslider.GetValue() != newValue:
self.rateslider.SetValue(newValue)
if self.updateSpinnerFlag == 1:
self.updateSpinnerFlag = 0
cc = connChoices[self.connChoice.GetSelection()]
if 'rate' in cc:
newValue = (self.rateslider.GetValue() *
cc['rate'].get('div', 1))
if self.rateSpinner.GetValue() != newValue:
self.rateSpinner.SetValue(newValue)
if self.fin:
if statistics is None or statistics.numOldSeeds > 0 or \
statistics.numCopies > 1:
self.gauge.SetValue(1000)
else:
self.gauge.SetValue(int(1000 * statistics.numCopies))
elif self.gui_fractiondone is not None:
gaugelevel = int(self.gui_fractiondone * 1000)
self.gauge.SetValue(gaugelevel)
if statistics is not None and statistics.downTotal is not None:
if self.configfileargs['gui_displaymiscstats']:
self.frame.SetTitle(
'{:.1%} ({:.2f} MiB) {} - BitTorrent {}'.format(
float(gaugelevel) / 1000,
float(sizeDone) / (1 << 20),
self.filename, version))
else:
self.frame.SetTitle('{:.1%} {} - BitTorrent {}'.format(
float(gaugelevel) / 1000, self.filename, version))
else:
self.frame.SetTitle('{:.0%} {} - BitTorrent {}'.format(
float(gaugelevel) / 1000, self.filename, version))
if self.ispaused:
self.timeText.SetLabel(hours(clock() - self.starttime) + ' /')
elif timeEst is None:
self.timeText.SetLabel(hours(clock() - self.starttime) + ' / ' +
self.activity)
else:
self.timeText.SetLabel(hours(clock() - self.starttime) + ' / ' +
hours(timeEst))
if not self.ispaused:
if downRate is not None:
self.downRateText.SetLabel('{:.0f} kB/s'.format(
float(downRate) / 1000))
if upRate is not None:
self.upRateText.SetLabel('%.0f kB/s' % (float(upRate) / 1000))
if self.taskbaricon:
icontext = 'BitTorrent '
if self.gui_fractiondone is not None and not self.fin:
if statistics is not None and statistics.downTotal is not None:
icontext += ' {:.1%} ({:.2f} MiB)'.format(
self.gui_fractiondone, float(sizeDone) / (1 << 20))
else:
icontext += ' {:.0%}'.format(self.gui_fractiondone)
if upRate is not None:
icontext += ' u:{:.0f} kB/s'.format(float(upRate) / 1000)
if downRate is not None:
icontext += ' d:{:.0f} kB/s'.format(float(downRate) / 1000)
icontext += ' ' + self.filename
try:
if self.gui_fractiondone is None or \
self.gui_fractiondone == 1.0:
self.frame.tbicon.SetIcon(self.finicon, icontext)
else:
self.frame.tbicon.SetIcon(self.icon, icontext)
except:
pass
if statistics is not None:
if self.autorate:
self.rateSpinner.SetValue(statistics.upRate)
self.connSpinner.SetValue(statistics.upSlots)
downtotal = statistics.downTotal + self.old_download
uptotal = statistics.upTotal + self.old_upload
if self.configfileargs['gui_displaymiscstats']:
self.downText.SetLabel('{:.2f} MiB'.format(
float(downtotal) / (1 << 20)))
self.upText.SetLabel('{:.2f} MiB'.format(
float(uptotal) / (1 << 20)))
if downtotal > 0:
sharerating = float(uptotal) / downtotal
if sharerating == 0:
shareSmiley = ''
color = 'Black'
elif sharerating < 0.5:
shareSmiley = ':-('
color = 'Red'
elif sharerating < 1.0:
shareSmiley = ':-|'
color = 'Orange'
else:
shareSmiley = ':-)'
color = 'Forest Green'
elif uptotal == 0:
sharerating = None
shareSmiley = ''
color = 'Black'
else:
sharerating = None
shareSmiley = '00 :-D'
color = 'Forest Green'
if sharerating is None:
self.shareRatingText.SetLabel(shareSmiley)
else:
self.shareRatingText.SetLabel('{:.3f} {}'.format(
sharerating, shareSmiley))
self.shareRatingText.SetForegroundColour(color)
if self.configfileargs['gui_displaystats']:
if not self.fin:
self.seedStatusText.SetLabel(
'connected to {:d} seeds; also seeing {:.3f} '
'distributed copies'.format(
statistics.numSeeds, statistics.numCopies2))
else:
self.seedStatusText.SetLabel(
'{:d} seeds seen recently; also seeing {:.3f} '
'distributed copies'.format(
statistics.numOldSeeds, statistics.numCopies))
self.peerStatusText.SetLabel(
'connected to {:d} peers with an average of {:.1%} '
'completed (total speed {:.0f} kB/s)'.format(
statistics.numPeers,
statistics.percentDone / 100,
float(statistics.torrentRate) / 1000))
if ((clock() - self.lastError) > 300):
self.errorText.SetLabel('')
if (self.configfileargs['gui_displaymiscstats'] and
statistics is not None and statistics.backgroundallocating):
self.bgalloc_periods += 1
if self.bgalloc_periods > 3:
self.bgalloc_periods = 0
self.bgallocText.SetLabel('ALLOCATING' + (' .' *
self.bgalloc_periods))
elif self.dow.superseedflag.isSet():
self.bgallocText.SetLabel('SUPER-SEED')
else:
self.bgallocText.SetLabel('')
if spew is not None and (clock() - self.spewwait > 1):
if self.advBox is not None:
self.spewwait = clock()
spewList = self.spewList
spewlen = len(spew) + 2
if statistics is not None:
kickbanlen = len(statistics.peers_kicked) + \
len(statistics.peers_banned)
if kickbanlen:
spewlen += kickbanlen + 1
else:
kickbanlen = 0
for x in range(spewlen - spewList.GetItemCount()):
i = wx.wxListItem()
spewList.InsertItem(i)
for x in range(spewlen, spewList.GetItemCount()):
spewList.DeleteItem(len(spew) + 1)
tot_uprate = 0.0
tot_downrate = 0.0
for x in range(len(spew)):
if (spew[x]['optimistic'] == 1):
a = '*'
else:
a = ' '
spewList.SetStringItem(x, 0, a)
spewList.SetStringItem(x, 1, spew[x]['id'])
spewList.SetStringItem(x, 2, spew[x]['ip'])
spewList.SetStringItem(x, 3, spew[x]['direction'])
if spew[x]['uprate'] > 100:
spewList.SetStringItem(x, 4, '{:.0f} kB/s'.format(
float(spew[x]['uprate']) / 1000))
else:
spewList.SetStringItem(x, 4, ' ')
tot_uprate += spew[x]['uprate']
if (spew[x]['uinterested'] == 1):
a = '*'
else:
a = ' '
spewList.SetStringItem(x, 5, a)
if (spew[x]['uchoked'] == 1):
a = '*'
else:
a = ' '
spewList.SetStringItem(x, 6, a)
if spew[x]['downrate'] > 100:
spewList.SetStringItem(x, 7, '{:.0f} kB/s'.format(
float(spew[x]['downrate']) / 1000))
else:
spewList.SetStringItem(x, 7, ' ')
tot_downrate += spew[x]['downrate']
if (spew[x]['dinterested'] == 1):
a = '*'
else:
a = ' '
spewList.SetStringItem(x, 8, a)
if (spew[x]['dchoked'] == 1):
a = '*'
else:
a = ' '
spewList.SetStringItem(x, 9, a)
if (spew[x]['snubbed'] == 1):
a = '*'
else:
a = ' '
spewList.SetStringItem(x, 10, a)
spewList.SetStringItem(x, 11, '{:.2f} MiB'.format(
float(spew[x]['dtotal']) / (1 << 20)))
if spew[x]['utotal'] is not None:
a = '{:.2f} MiB'.format(
float(spew[x]['utotal']) / (1 << 20))
else:
a = ''
spewList.SetStringItem(x, 12, a)
spewList.SetStringItem(
x, 13, '{:.1%}'.format(spew[x]['completed']))
if spew[x]['speed'] is not None:
a = '%.0f kB/s' % (float(spew[x]['speed']) / 1000)
else:
a = ''
spewList.SetStringItem(x, 14, a)
x = len(spew)
for i in range(15):
spewList.SetStringItem(x, i, '')
x += 1
spewList.SetStringItem(x, 2, ' TOTALS:')
spewList.SetStringItem(x, 4, '{:.0f} kB/s'.format(
float(tot_uprate) / 1000))
spewList.SetStringItem(x, 7, '{:.0f} kB/s'.format(
float(tot_downrate) / 1000))
if statistics is not None:
spewList.SetStringItem(x, 11, '{:.2f} MiB'.format(
float(statistics.downTotal) / (1 << 20)))
spewList.SetStringItem(x, 12, '{:.2f} MiB'.format(
float(statistics.upTotal) / (1 << 20)))
else:
spewList.SetStringItem(x, 11, '')
spewList.SetStringItem(x, 12, '')
for i in (0, 1, 3, 5, 6, 8, 9, 10, 13, 14):
spewList.SetStringItem(x, i, '')
if kickbanlen:
x += 1
for i in range(14):
spewList.SetStringItem(x, i, '')
for peer in statistics.peers_kicked:
x += 1
spewList.SetStringItem(x, 2, peer[0])
spewList.SetStringItem(x, 1, peer[1])
spewList.SetStringItem(x, 4, 'KICKED')
for i in (0, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14):
spewList.SetStringItem(x, i, '')
for peer in statistics.peers_banned:
x += 1
spewList.SetStringItem(x, 2, peer[0])
spewList.SetStringItem(x, 1, peer[1])
spewList.SetStringItem(x, 4, 'BANNED')
for i in (0, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14):
spewList.SetStringItem(x, i, '')
if statistics is not None:
l1 = '{} currently downloading {:d} pieces ({:d} just ' \
'started), {:d} pieces partially retrieved'.format(
' ' * 9, statistics.storage_active,
statistics.storage_new, statistics.storage_dirty)
if statistics.storage_isendgame:
l1 += ', endgame mode'
self.storagestats2.SetLabel(l1)
self.storagestats1.SetLabel(
'{} {:d} of {:d} pieces complete ({:d} just '
'downloaded), {:d} failed hash check, {}KiB redundant '
'data discarded'.format(
' ' * 9, statistics.storage_numcomplete,
statistics.storage_totalpieces,
statistics.storage_justdownloaded,
statistics.storage_numflunked,
comma_format(int(statistics.discarded / 1024))))
if (self.fileList is not None and statistics is not None and
(statistics.filelistupdated.isSet() or self.refresh_details)):
for i in range(len(statistics.filecomplete)):
if self.dow.fileselector[i] == -1:
self.fileList.SetItemImage(i, 0, 0)
self.fileList.SetStringItem(i, 1, '')
elif statistics.fileinplace[i]:
self.fileList.SetItemImage(i, 2, 2)
self.fileList.SetStringItem(i, 1, "done")
elif statistics.filecomplete[i]:
self.fileList.SetItemImage(i, 1, 1)
self.fileList.SetStringItem(i, 1, "100%")
else:
self.fileList.SetItemImage(i, 0, 0)
frac = statistics.fileamtdone[i]
if frac:
self.fileList.SetStringItem(
i, 1, '{:.0%}'.format(frac))
else:
self.fileList.SetStringItem(i, 1, '')
statistics.filelistupdated.clear()
self.refresh_details = False
if self.configfile.configReset(): # Set everything invisible!
self.dow.config['security'] = self.configfileargs['security']
statsdisplayflag = self.configfileargs['gui_displaymiscstats']
self.downTextLabel.Show(statsdisplayflag)
self.upTextLabel.Show(statsdisplayflag)
self.fileDestLabel.Show(statsdisplayflag)
self.fileDestText.Show(statsdisplayflag)
self.colSizer.Layout()
self.downText.SetLabel('') # blank these to flush them
self.upText.SetLabel('')
self.seedStatusText.SetLabel('')
self.peerStatusText.SetLabel('')
ratesettingsmode = self.configfileargs['gui_ratesettingsmode']
ratesettingsflag1 = True # \ settings
ratesettingsflag2 = False # / for 'basic'
if ratesettingsmode == 'none':
ratesettingsflag1 = False
elif ratesettingsmode == 'full':
ratesettingsflag2 = True
self.connChoiceLabel.Show(ratesettingsflag1)
self.connChoice.Show(ratesettingsflag1)
self.rateSpinnerLabel.Show(ratesettingsflag2)
self.rateSpinner.Show(ratesettingsflag2)
self.rateLowerText.Show(ratesettingsflag2)
self.rateUpperText.Show(ratesettingsflag2)
self.rateslider.Show(ratesettingsflag2)
self.connSpinnerLabel.Show(ratesettingsflag2)
self.connSpinner.Show(ratesettingsflag2)
self.connLowerText.Show(ratesettingsflag2)
self.connUpperText.Show(ratesettingsflag2)
self.connslider.Show(ratesettingsflag2)
self.unlimitedLabel.Show(ratesettingsflag2)
self.setgaugemode(None)
self.frame.Layout()
self.frame.Refresh()
self.gui_fractiondone = None
dpflag.set()
def finished(self):
self.fin = True
self.invokeLater(self.onFinishEvent)
def failed(self):
self.fin = True
self.invokeLater(self.onFailEvent)
def error(self, errormsg):
self.invokeLater(self.onErrorEvent, [errormsg])
def onFinishEvent(self):
self.activity = hours(clock() - self.starttime) + ' / ' + \
'Download Succeeded!'
self.cancelButton.SetLabel('Finish')
self.gauge.SetValue(0)
self.frame.SetTitle('{} - Upload - BitTorrent {}'.format(
self.filename, version))
try:
self.frame.SetIcon(self.finicon)
except:
pass
if self.taskbaricon:
self.frame.tbicon.SetIcon(self.finicon, "BitTorrent - Finished")
self.downRateText.SetLabel('')
def onFailEvent(self):
if not self.shuttingdown:
self.timeText.SetLabel(hours(clock() - self.starttime) + ' / ' +
'Failed!')
self.activity = 'Failed!'
self.cancelButton.SetLabel('Close')
self.gauge.SetValue(0)
self.downRateText.SetLabel('')
self.setStatusIcon('startup')
def onErrorEvent(self, errormsg):
# indent at least 2 spaces means a warning message
if errormsg[:2] == ' ':
self.errorText.SetLabel(errormsg)
self.lastError = clock()
else:
self.errorText.SetLabel(time.strftime('ERROR (%x %X) -\n') +
errormsg)
self.lastError = clock()
def chooseFile(self, default, size, saveas, dir):
f = threading.Event()
bucket = [None]
self.invokeLater(self.onChooseFile,
[default, bucket, f, size, dir, saveas])
f.wait()
return bucket[0]
def onChooseFile(self, default, bucket, f, size, dir, saveas):
if saveas == '':
if self.configfileargs['gui_default_savedir'] != '':
start_dir = self.configfileargs['gui_default_savedir']
else:
start_dir = self.configfileargs['last_saved']
if not os.path.isdir(start_dir): # if it's not set properly
start_dir = '/' # yes, this hack does work in Windows
if dir:
start_dir1 = start_dir
if os.path.isdir(os.path.join(start_dir, default)):
start_dir = os.path.join(start_dir, default)
dl = wx.wxDirDialog(
self.frame, 'Choose a directory to save to, pick a '
'partial download to resume', defaultPath=start_dir,
style=wx.wxDD_DEFAULT_STYLE | wx.wxDD_NEW_DIR_BUTTON)
else:
dl = wx.wxFileDialog(
self.frame, 'Choose file to save as, pick a partial '
'download to resume', defaultDir=start_dir,
defaultFile=default, wildcard='*', style=wx.wxSAVE)
if dl.ShowModal() != wx.wxID_OK:
f.set()
self.done(None)
return
d = dl.GetPath()
if d == start_dir:
d = start_dir1
bucket[0] = d
d1, d2 = os.path.split(d)
if d2 == default:
d = d1
self.configfile.WriteLastSaved(d)
else:
bucket[0] = saveas
default = os.path.basename(saveas)
self.onChooseFileDone(default, size)
f.set()
def ChooseFileDone(self, name, size):
self.invokeLater(self.onChooseFileDone, [name, size])
def onChooseFileDone(self, name, size):
self.torrentsize = size
lname = os.path.basename(name)
self.filename = lname
self.fileNameText.SetLabel('%s' % (lname))
self.fileSizeText.SetLabel('(%.2f MiB)' % (float(size) / (1 << 20)))
self.timeText.SetLabel(hours(clock() - self.starttime) + ' / ' +
self.activity)
self.fileDestText.SetLabel(name)
self.frame.SetTitle(lname + '- BitTorrent ' + version)
minsize = self.fileNameText.GetBestSize()
if (not self.configfileargs['gui_stretchwindow'] or
minsize.GetWidth() < self.addwidth):
minsize.SetWidth(self.addwidth)
self.fnsizer.SetMinSize(minsize)
minsize.SetHeight(self.fileSizeText.GetBestSize().GetHeight())
self.fnsizer2.SetMinSize(minsize)
minsize.SetWidth(minsize.GetWidth() + (self.FONT * 8))
minsize.SetHeight(self.fileNameText.GetBestSize().GetHeight() +
self.fileSizeText.GetBestSize().GetHeight())
minsize.SetHeight(2 * self.errorText.GetBestSize().GetHeight())
self.errorTextSizer.SetMinSize(minsize)
self.topboxsizer.SetMinSize(minsize)
# Kludge to make details and about catch the event
self.frame.SetSize((self.frame.GetSizeTuple()[0] + 1,
self.frame.GetSizeTuple()[1] + 1))
self.frame.SetSize((self.frame.GetSizeTuple()[0] - 1,
self.frame.GetSizeTuple()[1] - 1))
self.colSizer.Fit(self.frame)
self.frame.Layout()
self.frame.Refresh()
def newpath(self, path):
self.invokeLater(self.onNewpath, [path])
def onNewpath(self, path):
self.fileDestText.SetLabel(path)
def pause(self, event):
self.invokeLater(self.onPause)
def onPause(self):
if not self.dow:
return
if self.ispaused:
self.ispaused = False
self.pauseButton.SetLabel('Pause')
self.dow.Unpause()
else:
if self.dow.Pause():
self.ispaused = True
self.pauseButton.SetLabel('Resume')
self.downRateText.SetLabel(' ')
self.upRateText.SetLabel(' ')
self.setStatusIcon('startup')
def done(self, event):
self.uiflag.set()
self.flag.set()
self.shuttingdown = True
try:
self.frame.tbicon.RemoveIcon()
except:
pass
try:
self.frame.tbicon.Destroy()
except:
pass
try:
self.detailBox.Close()
except:
self.detailBox = None
try:
self.aboutBox.Close()
except:
self.aboutBox = None
try:
self.creditsBox.Close()
except:
self.creditsBox = None
try:
self.advBox.Close()
except:
self.advBox = None
try:
self.statusIconHelpBox.Close()
except:
self.statusIconHelpBox = None
try:
self.frame.RemoveIcon()
except:
pass
self.frame.Destroy()
def exception(self):
data = StringIO()
traceback.print_exc(file=data)
print data.getvalue() # report exception here too
self.on_errorwindow(data.getvalue())
def errorwindow(self, err):
self.invokeLater(self.on_errorwindow, [err])
def on_errorwindow(self, err):
if self._errorwindow is None:
w = wx.wxFrame(
None, -1, 'BITTORRENT ERROR', size=(1, 1),
style=wx.wxDEFAULT_FRAME_STYLE | wx.wxFULL_REPAINT_ON_RESIZE)
panel = wx.wxPanel(w, -1)
sizer = wx.wxFlexGridSizer(cols=1)
t = ('BitTorrent ' + version + '\n' +
'OS: ' + sys.platform + '\n' +
'Python version: ' + sys.version + '\n' +
'wxWindows version: ' + wx.wxVERSION_STRING + '\n')
try:
t += 'Allocation method: ' + self.config['alloc_type']
if self.dow.storagewrapper.bgalloc_active:
t += '*'
t += '\n'
except:
pass
sizer.Add(wx.wxTextCtrl(panel, -1, t + '\n' + err, size=(500, 300),
style=wx.wxTE_READONLY | wx.wxTE_MULTILINE))
sizer.Add(wx.wxStaticText(panel, -1,
'\nHelp us iron out the bugs in the engine!'))
linkMail = wx.wxStaticText(
panel, -1, 'Please report this error to ' + report_email)
linkMail.SetFont(wx.wxFont(self.FONT, wx.wxDEFAULT, wx.wxNORMAL,
wx.wxNORMAL, True))
linkMail.SetForegroundColour('Blue')
sizer.Add(linkMail)
def maillink(self):
threading.Thread(
target=open_new(
"mailto:{}?subject=autobugreport".format(report_email))
).start()
wx.EVT_LEFT_DOWN(linkMail, maillink)
border = wx.wxBoxSizer(wx.wxHORIZONTAL)
border.Add(sizer, 1, wx.wxEXPAND | wx.wxALL, 4)
panel.SetSizer(border)
panel.SetAutoLayout(True)
w.Show()
border.Fit(panel)
w.Fit()
self._errorwindow = w
class btWxApp(wx.wxApp):
def __init__(self, x, params):
self.params = params
wx.wxApp.__init__(self, x)
def OnInit(self):
doneflag = threading.Event()
self.configfile = configReader()
d = DownloadInfoFrame(doneflag, self.configfile)
self.SetTopWindow(d.frame)
if len(self.params) == 0:
b = wx.wxFileDialog(d.frame, 'Choose .torrent file to use',
defaultDir='', defaultFile='',
wildcard='*.torrent', style=wx.wxOPEN)
if b.ShowModal() == wx.wxID_OK:
self.params.append(b.GetPath())
thread = threading.Thread(
target=next, args=[self.params, d, doneflag, self.configfile])
thread.setDaemon(False)
thread.start()
return 1
def run(params):
if WXPROFILER:
import profile
import pstats
p = profile.Profile()
p.runcall(_run, params)
log_fname = 'profile_data_wx.' + time.strftime('%y%m%d%H%M%S') + '.txt'
with open(log_fname, 'a') as log:
normalstdout, sys.stdout = sys.stdout, log
pstats.Stats(p).strip_dirs().sort_stats('time').print_stats()
sys.stdout = normalstdout
else:
_run(params)
def _run(params):
app = btWxApp(0, params)
app.MainLoop()
def next(params, d, doneflag, configfile):
if PROFILER:
import profile
import pstats
p = profile.Profile()
p.runcall(_next, params, d, doneflag, configfile)
log_fname = 'profile_data.' + time.strftime('%y%m%d%H%M%S') + '.txt'
with open(log_fname, 'a') as log:
normalstdout, sys.stdout = sys.stdout, log
pstats.Stats(p).strip_dirs().sort_stats('time').print_stats()
sys.stdout = normalstdout
else:
_next(params, d, doneflag, configfile)
def _next(params, d, doneflag, configfile):
err = False
try:
while 1:
try:
config = parse_params(params, configfile.config)
except ValueError as e:
d.error('error: ' + str(e) +
'\nrun with no args for parameter explanations')
break
if not config:
d.displayUsage(get_usage(presets=configfile.config))
break
myid = createPeerID()
random.seed(myid)
rawserver = RawServer(doneflag, config['timeout_check_interval'],
config['timeout'],
ipv6_enable=config['ipv6_enabled'],
failfunc=d.error, errorfunc=d.errorwindow)
upnp_type = UPnP_test(config['upnp_nat_access'])
while True:
try:
listen_port = rawserver.find_and_bind(
config['minport'], config['maxport'], config['bind'],
ipv6_socket_style=config['ipv6_binds_v4'],
upnp=upnp_type, randomizer=config['random_port'])
break
except socket.error as e:
if upnp_type and e == UPnP_ERROR:
d.error('WARNING: COULD NOT FORWARD VIA UPnP')
upnp_type = 0
continue
d.error("Couldn't listen - " + str(e))
d.failed()
return
d.connection_stats = rawserver.get_stats()
response = get_response(config['responsefile'], config['url'],
d.error)
if not response:
break
infohash = hashlib.sha1(bencode(response['info'])).digest()
torrentdata = configfile.getTorrentData(infohash)
if torrentdata:
oldsave = torrentdata.get('saved as')
d.old_ratesettings = torrentdata.get('rate settings')
s = torrentdata.get('stats')
if s:
d.old_upload = s['uploaded']
d.old_download = s['downloaded']
else:
oldsave = None
dow = BT1Download(
d.updateStatus, d.finished, d.error, d.errorwindow, doneflag,
config, response, infohash, myid, rawserver, listen_port,
configfile.getConfigDir())
d.dow = dow
if config['gui_saveas_ask'] == 1:
oldsave = None
if oldsave:
if not dow.checkSaveLocation(oldsave):
oldsave = None
if oldsave:
def choosefile(default, size, saveas, dir, oldsave=oldsave):
d.ChooseFileDone(oldsave, size)
return oldsave
elif config['gui_saveas_ask'] == 0:
def choosefile(default, size, saveas, dir,
spot=config['gui_default_savedir']):
spot = os.path.join(spot, default)
d.ChooseFileDone(spot, size)
return spot
else:
choosefile = d.chooseFile
savedas = dow.saveAs(choosefile, d.newpath)
if not savedas:
break
if not dow.initFiles(old_style=True):
break
if not dow.startEngine():
dow.shutdown()
break
dow.startRerequester()
dow.autoStats()
if not dow.am_I_finished():
d.updateStatus(activity='connecting to peers')
rawserver.listen_forever(dow.getPortHandler())
ratesettings = {
'rate setting': d.current_ratesetting,
'max download rate': config['max_download_rate']
}
if d.current_ratesetting != 'automatic':
ratesettings['uploads'] = config['min_uploads']
ratesettings['max upload rate'] = config['max_upload_rate']
up, dn = dow.get_transfer_stats()
stats = {
'uploaded': up + d.old_upload,
'downloaded': dn + d.old_download
}
torrentdata = {
'saved as': savedas,
'rate settings': ratesettings,
'stats': stats
}
dow.shutdown(torrentdata)
break
except:
err = True
data = StringIO()
traceback.print_exc(file=data)
print data.getvalue() # report exception here too
d.errorwindow(data.getvalue())
try:
rawserver.shutdown()
except:
pass
if not d.fin:
d.failed()
if err:
# this will make the app stick in the task manager, but so be it
time.sleep(3600 * 24 * 30)
if __name__ == '__main__':
if sys.argv[1:] == ['--version']:
print version
sys.exit(0)
run(sys.argv[1:])
|
tests.py | """
// TODO: Write tests for retry_async
// TODO: Custom Viewer for Manhwa and Manhua
// TODO: redux integration
// TODO: Drive refresh every 35 minutes
// TODO: Mongo db implementation
TODO: async.run_in_exector for drive uploads.
TODO: site revamp
TODO: httpobject for drive auth
TODO: Add support for multiple sites
"""
# import os
# import requests
# import json
# from dotenv import load_dotenv
# import io
# load_dotenv()
# from config import get_drive_service, public_put_file_to_folder_resumable, public_get_document_view_url
# bytesO = "haha"
# bytesO = bytes(bytesO.encode())
# print(len(bytesO))
# folder_id = os.environ.get("DATA_FOLDER_ID")
# file_name = "tmp.txt"
# drive, gauth = get_drive_service()
# _id = public_put_file_to_folder_resumable(drive, file_name, "text/plain", folder_id)
# print(public_get_document_view_url(_id))
# import logging
# logging.getLogger().setLevel(logging.INFO)
# from asyncio_blocks import Google_Drive
# ACCOUNT_SECRETS = os.environ.get("ACCOUNT_SECRETS")
# parent_id = os.environ.get("DATA_FOLDER_ID")
# from gdrive import Google_Drive
# Google_Drive.init(ACCOUNT_SECRETS)
# with open("spider/res/1/2.jpg", 'rb') as f:
# file = io.BytesIO(f.read())
# file_id = Google_Drive.create_file("3.jpg", parent_id, file, "image/jpeg")
# logging.info(Google_Drive.get_public_url_file(file_id))
# # Google_Drive.delete_file(file_id)
# import pprint
# pp = pprint.PrettyPrinter(indent=6)
# pp.pprint(Google_Drive.find_file_by_id(file_id))
# for i in Google_Drive.get_file_list():
# pp.pprint(i['title'])
# import json
# import os
# import sys
# sys.path.append("../")
# from gdrive.gdrive import Google_Drive
# from dotenv import load_dotenv
# load_dotenv("../.env")
# ACCOUNT_SECRETS = "../" + os.environ.get("ACCOUNT_SECRETS")
# PARENT_FOLDER_ID = os.environ.get("DATA_FOLDER_ID")
# with open("res.json", 'r') as f:
# res = f.read()
# import io
# res = io.BytesIO(res.encode())
from asyncio import tasks
from concurrent import futures
from concurrent.futures import thread
import json
import os
import requests
from dotenv import load_dotenv
from gdrive import Google_Drive
from main import METADATA_JSON, PARENT_FOLDER_ID
load_dotenv()
ACCOUNT_SECRETS = os.environ.get("ACCOUNT_SECRETS")
PARENT_FOLDER_ID = os.environ.get("DATA_FOLDER_ID")
METADATA_JSON = os.environ.get("METADATA_JSON")
Google_Drive.init(ACCOUNT_SECRETS)
# k = Google_Drive.download_json_file(METADATA_JSON)
# del k['hi']
# k = json.dumps(k, indent=6)
# Google_Drive.update_json_file(METADATA_JSON, k)
# print(Google_Drive.drive)
# import io
# import gc
# def hi():
# f = io.BytesIO()
# f.write(b"haha")
# print(gc.collect())
# --------------------------------------------------------------------------------
# print(Google_Drive.get_public_url_file(METADATA_JSON))
# k = Google_Drive.download_json_file(METADATA_JSON)
# updated = {}
# for i in k:
# updated[Google_Drive.get_public_url_file(i)] = k[i]
# Google_Drive.update_json_file(METADATA_JSON, json.dumps(updated, indent=6))
# k = requests.get(Google_Drive.get_public_url_file(METADATA_JSON))
# print(json.loads(k.text))
#----------------------------------------------------------------------------------
# meta = Google_Drive.download_json_file(METADATA_JSON)
# for i in meta:
# if i == "1DTtLO3BMZ51EdSrHQ78V9NjcMrf2FDwx": continue
# g = Google_Drive.download_json_file(i)
# for chap in g:
# del chap["images"]
# out = {
# "title": meta[i],
# "num_chapters": len(g),
# "chapters": g,
# }
# Google_Drive.update_json_file(i, json.dumps(out, indent=6))
#----------------------------------------------------------------------------------
# j = Google_Drive.download_json_file("13iEugdhj_3MMsYOMpIKXQ4qNixsw1jg9")
# j = j["chapters"]
# assert isinstance(j, dict)
# Google_Drive.update_json_file("13iEugdhj_3MMsYOMpIKXQ4qNixsw1jg9", json.dumps(j, indent=6))
#----------------------------------------------------------------------------------
import asyncio
import aiohttp
class N_Flawed_Async:
@staticmethod
async def request():
return requests.get("https://www.google.com")
@staticmethod
async def req_all():
tasks = []
for i in range(10):
task = asyncio.ensure_future(N_Flawed_Async.request())
tasks.append(task)
return await asyncio.gather(*tasks)
@staticmethod
def req_all_s():
tasks = []
for i in range(10):
tasks.append(requests.get("https://www.google.com"))
return tasks
@staticmethod
def req_all_p():
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(N_Flawed_Async.req_all())
loop.run_until_complete(future)
return future.result()
class N_Correct_Async:
@staticmethod
def req():
return requests.get("https://www.google.com").status_code
@staticmethod
async def req_all_p():
loop = asyncio.get_event_loop()
tasks = []
for i in range(1000):
task = loop.run_in_executor(
None, N_Correct_Async.req
) #Should be a Self-Contained function, which is blocking the asyncio event loop
tasks.append(task)
return await asyncio.gather(*tasks)
@staticmethod
def req_all_p_executor():
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(N_Correct_Async.req_all_p())
loop.run_until_complete(future)
return future.result()
class N_Aoihttp_async:
@staticmethod
async def req(session):
async with session.get("https://www.google.com",
timeout=25) as response:
return response.status
@staticmethod
async def req_all_aiohttp():
tasks = []
async with aiohttp.ClientSession() as session:
for i in range(10):
task = asyncio.ensure_future(N_Aoihttp_async.req(session))
tasks.append(task)
return await asyncio.gather(*tasks)
@staticmethod
def req_all_aiohttp_executor():
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(N_Aoihttp_async.req_all_aiohttp())
loop.run_until_complete(future)
return future.result()
# print(N_Flawed_Async.req_all_p())
# print(N_Correct_Async.req_all_p_executor())
# print(N_Aoihttp_async.req_all_aiohttp_executor())
#----------------------------------------------------------------------------------
from utils import retry, retry_async
# @retry(method="dummy content", max_retries=3, delay=0.1)
# def dummy(_type=""):
# print("Success")
# dummy(_type="Content")
# print()
# dummy(_type="Image")
#----------------------------------------------------------------------------------
import time
import threading
t = 0
res = 0
def tick():
global t
while True:
time.sleep(1)
print(t, end="\t", flush=True)
t += 1
@retry_async("dummy", max_retries=5, delay=1)
async def test_retry_async():
global res
res += 1
if res > 5:
print("Success")
else:
print("Failed")
raise Exception("Failed")
# x = threading.Thread(target=tick)
# x.start()
# task = asyncio.ensure_future(test_retry_async())
# asyncio.get_event_loop().run_until_complete(task)
# print(task.result())
#----------------------------------------------------------------------------------
# import time
# k = time.monotonic()
# print(time.time())
# print(time.monotonic())
# time.sleep(1)
# print(time.time_ns())
# print(time.monotonic_ns())
# print(time.monotonic() - k)
#---------------------------------------------------------------------------------- |
onnxruntime_test_python.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# -*- coding: UTF-8 -*-
import unittest
import os
import numpy as np
import onnxruntime as onnxrt
import threading
class TestInferenceSession(unittest.TestCase):
def get_name(self, name):
if os.path.exists(name):
return name
rel = os.path.join("testdata", name)
if os.path.exists(rel):
return rel
this = os.path.dirname(__file__)
data = os.path.join(this, "..", "testdata")
res = os.path.join(data, name)
if os.path.exists(res):
return res
raise FileNotFoundError("Unable to find '{0}' or '{1}' or '{2}'".format(name, rel, res))
def run_model(self, session_object, run_options):
x = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32)
input_name = session_object.get_inputs()[0].name
res = session_object.run([], {input_name: x}, run_options=run_options)
output_expected = np.array([[1.0, 4.0], [9.0, 16.0], [25.0, 36.0]], dtype=np.float32)
np.testing.assert_allclose(output_expected, res[0], rtol=1e-05, atol=1e-08)
def testRunModel(self):
sess = onnxrt.InferenceSession(self.get_name("mul_1.onnx"))
x = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32)
input_name = sess.get_inputs()[0].name
self.assertEqual(input_name, "X")
input_shape = sess.get_inputs()[0].shape
self.assertEqual(input_shape, [3, 2])
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "Y")
output_shape = sess.get_outputs()[0].shape
self.assertEqual(output_shape, [3, 2])
res = sess.run([output_name], {input_name: x})
output_expected = np.array([[1.0, 4.0], [9.0, 16.0], [25.0, 36.0]], dtype=np.float32)
np.testing.assert_allclose(output_expected, res[0], rtol=1e-05, atol=1e-08)
def testRunModelFromBytes(self):
with open(self.get_name("mul_1.onnx"), "rb") as f:
content = f.read()
sess = onnxrt.InferenceSession(content)
x = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32)
input_name = sess.get_inputs()[0].name
self.assertEqual(input_name, "X")
input_shape = sess.get_inputs()[0].shape
self.assertEqual(input_shape, [3, 2])
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "Y")
output_shape = sess.get_outputs()[0].shape
self.assertEqual(output_shape, [3, 2])
res = sess.run([output_name], {input_name: x})
output_expected = np.array([[1.0, 4.0], [9.0, 16.0], [25.0, 36.0]], dtype=np.float32)
np.testing.assert_allclose(output_expected, res[0], rtol=1e-05, atol=1e-08)
def testRunModel2(self):
sess = onnxrt.InferenceSession(self.get_name("matmul_1.onnx"))
x = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32)
input_name = sess.get_inputs()[0].name
self.assertEqual(input_name, "X")
input_shape = sess.get_inputs()[0].shape
self.assertEqual(input_shape, [3, 2])
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "Y")
output_shape = sess.get_outputs()[0].shape
self.assertEqual(output_shape, [3, 1])
res = sess.run([output_name], {input_name: x})
output_expected = np.array([[5.0], [11.0], [17.0]], dtype=np.float32)
np.testing.assert_allclose(output_expected, res[0], rtol=1e-05, atol=1e-08)
def testRunModelMultipleThreads(self):
so = onnxrt.SessionOptions()
so.session_log_verbosity_level = 1
so.session_logid = "MultiThreadsTest"
sess = onnxrt.InferenceSession(self.get_name("mul_1.onnx"), sess_options=so)
ro1 = onnxrt.RunOptions()
ro1.run_tag = "thread1"
t1 = threading.Thread(target=self.run_model, args = (sess, ro1))
ro2 = onnxrt.RunOptions()
ro2.run_tag = "thread2"
t2 = threading.Thread(target=self.run_model, args = (sess, ro2))
t1.start()
t2.start()
t1.join()
t2.join()
def testRunDevice(self):
device = onnxrt.get_device()
self.assertTrue('CPU' in device or 'GPU' in device)
def testRunModelSymbolicInput(self):
sess = onnxrt.InferenceSession(self.get_name("matmul_2.onnx"))
x = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32)
input_name = sess.get_inputs()[0].name
self.assertEqual(input_name, "X")
input_shape = sess.get_inputs()[0].shape
# Input X has an unknown dimension.
self.assertEqual(input_shape, [None, 2])
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "Y")
output_shape = sess.get_outputs()[0].shape
# Output X has an unknown dimension.
self.assertEqual(output_shape, [None, 1])
res = sess.run([output_name], {input_name: x})
output_expected = np.array([[5.0], [11.0], [17.0]], dtype=np.float32)
np.testing.assert_allclose(output_expected, res[0], rtol=1e-05, atol=1e-08)
def testBooleanInputs(self):
sess = onnxrt.InferenceSession(self.get_name("logicaland.onnx"))
a = np.array([[True, True], [False, False]], dtype=np.bool)
b = np.array([[True, False], [True, False]], dtype=np.bool)
# input1:0 is first in the protobuf, and input:0 is second
# and we maintain the original order.
a_name = sess.get_inputs()[0].name
self.assertEqual(a_name, "input1:0")
a_shape = sess.get_inputs()[0].shape
self.assertEqual(a_shape, [2, 2])
a_type = sess.get_inputs()[0].type
self.assertEqual(a_type, 'tensor(bool)')
b_name = sess.get_inputs()[1].name
self.assertEqual(b_name, "input:0")
b_shape = sess.get_inputs()[1].shape
self.assertEqual(b_shape, [2, 2])
b_type = sess.get_inputs()[0].type
self.assertEqual(b_type, 'tensor(bool)')
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "output:0")
output_shape = sess.get_outputs()[0].shape
self.assertEqual(output_shape, [2, 2])
output_type = sess.get_outputs()[0].type
self.assertEqual(output_type, 'tensor(bool)')
output_expected = np.array([[True, False], [False, False]], dtype=np.bool)
res = sess.run([output_name], {a_name: a, b_name: b})
np.testing.assert_equal(output_expected, res[0])
def testStringInput1(self):
sess = onnxrt.InferenceSession(self.get_name("identity_string.onnx"))
x = np.array(['this', 'is', 'identity', 'test'], dtype=np.str).reshape((2,2))
x_name = sess.get_inputs()[0].name
self.assertEqual(x_name, "input:0")
x_shape = sess.get_inputs()[0].shape
self.assertEqual(x_shape, [2, 2])
x_type = sess.get_inputs()[0].type
self.assertEqual(x_type, 'tensor(string)')
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "output:0")
output_shape = sess.get_outputs()[0].shape
self.assertEqual(output_shape, [2, 2])
output_type = sess.get_outputs()[0].type
self.assertEqual(output_type, 'tensor(string)')
res = sess.run([output_name], {x_name: x})
np.testing.assert_equal(x, res[0])
def testStringInput2(self):
sess = onnxrt.InferenceSession(self.get_name("identity_string.onnx"))
x = np.array(['Olá', '你好', '여보세요', 'hello'], dtype=np.unicode).reshape((2,2))
x_name = sess.get_inputs()[0].name
self.assertEqual(x_name, "input:0")
x_shape = sess.get_inputs()[0].shape
self.assertEqual(x_shape, [2, 2])
x_type = sess.get_inputs()[0].type
self.assertEqual(x_type, 'tensor(string)')
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "output:0")
output_shape = sess.get_outputs()[0].shape
self.assertEqual(output_shape, [2, 2])
output_type = sess.get_outputs()[0].type
self.assertEqual(output_type, 'tensor(string)')
res = sess.run([output_name], {x_name: x})
np.testing.assert_equal(x, res[0])
def testInputBytes(self):
sess = onnxrt.InferenceSession(self.get_name("identity_string.onnx"))
x = np.array([b'this', b'is', b'identity', b'test']).reshape((2,2))
x_name = sess.get_inputs()[0].name
self.assertEqual(x_name, "input:0")
x_shape = sess.get_inputs()[0].shape
self.assertEqual(x_shape, [2, 2])
x_type = sess.get_inputs()[0].type
self.assertEqual(x_type, 'tensor(string)')
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "output:0")
output_shape = sess.get_outputs()[0].shape
self.assertEqual(output_shape, [2, 2])
output_type = sess.get_outputs()[0].type
self.assertEqual(output_type, 'tensor(string)')
res = sess.run([output_name], {x_name: x})
np.testing.assert_equal(x, res[0].astype('|S8'))
def testInputObject(self):
sess = onnxrt.InferenceSession(self.get_name("identity_string.onnx"))
x = np.array(['this', 'is', 'identity', 'test'], object).reshape((2,2))
x_name = sess.get_inputs()[0].name
self.assertEqual(x_name, "input:0")
x_shape = sess.get_inputs()[0].shape
self.assertEqual(x_shape, [2, 2])
x_type = sess.get_inputs()[0].type
self.assertEqual(x_type, 'tensor(string)')
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "output:0")
output_shape = sess.get_outputs()[0].shape
self.assertEqual(output_shape, [2, 2])
output_type = sess.get_outputs()[0].type
self.assertEqual(output_type, 'tensor(string)')
res = sess.run([output_name], {x_name: x})
np.testing.assert_equal(x, res[0])
def testInputVoid(self):
sess = onnxrt.InferenceSession(self.get_name("identity_string.onnx"))
x = np.array([b'this', b'is', b'identity', b'test'], np.void).reshape((2,2))
x_name = sess.get_inputs()[0].name
self.assertEqual(x_name, "input:0")
x_shape = sess.get_inputs()[0].shape
self.assertEqual(x_shape, [2, 2])
x_type = sess.get_inputs()[0].type
self.assertEqual(x_type, 'tensor(string)')
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "output:0")
output_shape = sess.get_outputs()[0].shape
self.assertEqual(output_shape, [2, 2])
output_type = sess.get_outputs()[0].type
self.assertEqual(output_type, 'tensor(string)')
res = sess.run([output_name], {x_name: x})
expr = np.array([['this\x00\x00\x00\x00', 'is\x00\x00\x00\x00\x00\x00'],
['identity', 'test\x00\x00\x00\x00']], dtype=object)
np.testing.assert_equal(expr, res[0])
def testConvAutoPad(self):
sess = onnxrt.InferenceSession(self.get_name("conv_autopad.onnx"))
x = np.array(25 * [1.0], dtype=np.float32).reshape((1,1,5,5))
x_name = sess.get_inputs()[0].name
self.assertEqual(x_name, "Input4")
x_shape = sess.get_inputs()[0].shape
self.assertEqual(x_shape, [1, 1, 5, 5])
x_type = sess.get_inputs()[0].type
self.assertEqual(x_type, 'tensor(float)')
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "Convolution5_Output_0")
output_shape = sess.get_outputs()[0].shape
self.assertEqual(output_shape, [1, 1, 5, 5])
output_type = sess.get_outputs()[0].type
self.assertEqual(output_type, 'tensor(float)')
res = sess.run([output_name], {x_name: x})
output_expected = np.array([[[[24., 33., 33., 33., 20.],
[27., 36., 36., 36., 21.],
[27., 36., 36., 36., 21.],
[27., 36., 36., 36., 21.],
[12., 15., 15., 15., 8.]]]], dtype=np.float32)
np.testing.assert_allclose(output_expected, res[0])
def testZipMapStringFloat(self):
sess = onnxrt.InferenceSession(self.get_name("zipmap_stringfloat.onnx"))
x = np.array([1.0, 0.0, 3.0, 44.0, 23.0, 11.0], dtype=np.float32).reshape((2,3))
x_name = sess.get_inputs()[0].name
self.assertEqual(x_name, "X")
x_type = sess.get_inputs()[0].type
self.assertEqual(x_type, 'tensor(float)')
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "Z")
output_type = sess.get_outputs()[0].type
self.assertEqual(output_type, 'seq(map(string,tensor(float)))')
output_expected = [{'class2': 0.0, 'class1': 1.0, 'class3': 3.0},
{'class2': 23.0, 'class1': 44.0, 'class3': 11.0}]
res = sess.run([output_name], {x_name: x})
self.assertEqual(output_expected, res[0])
def testZipMapInt64Float(self):
sess = onnxrt.InferenceSession(self.get_name("zipmap_int64float.onnx"))
x = np.array([1.0, 0.0, 3.0, 44.0, 23.0, 11.0], dtype=np.float32).reshape((2,3))
x_name = sess.get_inputs()[0].name
self.assertEqual(x_name, "X")
x_type = sess.get_inputs()[0].type
self.assertEqual(x_type, 'tensor(float)')
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "Z")
output_type = sess.get_outputs()[0].type
self.assertEqual(output_type, 'seq(map(int64,tensor(float)))')
output_expected = [{10: 1.0, 20: 0.0, 30: 3.0}, {10: 44.0, 20: 23.0, 30: 11.0}]
res = sess.run([output_name], {x_name: x})
self.assertEqual(output_expected, res[0])
def testRaiseWrongNumInputs(self):
with self.assertRaises(ValueError) as context:
sess = onnxrt.InferenceSession(self.get_name("logicaland.onnx"))
a = np.array([[True, True], [False, False]], dtype=np.bool)
res = sess.run([], {'input:0': a})
self.assertTrue('Model requires 2 inputs' in str(context.exception))
def testModelMeta(self):
model_path = "../models/opset8/test_squeezenet/model.onnx"
if not os.path.exists(model_path):
return
sess = onnxrt.InferenceSession(model_path)
modelmeta = sess.get_modelmeta()
self.assertEqual('onnx-caffe2', modelmeta.producer_name)
self.assertEqual('squeezenet_old', modelmeta.graph_name)
self.assertEqual('', modelmeta.domain)
self.assertEqual('', modelmeta.description)
def testProfilerWithSessionOptions(self):
so = onnxrt.SessionOptions()
so.enable_profiling = True
sess = onnxrt.InferenceSession(self.get_name("mul_1.onnx"), sess_options=so)
x = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32)
sess.run([], {'X': x})
profile_file = sess.end_profiling()
tags = ['pid', 'dur', 'ts', 'ph', 'X', 'name', 'args']
with open(profile_file) as f:
lines = f.readlines()
self.assertTrue('[' in lines[0])
for i in range(1, 8):
for tag in tags:
self.assertTrue(tag in lines[i])
self.assertTrue(']' in lines[8])
def testDictVectorizer(self):
sess = onnxrt.InferenceSession(self.get_name("pipeline_vectorize.onnx"))
input_name = sess.get_inputs()[0].name
self.assertEqual(input_name, "float_input")
input_type = str(sess.get_inputs()[0].type)
self.assertEqual(input_type, "map(int64,tensor(float))")
input_shape = sess.get_inputs()[0].shape
self.assertEqual(input_shape, [])
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "variable1")
output_type = sess.get_outputs()[0].type
self.assertEqual(output_type, "tensor(float)")
output_shape = sess.get_outputs()[0].shape
self.assertEqual(output_shape, [1, 1])
# Python type
x = {0: 25.0, 1: 5.13, 2: 0.0, 3: 0.453, 4: 5.966}
res = sess.run([output_name], {input_name: x})
output_expected = np.array([[49.752754]], dtype=np.float32)
np.testing.assert_allclose(output_expected, res[0], rtol=1e-05, atol=1e-08)
xwrong = x.copy()
xwrong["a"] = 5.6
try:
res = sess.run([output_name], {input_name: xwrong})
except RuntimeError as e:
self.assertIn("Unexpected key type <class 'str'>, it cannot be linked to C type int64_t", str(e))
# numpy type
x = {np.int64(k): np.float32(v) for k, v in x.items()}
res = sess.run([output_name], {input_name: x})
output_expected = np.array([[49.752754]], dtype=np.float32)
np.testing.assert_allclose(output_expected, res[0], rtol=1e-05, atol=1e-08)
x = {np.int64(k): np.float64(v) for k, v in x.items()}
res = sess.run([output_name], {input_name: x})
output_expected = np.array([[49.752754]], dtype=np.float32)
np.testing.assert_allclose(output_expected, res[0], rtol=1e-05, atol=1e-08)
x = {np.int32(k): np.float64(v) for k, v in x.items()}
res = sess.run([output_name], {input_name: x})
output_expected = np.array([[49.752754]], dtype=np.float32)
np.testing.assert_allclose(output_expected, res[0], rtol=1e-05, atol=1e-08)
def testLabelEncoder(self):
sess = onnxrt.InferenceSession(self.get_name("LabelEncoder.onnx"))
input_name = sess.get_inputs()[0].name
self.assertEqual(input_name, "input")
input_type = str(sess.get_inputs()[0].type)
self.assertEqual(input_type, "tensor(string)")
input_shape = sess.get_inputs()[0].shape
self.assertEqual(input_shape, [1, 1])
output_name = sess.get_outputs()[0].name
self.assertEqual(output_name, "variable")
output_type = sess.get_outputs()[0].type
self.assertEqual(output_type, "tensor(int64)")
output_shape = sess.get_outputs()[0].shape
self.assertEqual(output_shape, [1, 1])
# Array
x = np.array([['4']])
res = sess.run([output_name], {input_name: x})
output_expected = np.array([[3]], dtype=np.int64)
np.testing.assert_allclose(output_expected, res[0], rtol=1e-05, atol=1e-08)
# Python type
x = np.array(['4'])
res = sess.run([output_name], {input_name: x})
output_expected = np.array([3], dtype=np.int64)
np.testing.assert_allclose(output_expected, res[0], rtol=1e-05, atol=1e-08)
x = np.array(['4'], dtype=np.object)
res = sess.run([output_name], {input_name: x})
output_expected = np.array([3], dtype=np.int64)
np.testing.assert_allclose(output_expected, res[0], rtol=1e-05, atol=1e-08)
def test_run_model_mlnet(self):
sess = onnxrt.InferenceSession(self.get_name("mlnet_encoder.onnx"))
names = [_.name for _ in sess.get_outputs()]
self.assertEqual(['C00', 'C12'], names)
c0 = np.array([5.], dtype=np.float32).reshape(1, 1);
c1 = np.array([b'A\0A\0', b"B\0B\0", b"C\0C\0"], np.void).reshape(1, 3)
res = sess.run(None, {'C0': c0, 'C1': c1})
mat = res[1]
total = mat.sum()
self.assertEqual(total, 2)
self.assertEqual(list(mat.ravel()),
list(np.array([[[0., 0., 0., 0.], [1., 0., 0., 0.], [0., 0., 1., 0.]]]).ravel()))
# In memory, the size of each element is fixed and equal to the
# longest element. We cannot use bytes because numpy is trimming
# every final 0 for strings and bytes before creating the array
# (to save space). It does not have this behaviour for void
# but as a result, numpy does not know anymore the size
# of each element, they all have the same size.
c1 = np.array([b'A\0A\0\0', b"B\0B\0", b"C\0C\0"], np.void).reshape(1, 3)
res = sess.run(None, {'C0': c0, 'C1': c1})
mat = res[1]
total = mat.sum()
self.assertEqual(total, 0)
if __name__ == '__main__':
unittest.main()
|
flask_web.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from threading import Thread
from flask import Flask
from flask import flash
from flask import redirect, render_template, url_for, session
from flask_bootstrap import Bootstrap
from flask_mail import Mail, Message
from flask_migrate import Migrate, MigrateCommand
from flask_moment import Moment
from flask_script import Manager, Shell
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from app import keys
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
#数据库配置
app.config['SQLALCHEMY_DATABASE_URI'] =\
'sqlite:///' + os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
#email配置
app.config['MAIL_SERVER'] = keys.MAIL_SERVER
app.config['MAIL_PORT'] = keys.MAIL_PORT
app.config['MAIL_USE_TLS'] = keys.MAIL_USE_TLS
app.config['MAIL_USERNAME'] = keys.MAIL_USERNAME
app.config['MAIL_PASSWORD'] = keys.MAIL_PASSWORD
app.config['MAIL_SENDER'] = keys.MAIL_USERNAME
app.config['MAIL_SUBJECT_PREFIX'] = '[Flask Send]'
app.config['ADMIN'] = keys.ADMIN
db = SQLAlchemy(app) #配置数据库
bootstrap = Bootstrap(app) #配置模板
moment = Moment(app) #配置时间
manager = Manager(app)
migrate = Migrate(app,db) #数据库迁移
mail = Mail(app) #配置邮件
manager.add_command('db',MigrateCommand)
@app.route('/',methods=['GET','POST'])
def index():
form = NameForm()
if form.validate_on_submit():
old_name = session.get('name',None)
new_name = form.name.data
user = User.query.filter_by(username=new_name).first()
#检查数据库中的记录
if user is None:
user = User(username=new_name)
db.session.add(user)
db.session.commit()
session['known'] = False
if app.config['ADMIN']:
send_mail(app.config['ADMIN'],'New user register',
'mail/new_user',user=user)
else:
session['known'] = True
#检查name是否改变
if old_name is not None and old_name != new_name:
flash("You have changed your name")
session['name'] = new_name
return redirect(url_for('index'))
return render_template('index.html',form=form,
name=session.get('name',None),
known = session.get('known',False))
@app.route('/user/<name>')
def user(name):
return render_template('base.html',name=name)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'),404
@app.errorhandler(500)
def internal_sercer_error(e):
return render_template('500.html'),500
#web表单
class NameForm(FlaskForm):
name = StringField("What's your name?",validators=[Required()])
submit = SubmitField('Submit')
#ORM数据表
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role', lazy='dynamic')
def __repr__(self):
return '<Role %r>' % self.name
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
def __repr__(self):
return '<User %r>' % self.username
#导入数据库实例及模型
def make_shell_context():
return dict(app=app,db=db,Role=Role,User=User)
#电子邮件支持
def async_send_mail(app,msg):
with app.app_context():
mail.send(msg)
def send_mail(to,subject,template,**kwargs):
msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + subject,
sender=app.config['MAIL_SENDER'],recipients=[to])
msg.body = render_template(template+'.txt',**kwargs)
msg.html = render_template(template+'.html',**kwargs)
th = Thread(target=async_send_mail,args=(app,msg))
th.start()
return th
manager.add_command("shell",Shell(make_context=make_shell_context)) #导入数据库
manager.add_command("db",MigrateCommand)
if __name__ == '__main__':
# manager.run()
app.run(debug=True)
|
pi_controller.py | import os
import time
import traceback
import sys
from datetime import date, datetime
from tanager_tcp.tanager_server import TanagerServer
from tanager_tcp.tanager_client import TanagerClient
from threading import Thread
from pi_feeder import goniometer
INTERVAL = 0.25
CONFIG_LOC = os.path.join(os.path.expanduser("~"), ".tanager_config")
ENCODER_CONFIG_PATH = os.path.join(CONFIG_LOC, "encoder_config.txt")
AZ_CONFIG_PATH = os.path.join(CONFIG_LOC, "az_config.txt")
LOG_PATH = os.path.join(CONFIG_LOC, "pi_feeder")
def main():
if not os.path.isdir(CONFIG_LOC):
os.mkdir(CONFIG_LOC)
today = date.today()
now = today.strftime("%b-%d-%Y")
now += f"_{datetime.now().hour}_{datetime.now().minute}"
log_path = f"{LOG_PATH}_{now}.log"
sys.stdout = open(log_path, "w+")
pi_controller = PiController()
pi_controller.listen()
class PiController:
def __init__(self):
try:
with open(ENCODER_CONFIG_PATH, "r") as config_file:
i_zero = float(config_file.readline())
e_zero = float(config_file.readline())
az_zero = float(config_file.readline())
tray_zero = float(config_file.readline())
self.goniometer = goniometer.Goniometer(i_zero, e_zero, az_zero, tray_zero)
except (FileNotFoundError, NotADirectoryError):
dir_path = os.path.split(ENCODER_CONFIG_PATH)[0]
print(f"Encoder config file not found, creating new one at {ENCODER_CONFIG_PATH}")
if not os.path.isdir(dir_path):
os.mkdir(dir_path)
self.write_encoder_config(0, 0, 0, 0)
self.goniometer = goniometer.Goniometer()
current_az = 0
try:
with open(AZ_CONFIG_PATH, "r") as config_file:
current_az = float(config_file.readline())
except (FileNotFoundError, NotADirectoryError):
dir_path = os.path.split(AZ_CONFIG_PATH)[0]
print(f"Az config file not found, creating new one at {AZ_CONFIG_PATH}")
if not os.path.isdir(dir_path):
os.mkdir(dir_path)
self.write_az_config(0)
print("Homing azimuth")
self.goniometer.home_azimuth()
print(f"Setting to last known azimuth: {current_az}")
self.goniometer.set_position("azimuth", current_az)
self.cmdfiles0 = []
self.dir = "forward"
self.server = TanagerServer(12345)
self.client = TanagerClient(self.server.remote_server_address, 12345)
thread = Thread(target=self.server.listen)
thread.start()
def listen(self):
while True:
try:
self._listen()
except:
traceback.print_exc()
def _listen(self):
print("listening!")
t = 0
while True:
while len(self.server.queue) > 0:
if self.server.remote_server_address != self.client.server_address:
print("Setting control computer address:")
self.client.server_address = self.server.remote_server_address
print(self.client.server_address)
message = self.server.queue.pop(0)
cmd, params = self.decrypt(message)
for x in range(10):
cmd = cmd.replace(str(x), "")
if cmd != "test":
print(cmd)
if cmd == "movetray":
if "steps" in params:
steps = int(params[0])
self.goniometer.motors["sample tray"]["motor"].move_steps(steps)
filename = self.encrypt("donemovingtray")
else:
status = self.goniometer.set_position("sample tray", params[0])
if status["complete"]:
filename = self.encrypt("donemovingtray")
else:
filename = self.encrypt("failuremovingtray" + str(int(status["position"])))
self.send(filename)
elif cmd == "moveemission":
if "steps" in params:
steps = int(params[0])
self.goniometer.motors["emission"]["motor"].move_steps(steps)
filename = self.encrypt("donemovingemission")
else:
if self.goniometer.emission == None:
filename = self.encrypt("nopiconfig")
else:
status = self.goniometer.set_position("emission", int(params[0]))
if status["complete"]:
filename = self.encrypt("donemovingemission")
else:
filename = self.encrypt("failuremovingemission" + str(int(status["position"])))
self.send(filename)
elif cmd == "moveincidence":
if "steps" in params:
steps = int(params[0])
self.goniometer.motors["incidence"]["motor"].move_steps(steps)
filename = self.encrypt("donemovingincidence")
else:
if self.goniometer.incidence == None:
filename = self.encrypt("nopiconfig")
else:
status = self.goniometer.set_position("incidence", int(params[0]))
if status["complete"]:
filename = self.encrypt("donemovingincidence")
else:
filename = self.encrypt("failuremovingincidence" + str(status["position"]))
self.send(filename)
elif cmd == "moveazimuth":
if "steps" in params:
steps = int(params[0])
self.goniometer.motors["azimuth"]["motor"].move_steps(steps)
filename = self.encrypt("donemovingazimuth")
if self.goniometer.azimuth == None:
filename = self.encrypt("nopiconfig")
else:
status = self.goniometer.set_position("azimuth", int(params[0]))
filename = self.encrypt("donemovingazimuth" + str(int(status["position"])))
print("Writing az config")
self.write_az_config(self.goniometer.azimuth)
self.send(filename)
elif cmd == "configure":
if params[2].upper() == "WR":
params[2] = -1
self.goniometer.configure(float(params[0]), float(params[1]), int(params[2]))
self.write_encoder_config(
self.goniometer.motors["incidence"]["motor"].encoder._zero_position,
self.goniometer.motors["emission"]["motor"].encoder._zero_position,
self.goniometer.motors["azimuth"]["motor"].encoder._zero_position,
self.goniometer.motors["sample tray"]["motor"].encoder._zero_position,
)
filename = self.encrypt(
"piconfigsuccess",
[
str(self.goniometer.incidence),
str(self.goniometer.emission),
str(self.goniometer.azimuth),
str(self.goniometer.tray_pos),
],
)
self.send(filename)
elif cmd == "getcurrentposition":
self.goniometer.move_tray_to_nearest()
self.goniometer.update_position()
filename = self.encrypt(
"currentposition",
[
str(self.goniometer.incidence),
str(self.goniometer.emission),
str(self.goniometer.azimuth),
str(self.goniometer.tray_pos),
],
)
self.send(filename)
t = t + INTERVAL
time.sleep(INTERVAL)
def write_encoder_config(self, i, e, az, tray):
with open(ENCODER_CONFIG_PATH, "w+") as config_file:
config_file.write(f"{i}\n")
config_file.write(f"{e}\n")
config_file.write(f"{az}\n")
config_file.write(f"{tray}\n")
def write_az_config(self, az):
with open(AZ_CONFIG_PATH, "w+") as config_file:
config_file.write(f"{az}\n")
def send(self, message):
sent = self.client.send(message)
while not sent:
print("Failed to send message, retrying.")
print(message)
time.sleep(2)
sent = self.client.send(message)
def encrypt(self, cmd, parameters=None):
filename = cmd
if parameters:
for param in parameters:
param = param.replace("/", "+")
param = param.replace("\\", "+")
param = param.replace(":", "=")
filename = filename + "&" + param
return filename
def decrypt(self, encrypted):
cmd = encrypted.split("&")[0]
params = encrypted.split("&")[1:]
i = 0
for param in params:
params[i] = param.replace("+", "\\").replace("=", ":")
params[i] = params[i].replace("++", "+")
i = i + 1
return cmd, params
if __name__ == "__main__":
main()
|
cursor_wrapper.py | import logging
from threading import Thread
from time import time
from django.db.backends.utils import CursorWrapper
from .log_object import SqlLogObject, settings
log = logging.getLogger('dl_logger')
class CursorLogWrapper(CursorWrapper):
def execute(self, sql, params=None):
return self.log_query(super(CursorLogWrapper, self).execute, sql, params)
def executemany(self, sql, param_list):
return self.log_query(super(CursorLogWrapper, self).executemany, sql, param_list)
def log_query(self, method, *args):
start = time()
try:
return method(*args)
finally:
stop = time()
duration = stop - start
def do_log(cursor, *log_args):
if duration < settings.SQL_THRESHOLD:
return
sql = self.db.ops.last_executed_query(cursor, *log_args)
sql_info = {
'sql': sql,
'time': "%.3f" % duration
}
self.db.queries_log.append(sql_info)
record = SqlLogObject(sql_info)
log.info(record)
Thread(target=do_log, args=((self.cursor,) + args)).start()
|
scheduler.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
| This file is part of the web2py Web Framework
| Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Background processes made simple
---------------------------------
"""
from __future__ import print_function
import os
import re
import time
import multiprocessing
import sys
import threading
import traceback
import signal
import socket
import datetime
import logging
import optparse
import tempfile
import types
from functools import reduce
from json import loads, dumps
from gluon import DAL, Field, IS_NOT_EMPTY, IS_IN_SET, IS_NOT_IN_DB, IS_EMPTY_OR
from gluon import IS_INT_IN_RANGE, IS_DATETIME, IS_IN_DB
from gluon.utils import web2py_uuid
from gluon._compat import Queue, long, iteritems, PY2
from gluon.storage import Storage
USAGE = """
## Example
For any existing app
Create File: app/models/scheduler.py ======
from gluon.scheduler import Scheduler
def demo1(*args,**vars):
print('you passed args=%s and vars=%s' % (args, vars))
return 'done!'
def demo2():
1/0
scheduler = Scheduler(db,dict(demo1=demo1,demo2=demo2))
## run worker nodes with:
cd web2py
python web2py.py -K myapp
or
python gluon/scheduler.py -u sqlite://storage.sqlite \
-f applications/myapp/databases/ \
-t mytasks.py
(-h for info)
python scheduler.py -h
## schedule jobs using
http://127.0.0.1:8000/myapp/appadmin/insert/db/scheduler_task
## monitor scheduled jobs
http://127.0.0.1:8000/myapp/appadmin/select/db?query=db.scheduler_task.id>0
## view completed jobs
http://127.0.0.1:8000/myapp/appadmin/select/db?query=db.scheduler_run.id>0
## view workers
http://127.0.0.1:8000/myapp/appadmin/select/db?query=db.scheduler_worker.id>0
"""
path = os.getcwd()
if 'WEB2PY_PATH' not in os.environ:
os.environ['WEB2PY_PATH'] = path
IDENTIFIER = "%s#%s" % (socket.gethostname(), os.getpid())
logger = logging.getLogger('web2py.scheduler.%s' % IDENTIFIER)
QUEUED = 'QUEUED'
ASSIGNED = 'ASSIGNED'
RUNNING = 'RUNNING'
COMPLETED = 'COMPLETED'
FAILED = 'FAILED'
TIMEOUT = 'TIMEOUT'
STOPPED = 'STOPPED'
ACTIVE = 'ACTIVE'
TERMINATE = 'TERMINATE'
DISABLED = 'DISABLED'
KILL = 'KILL'
PICK = 'PICK'
STOP_TASK = 'STOP_TASK'
EXPIRED = 'EXPIRED'
SECONDS = 1
HEARTBEAT = 3 * SECONDS
MAXHIBERNATION = 10
CLEAROUT = '!clear!'
CALLABLETYPES = (types.LambdaType, types.FunctionType,
types.BuiltinFunctionType,
types.MethodType, types.BuiltinMethodType)
class Task(object):
"""Defines a "task" object that gets passed from the main thread to the
executor's one
"""
def __init__(self, app, function, timeout, args='[]', vars='{}', **kwargs):
logger.debug(' new task allocated: %s.%s', app, function)
self.app = app
self.function = function
self.timeout = timeout
self.args = args # json
self.vars = vars # json
self.__dict__.update(kwargs)
def __str__(self):
return '<Task: %s>' % self.function
class TaskReport(object):
"""Defines a "task report" object that gets passed from the executor's
thread to the main one
"""
def __init__(self, status, result=None, output=None, tb=None):
logger.debug(' new task report: %s', status)
if tb:
logger.debug(' traceback: %s', tb)
else:
logger.debug(' result: %s', result)
self.status = status
self.result = result
self.output = output
self.tb = tb
def __str__(self):
return '<TaskReport: %s>' % self.status
class JobGraph(object):
"""Experimental: dependencies amongs tasks."""
def __init__(self, db, job_name):
self.job_name = job_name or 'job_0'
self.db = db
def add_deps(self, task_parent, task_child):
"""Create a dependency between task_parent and task_child."""
self.db.scheduler_task_deps.insert(task_parent=task_parent,
task_child=task_child,
job_name=self.job_name)
def validate(self, job_name=None):
"""Validate if all tasks job_name can be completed.
Checks if there are no mutual dependencies among tasks.
Commits at the end if successfull, or it rollbacks the entire
transaction. Handle with care!
"""
db = self.db
sd = db.scheduler_task_deps
if job_name:
q = sd.job_name == job_name
else:
q = sd.id > 0
edges = db(q).select()
nested_dict = {}
for row in edges:
k = row.task_parent
if k in nested_dict:
nested_dict[k].add(row.task_child)
else:
nested_dict[k] = set((row.task_child,))
try:
rtn = []
for k, v in nested_dict.items():
v.discard(k) # Ignore self dependencies
extra_items_in_deps = reduce(set.union, nested_dict.values()) - set(nested_dict.keys())
nested_dict.update(dict((item, set()) for item in extra_items_in_deps))
while True:
ordered = set(item for item, dep in nested_dict.items() if not dep)
if not ordered:
break
rtn.append(ordered)
nested_dict = dict(
(item, (dep - ordered)) for item, dep in nested_dict.items()
if item not in ordered
)
assert not nested_dict, "A cyclic dependency exists amongst %r" % nested_dict
db.commit()
return rtn
except:
db.rollback()
return None
class CronParser(object):
def __init__(self, cronline, base=None):
self.cronline = cronline
self.sched = base or datetime.datetime.now()
self.task = None
@staticmethod
def _rangetolist(s, period='min'):
retval = []
if s.startswith('*'):
if period == 'min':
s = s.replace('*', '0-59', 1)
elif period == 'hr':
s = s.replace('*', '0-23', 1)
elif period == 'dom':
s = s.replace('*', '1-31', 1)
elif period == 'mon':
s = s.replace('*', '1-12', 1)
elif period == 'dow':
s = s.replace('*', '0-6', 1)
m = re.compile(r'(\d+)-(\d+)/(\d+)')
match = m.match(s)
if match:
min_, max_ = int(match.group(1)), int(match.group(2)) + 1
step_ = int(match.group(3))
else:
m = re.compile(r'(\d+)/(\d+)')
ranges_max = {'min': 59, 'hr': 23, 'mon': 12, 'dom': 31, 'dow': 7}
match = m.match(s)
if match:
min_, max_ = int(match.group(1)), ranges_max[period] + 1
step_ = int(match.group(2))
if match:
for i in range(min_, max_, step_):
retval.append(i)
return retval
@staticmethod
def _sanitycheck(values, period):
if period == 'min':
check = all(0 <= i <= 59 for i in values)
elif period == 'hr':
check = all(0 <= i <= 23 for i in values)
elif period == 'dom':
domrange = list(range(1, 32)) + ['l']
check = all(i in domrange for i in values)
elif period == 'mon':
check = all(1 <= i <= 12 for i in values)
elif period == 'dow':
check = all(0 <= i <= 7 for i in values)
return check
def _parse(self):
line = self.cronline.lower()
task = {}
if line.startswith('@yearly'):
line = line.replace('@yearly', '0 0 1 1 *')
elif line.startswith('@annually'):
line = line.replace('@annually', '0 0 1 1 *')
elif line.startswith('@monthly'):
line = line.replace('@monthly', '0 0 1 * *')
elif line.startswith('@weekly'):
line = line.replace('@weekly', '0 0 * * 0')
elif line.startswith('@daily'):
line = line.replace('@daily', '0 0 * * *')
elif line.startswith('@midnight'):
line = line.replace('@midnight', '0 0 * * *')
elif line.startswith('@hourly'):
line = line.replace('@hourly', '0 * * * *')
params = line.strip().split()
if len(params) < 5:
raise ValueError('Invalid cron line (too short)')
elif len(params) > 5:
raise ValueError('Invalid cron line (too long)')
daysofweek = {'sun': 0, 'mon': 1, 'tue': 2, 'wed': 3, 'thu': 4,
'fri': 5, 'sat': 6}
monthsofyear = {'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5,
'jun': 6, 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10,
'nov': 11, 'dec': 12, 'l': 'l'}
for (s, i) in zip(params[:5], ['min', 'hr', 'dom', 'mon', 'dow']):
if s not in [None, '*']:
task[i] = []
vals = s.split(',')
for val in vals:
if i == 'dow':
refdict = daysofweek
elif i == 'mon':
refdict = monthsofyear
if i in ('dow', 'mon') and '-' in val and '/' not in val:
isnum = val.split('-')[0].isdigit()
if isnum:
val = '%s/1' % val
else:
val = '-'.join([str(refdict[v])
for v in val.split('-')])
if val != '-1' and '-' in val and '/' not in val:
val = '%s/1' % val
if '/' in val:
task[i] += self._rangetolist(val, i)
elif val.isdigit() or val == '-1':
task[i].append(int(val))
elif i in ('dow', 'mon'):
if val in refdict:
task[i].append(refdict[val])
elif i == 'dom' and val == 'l':
task[i].append(val)
if not task[i]:
raise ValueError('Invalid cron value (%s)' % s)
if not self._sanitycheck(task[i], i):
raise ValueError('Invalid cron value (%s)' % s)
task[i] = sorted(task[i])
self.task = task
@staticmethod
def _get_next_dow(sched, task):
task_dow = [a % 7 for a in task['dow']]
while sched.isoweekday() % 7 not in task_dow:
sched += datetime.timedelta(days=1)
return sched
@staticmethod
def _get_next_dom(sched, task):
if task['dom'] == ['l']:
last_feb = 29 if sched.year % 4 == 0 else 28
lastdayofmonth = [
31, last_feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
]
task_dom = [lastdayofmonth[sched.month - 1]]
else:
task_dom = task['dom']
while sched.day not in task_dom:
sched += datetime.timedelta(days=1)
return sched
@staticmethod
def _get_next_mon(sched, task):
while sched.month not in task['mon']:
if sched.month < 12:
sched = sched.replace(month=sched.month + 1)
else:
sched = sched.replace(month=1, year=sched.year + 1)
return sched
@staticmethod
def _getnext_hhmm(sched, task, add_to=True):
if add_to:
sched += datetime.timedelta(minutes=1)
if 'min' in task:
while sched.minute not in task['min']:
sched += datetime.timedelta(minutes=1)
if 'hr' in task and sched.hour not in task['hr']:
while sched.hour not in task['hr']:
sched += datetime.timedelta(hours=1)
return sched
def _getnext_date(self, sched, task):
if 'dow' in task and 'dom' in task:
dow = self._get_next_dow(sched, task)
dom = self._get_next_dom(sched, task)
sched = min(dow, dom)
elif 'dow' in task:
sched = self._get_next_dow(sched, task)
elif 'dom' in task:
sched = self._get_next_dom(sched, task)
if 'mon' in task:
sched = self._get_next_mon(sched, task)
return sched.replace(hour=0, minute=0)
def get_next(self):
"""Get next date according to specs."""
if not self.task:
self._parse()
task = self.task
sched = self.sched
x = 0
while x < 1000: # avoid potential max recursions
x += 1
try:
next_date = self._getnext_date(sched, task)
except (ValueError, OverflowError) as e:
raise ValueError('Invalid cron expression (%s)' % e)
if next_date.date() > self.sched.date():
# we rolled date, check for valid hhmm
sched = self._getnext_hhmm(next_date, task, False)
break
else:
# same date, get next hhmm
sched_time = self._getnext_hhmm(sched, task, True)
if sched_time.date() > sched.date():
# we rolled date again :(
sched = sched_time
else:
sched = sched_time
break
else:
raise ValueError('Potential bug found, please submit your '
'cron expression to the authors')
self.sched = sched
return sched
def __iter__(self):
"""Support iteration."""
return self
__next__ = next = get_next
# the two functions below deal with simplejson decoding as unicode, esp for the dict decode
# and subsequent usage as function Keyword arguments unicode variable names won't work!
# borrowed from http://stackoverflow.com/questions/956867/
def _decode_list(lst):
if not PY2:
return lst
newlist = []
for i in lst:
if isinstance(i, unicode):
i = i.encode('utf-8')
elif isinstance(i, list):
i = _decode_list(i)
newlist.append(i)
return newlist
def _decode_dict(dct):
if not PY2:
return dct
newdict = {}
for k, v in iteritems(dct):
if isinstance(k, unicode):
k = k.encode('utf-8')
if isinstance(v, unicode):
v = v.encode('utf-8')
elif isinstance(v, list):
v = _decode_list(v)
newdict[k] = v
return newdict
def executor(queue, task, out):
"""The function used to execute tasks in the background process."""
logger.debug(' task started')
class LogOutput(object):
"""Facility to log output at intervals."""
def __init__(self, out_queue):
self.out_queue = out_queue
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
def flush(self):
pass
def write(self, data):
self.out_queue.put(data)
W2P_TASK = Storage({
'id': task.task_id,
'uuid': task.uuid,
'run_id': task.run_id
})
stdout = LogOutput(out)
try:
if task.app:
os.chdir(os.environ['WEB2PY_PATH'])
from gluon.shell import env, parse_path_info
from gluon import current
level = logging.getLogger().getEffectiveLevel()
logging.getLogger().setLevel(logging.WARN)
# Get controller-specific subdirectory if task.app is of
# form 'app/controller'
(a, c, f) = parse_path_info(task.app)
_env = env(a=a, c=c, import_models=True,
extra_request={'is_scheduler': True})
logging.getLogger().setLevel(level)
f = task.function
functions = current._scheduler.tasks
if not functions:
# look into env
_function = _env.get(f)
else:
_function = functions.get(f)
if not isinstance(_function, CALLABLETYPES):
raise NameError(
"name '%s' not found in scheduler's environment" % f)
# Inject W2P_TASK into environment
_env.update({'W2P_TASK': W2P_TASK})
# Inject W2P_TASK into current
from gluon import current
current.W2P_TASK = W2P_TASK
globals().update(_env)
args = _decode_list(loads(task.args))
vars = loads(task.vars, object_hook=_decode_dict)
result = dumps(_function(*args, **vars))
else:
# for testing purpose only
result = eval(task.function)(
*loads(task.args, object_hook=_decode_dict),
**loads(task.vars, object_hook=_decode_dict))
if len(result) >= 1024:
fd, temp_path = tempfile.mkstemp(suffix='.w2p_sched')
with os.fdopen(fd, 'w') as f:
f.write(result)
result = 'w2p_special:%s' % temp_path
queue.put(TaskReport('COMPLETED', result=result))
except BaseException as e:
tb = traceback.format_exc()
queue.put(TaskReport('FAILED', tb=tb))
del stdout
class MetaScheduler(threading.Thread):
"""Base class documenting scheduler's base methods."""
def __init__(self):
threading.Thread.__init__(self)
self.process = None # the background process
self.have_heartbeat = True # set to False to kill
self.empty_runs = 0
def async(self, task):
"""Start the background process.
Args:
task : a `Task` object
Returns:
tuple: containing::
('ok',result,output)
('error',exception,None)
('timeout',None,None)
('terminated',None,None)
"""
db = self.db
sr = db.scheduler_run
out = multiprocessing.Queue()
queue = multiprocessing.Queue(maxsize=1)
p = multiprocessing.Process(target=executor, args=(queue, task, out))
self.process = p
logger.debug(' task starting')
p.start()
task_output = ""
tout = ""
try:
if task.sync_output > 0:
run_timeout = task.sync_output
else:
run_timeout = task.timeout
start = time.time()
while p.is_alive() and (not task.timeout or time.time() - start < task.timeout):
if tout:
try:
logger.debug(' partial output saved')
db(sr.id == task.run_id).update(run_output=task_output)
db.commit()
except:
pass
p.join(timeout=run_timeout)
tout = ""
while not out.empty():
tout += out.get()
if tout:
logger.debug(' partial output: "%s"', str(tout))
if CLEAROUT in tout:
task_output = tout[
tout.rfind(CLEAROUT) + len(CLEAROUT):]
else:
task_output += tout
except:
p.terminate()
p.join()
logger.debug(' task stopped by general exception')
tr = TaskReport(STOPPED)
else:
if p.is_alive():
p.terminate()
logger.debug(' task timeout')
try:
# we try to get a traceback here
tr = queue.get(timeout=2)
tr.status = TIMEOUT
tr.output = task_output
except Queue.Empty:
tr = TaskReport(TIMEOUT)
elif queue.empty():
logger.debug(' task stopped')
tr = TaskReport(STOPPED)
else:
logger.debug(' task completed or failed')
tr = queue.get()
result = tr.result
if result and result.startswith('w2p_special'):
temp_path = result.replace('w2p_special:', '', 1)
with open(temp_path) as f:
tr.result = f.read()
os.unlink(temp_path)
tr.output = task_output
return tr
def die(self):
"""Forces termination of the worker process along with any running
task"""
logger.info('die!')
self.have_heartbeat = False
self.terminate_process()
def give_up(self):
"""Waits for any running task to be executed, then exits the worker
process"""
logger.info('Giving up as soon as possible!')
self.have_heartbeat = False
def terminate_process(self):
"""Terminate any running tasks (internal use only)"""
try:
self.process.terminate()
except:
pass # no process to terminate
def run(self):
"""This is executed by the main thread to send heartbeats"""
counter = 0
while self.have_heartbeat:
self.send_heartbeat(counter)
counter += 1
def start_heartbeats(self):
self.start()
def send_heartbeat(self, counter):
raise NotImplementedError
def pop_task(self):
"""Fetches a task ready to be executed"""
raise NotImplementedError
def report_task(self, task, task_report):
"""Creates a task report"""
raise NotImplementedError
def sleep(self):
raise NotImplementedError
def loop(self):
"""Main loop, fetching tasks and starting executor's background
processes"""
raise NotImplementedError
TASK_STATUS = (QUEUED, RUNNING, COMPLETED, FAILED, TIMEOUT, STOPPED, EXPIRED)
RUN_STATUS = (RUNNING, COMPLETED, FAILED, TIMEOUT, STOPPED)
WORKER_STATUS = (ACTIVE, PICK, DISABLED, TERMINATE, KILL, STOP_TASK)
class IS_CRONLINE(object):
"""
Validates cronline
"""
def __init__(self, error_message=None):
self.error_message = error_message
def __call__(self, value):
recur = CronParser(value, datetime.datetime.now())
try:
recur.get_next()
return (value, None)
except (KeyError, ValueError) as e:
if not self.error_message:
return (value, e)
return (value, self.error_message)
class TYPE(object):
"""
Validator that checks whether field is valid json and validates its type.
Used for `args` and `vars` of the scheduler_task table
"""
def __init__(self, myclass=list, parse=False):
self.myclass = myclass
self.parse = parse
def __call__(self, value):
from gluon import current
try:
obj = loads(value)
except:
return (value, current.T('invalid json'))
else:
if isinstance(obj, self.myclass):
if self.parse:
return (obj, None)
else:
return (value, None)
else:
return (value, current.T('Not of type: %s') % self.myclass)
class Scheduler(MetaScheduler):
"""Scheduler object
Args:
db: DAL connection where Scheduler will create its tables
tasks(dict): either a dict containing name-->func or None.
If None, functions will be searched in the environment
migrate(bool): turn migration on/off for the Scheduler's tables
worker_name(str): force worker_name to identify each process.
Leave it to None to autoassign a name (hostname#pid)
group_names(list): process tasks belonging to this group
defaults to ['main'] if nothing gets passed
heartbeat(int): how many seconds the worker sleeps between one
execution and the following one. Indirectly sets how many seconds
will pass between checks for new tasks
max_empty_runs(int): how many loops are allowed to pass without
processing any tasks before exiting the process. 0 to keep always
the process alive
discard_results(bool): Scheduler stores executions's details into the
scheduler_run table. By default, only if there is a result the
details are kept. Turning this to True means discarding results
even for tasks that return something
utc_time(bool): do all datetime calculations assuming UTC as the
timezone. Remember to pass `start_time` and `stop_time` to tasks
accordingly
"""
def __init__(self, db, tasks=None, migrate=True,
worker_name=None, group_names=None, heartbeat=HEARTBEAT,
max_empty_runs=0, discard_results=False, utc_time=False):
MetaScheduler.__init__(self)
self.db = db
self.db_thread = None
self.tasks = tasks
self.group_names = group_names or ['main']
self.heartbeat = heartbeat
self.worker_name = worker_name or IDENTIFIER
self.max_empty_runs = max_empty_runs
self.discard_results = discard_results
self.is_a_ticker = False
self.do_assign_tasks = False
self.greedy = False
self.utc_time = utc_time
self.w_stats = Storage(
dict(
status=RUNNING,
sleep=heartbeat,
total=0,
errors=0,
empty_runs=0,
queue=0,
distribution=None,
workers=0)
) # dict holding statistics
from gluon import current
current._scheduler = self
self.define_tables(db, migrate=migrate)
def __get_migrate(self, tablename, migrate=True):
if migrate is False:
return False
elif migrate is True:
return True
elif isinstance(migrate, str):
return "%s%s.table" % (migrate, tablename)
return True
def now(self):
"""Shortcut that fetches current time based on UTC preferences."""
return self.utc_time and datetime.datetime.utcnow() or datetime.datetime.now()
def set_requirements(self, scheduler_task):
"""Called to set defaults for lazy_tables connections."""
from gluon import current
if hasattr(current, 'request'):
scheduler_task.application_name.default = '%s/%s' % (
current.request.application, current.request.controller
)
def define_tables(self, db, migrate):
"""Define Scheduler tables structure."""
from pydal.base import DEFAULT
logger.debug('defining tables (migrate=%s)', migrate)
now = self.now
db.define_table(
'scheduler_task',
Field('application_name', requires=IS_NOT_EMPTY(),
default=None, writable=False),
Field('task_name', default=None),
Field('group_name', default='main'),
Field('status', requires=IS_IN_SET(TASK_STATUS),
default=QUEUED, writable=False),
Field('function_name',
requires=IS_IN_SET(sorted(self.tasks.keys()))
if self.tasks else DEFAULT),
Field('uuid', length=255,
requires=IS_NOT_IN_DB(db, 'scheduler_task.uuid'),
unique=True, default=web2py_uuid),
Field('args', 'text', default='[]', requires=TYPE(list)),
Field('vars', 'text', default='{}', requires=TYPE(dict)),
Field('enabled', 'boolean', default=True),
Field('start_time', 'datetime', default=now,
requires=IS_DATETIME()),
Field('next_run_time', 'datetime', default=now),
Field('stop_time', 'datetime'),
Field('repeats', 'integer', default=1, comment="0=unlimited",
requires=IS_INT_IN_RANGE(0, None)),
Field('retry_failed', 'integer', default=0, comment="-1=unlimited",
requires=IS_INT_IN_RANGE(-1, None)),
Field('period', 'integer', default=60, comment='seconds',
requires=IS_INT_IN_RANGE(0, None)),
Field('prevent_drift', 'boolean', default=False,
comment='Exact start_times between runs'),
Field('cronline', default=None,
comment='Discard "period", use this cron expr instead',
requires=IS_EMPTY_OR(IS_CRONLINE())),
Field('timeout', 'integer', default=60, comment='seconds',
requires=IS_INT_IN_RANGE(1, None)),
Field('sync_output', 'integer', default=0,
comment="update output every n sec: 0=never",
requires=IS_INT_IN_RANGE(0, None)),
Field('times_run', 'integer', default=0, writable=False),
Field('times_failed', 'integer', default=0, writable=False),
Field('last_run_time', 'datetime', writable=False, readable=False),
Field('assigned_worker_name', default='', writable=False),
on_define=self.set_requirements,
migrate=self.__get_migrate('scheduler_task', migrate),
format='(%(id)s) %(task_name)s')
db.define_table(
'scheduler_run',
Field('task_id', 'reference scheduler_task'),
Field('status', requires=IS_IN_SET(RUN_STATUS)),
Field('start_time', 'datetime'),
Field('stop_time', 'datetime'),
Field('run_output', 'text'),
Field('run_result', 'text'),
Field('traceback', 'text'),
Field('worker_name', default=self.worker_name),
migrate=self.__get_migrate('scheduler_run', migrate)
)
db.define_table(
'scheduler_worker',
Field('worker_name', length=255, unique=True),
Field('first_heartbeat', 'datetime'),
Field('last_heartbeat', 'datetime'),
Field('status', requires=IS_IN_SET(WORKER_STATUS)),
Field('is_ticker', 'boolean', default=False, writable=False),
Field('group_names', 'list:string', default=self.group_names),
Field('worker_stats', 'json'),
migrate=self.__get_migrate('scheduler_worker', migrate)
)
db.define_table(
'scheduler_task_deps',
Field('job_name', default='job_0'),
Field('task_parent', 'integer',
requires=IS_IN_DB(db, 'scheduler_task.id', '%(task_name)s')
),
Field('task_child', 'reference scheduler_task'),
Field('can_visit', 'boolean', default=False),
migrate=self.__get_migrate('scheduler_task_deps', migrate)
)
if migrate is not False:
db.commit()
def loop(self, worker_name=None):
"""Main loop.
This works basically as a neverending loop that:
- checks if the worker is ready to process tasks (is not DISABLED)
- pops a task from the queue
- if there is a task:
- spawns the executor background process
- waits for the process to be finished
- sleeps `heartbeat` seconds
- if there is not a task:
- checks for max_empty_runs
- sleeps `heartbeat` seconds
"""
signal.signal(signal.SIGTERM, lambda signum, stack_frame: sys.exit(1))
try:
self.start_heartbeats()
while self.have_heartbeat:
if self.w_stats.status == DISABLED:
logger.debug('Someone stopped me, sleeping until better'
' times come (%s)', self.w_stats.sleep)
self.sleep()
continue
logger.debug('looping...')
task = self.wrapped_pop_task()
if task:
self.w_stats.empty_runs = 0
self.w_stats.status = RUNNING
self.w_stats.total += 1
self.wrapped_report_task(task, self.async(task))
if not self.w_stats.status == DISABLED:
self.w_stats.status = ACTIVE
else:
self.w_stats.empty_runs += 1
logger.debug('sleeping...')
if self.max_empty_runs != 0:
logger.debug('empty runs %s/%s',
self.w_stats.empty_runs,
self.max_empty_runs)
if self.w_stats.empty_runs >= self.max_empty_runs:
logger.info(
'empty runs limit reached, killing myself')
self.die()
self.sleep()
except (KeyboardInterrupt, SystemExit):
logger.info('catched')
self.die()
def wrapped_assign_tasks(self, db):
"""Commodity function to call `assign_tasks` and trap exceptions.
If an exception is raised, assume it happened because of database
contention and retries `assign_task` after 0.5 seconds
"""
logger.debug('Assigning tasks...')
db.commit() # db.commit() only for Mysql
x = 0
while x < 10:
try:
self.assign_tasks(db)
db.commit()
logger.debug('Tasks assigned...')
break
except:
self.w_stats.errors += 1
db.rollback()
logger.error('TICKER: error assigning tasks (%s)', x)
x += 1
time.sleep(0.5)
def wrapped_pop_task(self):
"""Commodity function to call `pop_task` and trap exceptions.
If an exception is raised, assume it happened because of database
contention and retries `pop_task` after 0.5 seconds
"""
db = self.db
db.commit() # another nifty db.commit() only for Mysql
x = 0
while x < 10:
try:
rtn = self.pop_task(db)
return rtn
break
except:
self.w_stats.errors += 1
db.rollback()
logger.error(' error popping tasks')
x += 1
time.sleep(0.5)
def pop_task(self, db):
"""Grab a task ready to be executed from the queue."""
now = self.now()
st = self.db.scheduler_task
if self.is_a_ticker and self.do_assign_tasks:
# I'm a ticker, and 5 loops passed without reassigning tasks,
# let's do that and loop again
self.wrapped_assign_tasks(db)
return None
# ready to process something
grabbed = db(
(st.assigned_worker_name == self.worker_name) &
(st.status == ASSIGNED)
)
task = grabbed.select(limitby=(0, 1), orderby=st.next_run_time).first()
if task:
task.update_record(status=RUNNING, last_run_time=now)
# noone will touch my task!
db.commit()
logger.debug(' work to do %s', task.id)
else:
if self.is_a_ticker and self.greedy:
# there are other tasks ready to be assigned
logger.info('TICKER: greedy loop')
self.wrapped_assign_tasks(db)
else:
logger.info('nothing to do')
return None
times_run = task.times_run + 1
if task.cronline:
cron_recur = CronParser(task.cronline, now.replace(second=0))
next_run_time = cron_recur.get_next()
elif not task.prevent_drift:
next_run_time = task.last_run_time + datetime.timedelta(
seconds=task.period
)
else:
# calc next_run_time based on available slots
# see #1191
next_run_time = task.start_time
secondspassed = (now - next_run_time).total_seconds()
steps = secondspassed // task.period + 1
next_run_time += datetime.timedelta(seconds=task.period * steps)
if times_run < task.repeats or task.repeats == 0:
# need to run (repeating task)
run_again = True
else:
# no need to run again
run_again = False
run_id = 0
while True and not self.discard_results:
logger.debug(' new scheduler_run record')
try:
run_id = db.scheduler_run.insert(
task_id=task.id,
status=RUNNING,
start_time=now,
worker_name=self.worker_name)
db.commit()
break
except:
time.sleep(0.5)
db.rollback()
logger.info('new task %(id)s "%(task_name)s"'
' %(application_name)s.%(function_name)s' % task)
return Task(
app=task.application_name,
function=task.function_name,
timeout=task.timeout,
args=task.args, # in json
vars=task.vars, # in json
task_id=task.id,
run_id=run_id,
run_again=run_again,
next_run_time=next_run_time,
times_run=times_run,
stop_time=task.stop_time,
retry_failed=task.retry_failed,
times_failed=task.times_failed,
sync_output=task.sync_output,
uuid=task.uuid)
def wrapped_report_task(self, task, task_report):
"""Commodity function to call `report_task` and trap exceptions.
If an exception is raised, assume it happened because of database
contention and retries `pop_task` after 0.5 seconds
"""
db = self.db
while True:
try:
self.report_task(task, task_report)
db.commit()
break
except:
self.w_stats.errors += 1
db.rollback()
logger.error(' error storing result')
time.sleep(0.5)
def report_task(self, task, task_report):
"""Take care of storing the result according to preferences.
Deals with logic for repeating tasks.
"""
db = self.db
now = self.now()
st = db.scheduler_task
sr = db.scheduler_run
if not self.discard_results:
if task_report.result != 'null' or task_report.tb:
# result is 'null' as a string if task completed
# if it's stopped it's None as NoneType, so we record
# the STOPPED "run" anyway
logger.debug(' recording task report in db (%s)',
task_report.status)
db(sr.id == task.run_id).update(
status=task_report.status,
stop_time=now,
run_result=task_report.result,
run_output=task_report.output,
traceback=task_report.tb)
else:
logger.debug(' deleting task report in db because of no result')
db(sr.id == task.run_id).delete()
# if there is a stop_time and the following run would exceed it
is_expired = (task.stop_time and
task.next_run_time > task.stop_time and
True or False)
status = (task.run_again and is_expired and EXPIRED or
task.run_again and not is_expired and
QUEUED or COMPLETED)
if task_report.status == COMPLETED:
d = dict(status=status,
next_run_time=task.next_run_time,
times_run=task.times_run,
times_failed=0
)
db(st.id == task.task_id).update(**d)
if status == COMPLETED:
self.update_dependencies(db, task.task_id)
else:
st_mapping = {'FAILED': 'FAILED',
'TIMEOUT': 'TIMEOUT',
'STOPPED': 'FAILED'}[task_report.status]
status = (task.retry_failed
and task.times_failed < task.retry_failed
and QUEUED or task.retry_failed == -1
and QUEUED or st_mapping)
db(st.id == task.task_id).update(
times_failed=st.times_failed + 1,
next_run_time=task.next_run_time,
status=status
)
logger.info('task completed (%s)', task_report.status)
def update_dependencies(self, db, task_id):
"""Unblock execution paths for Jobs."""
db(db.scheduler_task_deps.task_child == task_id).update(can_visit=True)
def adj_hibernation(self):
"""Used to increase the "sleep" interval for DISABLED workers."""
if self.w_stats.status == DISABLED:
wk_st = self.w_stats.sleep
hibernation = wk_st + HEARTBEAT if wk_st < MAXHIBERNATION else MAXHIBERNATION
self.w_stats.sleep = hibernation
def send_heartbeat(self, counter):
"""Coordination among available workers.
It:
- sends the heartbeat
- elects a ticker among available workers (the only process that
effectively dispatch tasks to workers)
- deals with worker's statuses
- does "housecleaning" for dead workers
- triggers tasks assignment to workers
"""
if not self.db_thread:
logger.debug('thread building own DAL object')
self.db_thread = DAL(
self.db._uri, folder=self.db._adapter.folder, decode_credentials=True)
self.define_tables(self.db_thread, migrate=False)
try:
db = self.db_thread
sw, st = db.scheduler_worker, db.scheduler_task
now = self.now()
# record heartbeat
mybackedstatus = db(sw.worker_name == self.worker_name).select().first()
if not mybackedstatus:
sw.insert(status=ACTIVE, worker_name=self.worker_name,
first_heartbeat=now, last_heartbeat=now,
group_names=self.group_names,
worker_stats=self.w_stats)
self.w_stats.status = ACTIVE
self.w_stats.sleep = self.heartbeat
mybackedstatus = ACTIVE
else:
mybackedstatus = mybackedstatus.status
if mybackedstatus == DISABLED:
# keep sleeping
self.w_stats.status = DISABLED
logger.debug('........recording heartbeat (%s)',
self.w_stats.status)
db(sw.worker_name == self.worker_name).update(
last_heartbeat=now,
worker_stats=self.w_stats)
elif mybackedstatus == TERMINATE:
self.w_stats.status = TERMINATE
logger.debug("Waiting to terminate the current task")
self.give_up()
elif mybackedstatus == KILL:
self.w_stats.status = KILL
self.die()
return
else:
if mybackedstatus == STOP_TASK:
logger.info('Asked to kill the current task')
self.terminate_process()
logger.debug('........recording heartbeat (%s)',
self.w_stats.status)
db(sw.worker_name == self.worker_name).update(
last_heartbeat=now, status=ACTIVE,
worker_stats=self.w_stats)
self.w_stats.sleep = self.heartbeat # re-activating the process
if self.w_stats.status != RUNNING:
self.w_stats.status = ACTIVE
self.do_assign_tasks = False
if counter % 5 == 0 or mybackedstatus == PICK:
try:
# delete dead workers
expiration = now - datetime.timedelta(
seconds=self.heartbeat * 3)
departure = now - datetime.timedelta(
seconds=self.heartbeat * 3 * 15)
logger.debug(
' freeing workers that have not sent heartbeat')
dead_workers = db(
((sw.last_heartbeat < expiration) & (sw.status == ACTIVE)) |
((sw.last_heartbeat < departure) & (sw.status != ACTIVE))
)
dead_workers_name = dead_workers._select(sw.worker_name)
db(
(st.assigned_worker_name.belongs(dead_workers_name)) &
(st.status == RUNNING)
).update(assigned_worker_name='', status=QUEUED)
dead_workers.delete()
try:
self.is_a_ticker = self.being_a_ticker()
except:
logger.error('Error coordinating TICKER')
if self.w_stats.status == ACTIVE:
self.do_assign_tasks = True
except:
logger.error('Error cleaning up')
db.commit()
except:
logger.error('Error retrieving status')
db.rollback()
self.adj_hibernation()
self.sleep()
def being_a_ticker(self):
"""Elect a TICKER process that assigns tasks to available workers.
Does its best to elect a worker that is not busy processing other tasks
to allow a proper distribution of tasks among all active workers ASAP
"""
db = self.db_thread
sw = db.scheduler_worker
my_name = self.worker_name
all_active = db(
(sw.worker_name != my_name) & (sw.status == ACTIVE)
).select(sw.is_ticker, sw.worker_name)
ticker = all_active.find(lambda row: row.is_ticker is True).first()
not_busy = self.w_stats.status == ACTIVE
if not ticker:
# if no other tickers are around
if not_busy:
# only if I'm not busy
db(sw.worker_name == my_name).update(is_ticker=True)
db(sw.worker_name != my_name).update(is_ticker=False)
logger.info("TICKER: I'm a ticker")
else:
# I'm busy
if len(all_active) >= 1:
# so I'll "downgrade" myself to a "poor worker"
db(sw.worker_name == my_name).update(is_ticker=False)
else:
not_busy = True
db.commit()
return not_busy
else:
logger.info(
"%s is a ticker, I'm a poor worker" % ticker.worker_name)
return False
def assign_tasks(self, db):
"""Assign task to workers, that can then pop them from the queue.
Deals with group_name(s) logic, in order to assign linearly tasks
to available workers for those groups
"""
sw, st, sd = db.scheduler_worker, db.scheduler_task, db.scheduler_task_deps
now = self.now()
all_workers = db(sw.status == ACTIVE).select()
# build workers as dict of groups
wkgroups = {}
for w in all_workers:
if w.worker_stats['status'] == 'RUNNING':
continue
group_names = w.group_names
for gname in group_names:
if gname not in wkgroups:
wkgroups[gname] = dict(
workers=[{'name': w.worker_name, 'c': 0}])
else:
wkgroups[gname]['workers'].append(
{'name': w.worker_name, 'c': 0})
# set queued tasks that expired between "runs" (i.e., you turned off
# the scheduler): then it wasn't expired, but now it is
db(
(st.status.belongs((QUEUED, ASSIGNED))) &
(st.stop_time < now)
).update(status=EXPIRED)
# calculate dependencies
deps_with_no_deps = db(
(sd.can_visit == False) &
(~sd.task_child.belongs(
db(sd.can_visit == False)._select(sd.task_parent)
)
)
)._select(sd.task_child)
no_deps = db(
(st.status.belongs((QUEUED, ASSIGNED))) &
(
(sd.id == None) | (st.id.belongs(deps_with_no_deps))
)
)._select(st.id, distinct=True, left=sd.on(
(st.id == sd.task_parent) &
(sd.can_visit == False)
)
)
all_available = db(
(st.status.belongs((QUEUED, ASSIGNED))) &
(st.next_run_time <= now) &
(st.enabled == True) &
(st.id.belongs(no_deps))
)
limit = len(all_workers) * (50 / (len(wkgroups) or 1))
# if there are a moltitude of tasks, let's figure out a maximum of
# tasks per worker. This can be further tuned with some added
# intelligence (like esteeming how many tasks will a worker complete
# before the ticker reassign them around, but the gain is quite small
# 50 is a sweet spot also for fast tasks, with sane heartbeat values
# NB: ticker reassign tasks every 5 cycles, so if a worker completes
# its 50 tasks in less than heartbeat*5 seconds,
# it won't pick new tasks until heartbeat*5 seconds pass.
# If a worker is currently elaborating a long task, its tasks needs to
# be reassigned to other workers
# this shuffles up things a bit, in order to give a task equal chances
# to be executed
# let's freeze it up
db.commit()
x = 0
for group in wkgroups.keys():
tasks = all_available(st.group_name == group).select(
limitby=(0, limit), orderby=st.next_run_time)
# let's break up the queue evenly among workers
for task in tasks:
x += 1
gname = task.group_name
ws = wkgroups.get(gname)
if ws:
counter = 0
myw = 0
for i, w in enumerate(ws['workers']):
if w['c'] < counter:
myw = i
counter = w['c']
assigned_wn = wkgroups[gname]['workers'][myw]['name']
d = dict(
status=ASSIGNED,
assigned_worker_name=assigned_wn
)
db(
(st.id == task.id) &
(st.status.belongs((QUEUED, ASSIGNED)))
).update(**d)
wkgroups[gname]['workers'][myw]['c'] += 1
db.commit()
# I didn't report tasks but I'm working nonetheless!!!!
if x > 0:
self.w_stats.empty_runs = 0
self.w_stats.queue = x
self.w_stats.distribution = wkgroups
self.w_stats.workers = len(all_workers)
# I'll be greedy only if tasks assigned are equal to the limit
# (meaning there could be others ready to be assigned)
self.greedy = x >= limit
logger.info('TICKER: workers are %s', len(all_workers))
logger.info('TICKER: tasks are %s', x)
def sleep(self):
"""Calculate the number of seconds to sleep."""
time.sleep(self.w_stats.sleep)
# should only sleep until next available task
def set_worker_status(self, group_names=None, action=ACTIVE,
exclude=None, limit=None, worker_name=None):
"""Internal function to set worker's status."""
ws = self.db.scheduler_worker
if not group_names:
group_names = self.group_names
elif isinstance(group_names, str):
group_names = [group_names]
if worker_name:
self.db(ws.worker_name == worker_name).update(status=action)
return
exclusion = exclude and exclude.append(action) or [action]
if not limit:
for group in group_names:
self.db(
(ws.group_names.contains(group)) &
(~ws.status.belongs(exclusion))
).update(status=action)
else:
for group in group_names:
workers = self.db((ws.group_names.contains(group)) &
(~ws.status.belongs(exclusion))
)._select(ws.id, limitby=(0, limit))
self.db(ws.id.belongs(workers)).update(status=action)
def disable(self, group_names=None, limit=None, worker_name=None):
"""Set DISABLED on the workers processing `group_names` tasks.
A DISABLED worker will be kept alive but it won't be able to process
any waiting tasks, essentially putting it to sleep.
By default, all group_names of Scheduler's instantation are selected
"""
self.set_worker_status(
group_names=group_names,
action=DISABLED,
exclude=[DISABLED, KILL, TERMINATE],
limit=limit)
def resume(self, group_names=None, limit=None, worker_name=None):
"""Wakes a worker up (it will be able to process queued tasks)"""
self.set_worker_status(
group_names=group_names,
action=ACTIVE,
exclude=[KILL, TERMINATE],
limit=limit)
def terminate(self, group_names=None, limit=None, worker_name=None):
"""Sets TERMINATE as worker status. The worker will wait for any
currently running tasks to be executed and then it will exit gracefully
"""
self.set_worker_status(
group_names=group_names,
action=TERMINATE,
exclude=[KILL],
limit=limit)
def kill(self, group_names=None, limit=None, worker_name=None):
"""Sets KILL as worker status. The worker will be killed even if it's
processing a task."""
self.set_worker_status(
group_names=group_names,
action=KILL,
limit=limit)
def queue_task(self, function, pargs=[], pvars={}, **kwargs):
"""
Queue tasks. This takes care of handling the validation of all
parameters
Args:
function: the function (anything callable with a __name__)
pargs: "raw" args to be passed to the function. Automatically
jsonified.
pvars: "raw" kwargs to be passed to the function. Automatically
jsonified
kwargs: all the parameters available (basically, every
`scheduler_task` column). If args and vars are here, they
should be jsonified already, and they will override pargs
and pvars
Returns:
a dict just as a normal validate_and_insert(), plus a uuid key
holding the uuid of the queued task. If validation is not passed
( i.e. some parameters are invalid) both id and uuid will be None,
and you'll get an "error" dict holding the errors found.
"""
if hasattr(function, '__name__'):
function = function.__name__
targs = 'args' in kwargs and kwargs.pop('args') or dumps(pargs)
tvars = 'vars' in kwargs and kwargs.pop('vars') or dumps(pvars)
tuuid = 'uuid' in kwargs and kwargs.pop('uuid') or web2py_uuid()
tname = 'task_name' in kwargs and kwargs.pop('task_name') or function
immediate = 'immediate' in kwargs and kwargs.pop('immediate') or None
cronline = kwargs.get('cronline')
kwargs.update(
function_name=function,
task_name=tname,
args=targs,
vars=tvars,
uuid=tuuid,
)
if cronline:
try:
start_time = kwargs.get('start_time', self.now)
next_run_time = CronParser(cronline, start_time).get_next()
kwargs.update(start_time=start_time, next_run_time=next_run_time)
except:
pass
if 'start_time' in kwargs and 'next_run_time' not in kwargs:
kwargs.update(next_run_time=kwargs['start_time'])
rtn = self.db.scheduler_task.validate_and_insert(**kwargs)
if not rtn.errors:
rtn.uuid = tuuid
if immediate:
self.db(
(self.db.scheduler_worker.is_ticker == True)
).update(status=PICK)
else:
rtn.uuid = None
return rtn
def task_status(self, ref, output=False):
"""
Retrieves task status and optionally the result of the task
Args:
ref: can be
- an integer : lookup will be done by scheduler_task.id
- a string : lookup will be done by scheduler_task.uuid
- a `Query` : lookup as you wish, e.g. ::
db.scheduler_task.task_name == 'test1'
output(bool): if `True`, fetch also the scheduler_run record
Returns:
a single Row object, for the last queued task.
If output == True, returns also the last scheduler_run record.
The scheduler_run record is fetched by a left join, so it can
have all fields == None
"""
from pydal.objects import Query
sr, st = self.db.scheduler_run, self.db.scheduler_task
if isinstance(ref, (int, long)):
q = st.id == ref
elif isinstance(ref, str):
q = st.uuid == ref
elif isinstance(ref, Query):
q = ref
else:
raise SyntaxError(
"You can retrieve results only by id, uuid or Query")
fields = [st.ALL]
left = False
orderby = ~st.id
if output:
fields = st.ALL, sr.ALL
left = sr.on(sr.task_id == st.id)
orderby = ~st.id | ~sr.id
row = self.db(q).select(
*fields,
**dict(orderby=orderby,
left=left,
limitby=(0, 1))
).first()
if row and output:
row.result = row.scheduler_run.run_result and \
loads(row.scheduler_run.run_result,
object_hook=_decode_dict) or None
return row
def stop_task(self, ref):
"""Shortcut for task termination.
If the task is RUNNING it will terminate it, meaning that status
will be set as FAILED.
If the task is QUEUED, its stop_time will be set as to "now",
the enabled flag will be set to False, and the status to STOPPED
Args:
ref: can be
- an integer : lookup will be done by scheduler_task.id
- a string : lookup will be done by scheduler_task.uuid
Returns:
- 1 if task was stopped (meaning an update has been done)
- None if task was not found, or if task was not RUNNING or QUEUED
Note:
Experimental
"""
st, sw = self.db.scheduler_task, self.db.scheduler_worker
if isinstance(ref, (int, long)):
q = st.id == ref
elif isinstance(ref, str):
q = st.uuid == ref
else:
raise SyntaxError(
"You can retrieve results only by id or uuid")
task = self.db(q).select(st.id, st.status, st.assigned_worker_name)
task = task.first()
rtn = None
if not task:
return rtn
if task.status == 'RUNNING':
q = sw.worker_name == task.assigned_worker_name
rtn = self.db(q).update(status=STOP_TASK)
elif task.status == 'QUEUED':
rtn = self.db(q).update(
stop_time=self.now(),
enabled=False,
status=STOPPED)
return rtn
def get_workers(self, only_ticker=False):
""" Returns a dict holding `worker_name : {**columns}`
representing all "registered" workers
only_ticker returns only the workers running as a TICKER,
if there are any
"""
db = self.db
if only_ticker:
workers = db(db.scheduler_worker.is_ticker == True).select()
else:
workers = db(db.scheduler_worker.id > 0).select()
all_workers = {}
for row in workers:
all_workers[row.worker_name] = Storage(
status=row.status,
first_heartbeat=row.first_heartbeat,
last_heartbeat=row.last_heartbeat,
group_names=row.group_names,
is_ticker=row.is_ticker,
worker_stats=row.worker_stats
)
return all_workers
def main():
"""
allows to run worker without python web2py.py .... by simply::
python gluon/scheduler.py
"""
parser = optparse.OptionParser()
parser.add_option(
"-w", "--worker_name", dest="worker_name", default=None,
help="start a worker with name")
parser.add_option(
"-b", "--heartbeat", dest="heartbeat", default=10,
type='int', help="heartbeat time in seconds (default 10)")
parser.add_option(
"-L", "--logger_level", dest="logger_level",
default=30,
type='int',
help="set debug output level (0-100, 0 means all, 100 means none;default is 30)")
parser.add_option("-E", "--empty-runs",
dest="max_empty_runs",
type='int',
default=0,
help="max loops with no grabbed tasks permitted (0 for never check)")
parser.add_option(
"-g", "--group_names", dest="group_names",
default='main',
help="comma separated list of groups to be picked by the worker")
parser.add_option(
"-f", "--db_folder", dest="db_folder",
default='/Users/mdipierro/web2py/applications/scheduler/databases',
help="location of the dal database folder")
parser.add_option(
"-u", "--db_uri", dest="db_uri",
default='sqlite://storage.sqlite',
help="database URI string (web2py DAL syntax)")
parser.add_option(
"-t", "--tasks", dest="tasks", default=None,
help="file containing task files, must define" +
"tasks = {'task_name':(lambda: 'output')} or similar set of tasks")
parser.add_option(
"-U", "--utc-time", dest="utc_time", default=False,
help="work with UTC timestamps"
)
(options, args) = parser.parse_args()
if not options.tasks or not options.db_uri:
print(USAGE)
if options.tasks:
path, filename = os.path.split(options.tasks)
if filename.endswith('.py'):
filename = filename[:-3]
sys.path.append(path)
print('importing tasks...')
tasks = __import__(filename, globals(), locals(), [], -1).tasks
print('tasks found: ' + ', '.join(tasks.keys()))
else:
tasks = {}
group_names = [x.strip() for x in options.group_names.split(',')]
logging.getLogger().setLevel(options.logger_level)
print('groups for this worker: ' + ', '.join(group_names))
print('connecting to database in folder: ' + options.db_folder or './')
print('using URI: ' + options.db_uri)
db = DAL(options.db_uri, folder=options.db_folder, decode_credentials=True)
print('instantiating scheduler...')
scheduler = Scheduler(db=db,
worker_name=options.worker_name,
tasks=tasks,
migrate=True,
group_names=group_names,
heartbeat=options.heartbeat,
max_empty_runs=options.max_empty_runs,
utc_time=options.utc_time)
signal.signal(signal.SIGTERM, lambda signum, stack_frame: sys.exit(1))
print('starting main worker loop...')
scheduler.loop()
if __name__ == '__main__':
main()
|
test_gc.py | import unittest
import unittest.mock
from test.support import (verbose, refcount_test, run_unittest,
cpython_only, start_threads,
temp_dir, requires_type_collecting, 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)
@requires_type_collecting
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.assertFalse(gc.is_tracked(UserClassSlots()))
self.assertFalse(gc.is_tracked(UserFloatSlots()))
self.assertFalse(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)
@requires_type_collecting
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')
@requires_type_collecting
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')
@requires_type_collecting
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()
|
dropcheck_report.py | # -*- coding:utf-8 -*-
import subprocess
import multiprocessing as mp
import time
import os
import json
import yaml
CONFIG_PATH = 'config.yaml'
REPORT_PATH = 'dat/dropcheck_report.json'
def open_config():
'''Get DNS address from config'''
default_config = {'address': {'dns_v4_prime': '1.1.1.1', 'dns_v4_second': '1.0.0.1',
'dns_v6_prime': '2606:4700:4700::1111', 'dns_v6_second': '2606:4700:4700::1001'}}
# ファイルからDNSアドレスを取得(キャッシュサーバを指定して取りに行こう)
if os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH, 'r') as f:
try:
config = yaml.load(f)
except ValueError:
config = default_config
else:
config = default_config
return config
def get_ip_info(command, result_key, q):
'''Get IP information with ifconfig'''
# スペース区切りでifconfigの結果を取得
ifconfig_rslt = subprocess.check_output(
command, shell=True).decode('utf-8')
# 行ごとに分割
ip_info_line = ifconfig_rslt.rstrip('\n').split('\n')
# パースして辞書に格納
ip_info = {'inet': '', 'inet6': {}}
for i in ip_info_line:
line = i.split()
if(line[0] == 'inet'):
ip_info[line[0]] = {line[2]: line[3], line[4]: line[5]}
elif(line[0] == 'inet6'):
ip_info[line[0]][line[1]] = {line[2]: line[3], line[4]: line[5]}
print('FINISH: {}'.format(result_key))
q.put([result_key, ip_info])
def get_ping(command, result_key, q):
'''ping and ping6'''
ping_rslt = subprocess.check_output(command, shell=True).decode('utf-8')
# 結果をパース
ping_rslt_line = ping_rslt.rstrip('\n').split('\n')
ping_out = {}
ping_out['dst'] = ping_rslt_line[0].split()[1]
ping_out['send'] = ping_rslt_line[1].split()[0]
ping_out['recv'] = ping_rslt_line[1].split()[3]
ping_out['loss'] = ping_rslt_line[1].split()[6]
ping_out['round-trip'] = {}
# round_tripの記録
round_trip_item = ping_rslt_line[2].split()[1].split('/')
round_trip_value = ping_rslt_line[2].split()[3].split('/')
for i in range(len(round_trip_item)):
ping_out['round-trip'][round_trip_item[i]] = round_trip_value[i]
print('FINISH: {}'.format(result_key))
q.put([result_key, ping_out])
def get_dns(command, result_key, q):
'''name resolve with dig'''
dig_rslt = subprocess.check_output(command, shell=True).decode('utf-8')
dns = {'server': command.split()[3].lstrip(
'@'), 'result': dig_rslt.rstrip('\n')}
print('FINISH: {}'.format(result_key))
q.put([result_key, dns])
def get_http(command, result_key, q):
'''get http status code'''
http_rslt = subprocess.check_output(
command, shell=True).decode('utf-8').rstrip('\n')
print('FINISH: {}'.format(result_key))
q.put([result_key, http_rslt])
def get_trace(command, result_key, q):
'''traceroute'''
trace_rslt = subprocess.check_output(command, shell=True).decode('utf-8')
trace = json.loads(trace_rslt)
print('FINISH: {}'.format(result_key))
q.put([result_key, trace])
def dropcheck(tasks):
'''run Dropcheck and make report'''
dropcheck_report = {}
# 並列処理用のキュー
q = mp.Queue()
jobs, args = [], []
for i in tasks:
jobs += [eval('get_' + tasks[i]['kind'])]
args += [(tasks[i]['command'], i, q)]
for job, arg in zip(jobs, args):
mp.Process(target=job, args=arg).start()
for i in args:
report = q.get()
# 一度関数に渡しといたkeyで辞書に格納。絶対もっといいやり方ある....
dropcheck_report[report[0]] = report[1]
return dropcheck_report
def update_reports(dropcheck_report):
'''save Dropcheck report to json'''
if os.path.exists(REPORT_PATH):
with open(REPORT_PATH, 'r') as f:
try:
reports = json.load(f)
except ValueError:
reports = {}
else:
reports = {}
reports[time.time()] = dropcheck_report
with open(REPORT_PATH, 'w') as f:
json.dump(reports, f)
def main():
# コンフィグ読み込み
config = open_config()
# 実行コマンド群
tasks = {
# USB ether
'ip_info': {
'command': "networksetup -listallhardwareports | grep -1 USB | sed -n 3p | awk '{print $2}' | xargs -L 1 -I@ ifconfig @ | grep inet | awk '{print $1, $6, \"addr\", $2, $3, $4}'",
'kind': 'ip_info',
},
# airport (for test)
# 'ip_info': {
# 'command': "networksetup -listallhardwareports | grep -1 Wi-Fi | sed -n 3p | awk '{print $2}' | xargs -L 1 -I@ ifconfig @ | grep inet | awk '{print $1, $6, \"addr\", $2, $3, $4}'",
# 'kind': 'ip_info',
# },
'ping_gw': {
'command': 'netstat -rnA -f inet | grep default | awk "{print \$2}" | head -n 1 | xargs -L 1 -I@ ping @ -c 5 -D -s 1472 | grep -1 transmitted',
'kind': 'ping',
},
'ping6_gw': {
'command': 'netstat -rnA -f inet6 | grep default | awk "{print \$2}" | head -n 1 | xargs -L 1 -I@ ping6 @ -c 5 -Dm -s 1452 | grep -1 transmitted',
'kind': 'ping',
},
'ping_out': {
'command': 'ping 1.1.1.1 -c 5 -D -s 1472 | grep -1 transmitted',
'kind': 'ping',
},
'ping6_out': {
'command': 'ping6 2001:200:dff:fff1:216:3eff:feb1:44d7 -c 5 -Dm -s 1452 | grep -1 transmitted',
'kind': 'ping',
},
'dns_v4': {
'command': f'dig www.wide.ad.jp A @{config["address"]["dns_v4_prime"]} +short',
'kind': 'dns',
},
'dns_v6': {
'command': f'dig www.wide.ad.jp AAAA @{config["address"]["dns_v6_prime"]} +short',
'kind': 'dns',
},
# 'dns_v6': {
# 'command': f'dig www.wide.ad.jp AAAA @{config["address"]["dns_v4_prime"]} +short',
# },
'trace_v4': {
'command': 'mtr -c 100 -i 0.1 -wb --report --json 1.1.1.1',
'kind': 'trace',
},
'trace_v6': {
'command': 'mtr -c 100 -i 0.1 -wb --report --json 2001:200:dff:fff1:216:3eff:feb1:44d7',
'kind': 'trace',
},
'http_v4': {
'command': 'curl -s https://ipv4.google.com/ -o /dev/null -w "%{http_code}"',
'kind': 'http',
},
'http_v6': {
'command': 'curl -s https://ipv6.google.com/ -o /dev/null -w "%{http_code}"',
'kind': 'http',
}
}
# Dropcheckレポートを作成
dropcheck_report = dropcheck(tasks)
# 結果をjsonファイルに出力
update_reports(dropcheck_report)
if __name__ == '__main__':
main()
|
__init__.py | import random
import binascii
import string
import re
import os
import pyevmasm as EVMAsm
from .. import Manticore
from ..exceptions import EthereumError, DependencyError, NoAliveStates
from ..core.smtlib import ConstraintSet, Operators, solver, BitVec, Array, ArrayProxy
from ..platforms import evm
from ..core.state import State, TerminateState
from ..utils.helpers import issymbolic, PickleSerializer
from ..utils import config
from ..utils.log import init_logging
import tempfile
from subprocess import Popen, PIPE, check_output
from multiprocessing import Process, Queue
from queue import Empty as EmptyQueue
import sha3
import json
import logging
import io
from ..core.plugin import Plugin
from functools import reduce
# exported externally
from .detectors import Detector, DetectEnvInstruction, DetectExternalCallAndLeak, DetectReentrancySimple, DetectSelfdestruct, DetectUnusedRetVal, DetectDelegatecall, DetectIntegerOverflow, DetectInvalid, DetectReentrancyAdvanced, DetectUninitializedMemory, DetectUninitializedStorage
from .account import EVMAccount, EVMContract
from .abi import ABI
from .solidity import SolidityMetadata
logger = logging.getLogger(__name__)
init_logging() # FIXME(mark): emitting a warning in abi.py does not work unless this is called a second time here
def flagged(flag):
"""
Return special character denoting concretization happened.
"""
return '(*)' if flag else ''
#
# Plugins
#
class FilterFunctions(Plugin):
def __init__(self, regexp=r'.*', mutability='both', depth='both', fallback=False, include=True, **kwargs):
"""Constrain input based on function metadata.
Include or avoid functions selected by the specified criteria.
Examples
Do not explore any human transactions that end up calling a constant function::
no_human_constant = FilterFunctions(depth='human', mutability='constant', include=False)
At human tx depth only accept synthetic check functions::
only_tests = FilterFunctions(regexp=r'mcore_.*', depth='human', include=False)
:param regexp: a regular expression over the name of the function '.*' will match all functions
:param mutability: mutable, constant or both will match functions declared in the abi to be of such class
:param depth: match functions in internal transactions, in human initiated transactions or in both types
:param fallback: if True include the fallback function. Hash will be 00000000 for it
:param include: if False exclude the selected functions, if True include them
"""
super().__init__(**kwargs)
depth = depth.lower()
if depth not in ('human', 'internal', 'both'):
raise ValueError
mutability = mutability.lower()
if mutability not in ('mutable', 'constant', 'both'):
raise ValueError
#fixme better names for member variables
self._regexp = regexp
self._mutability = mutability
self._depth = depth
self._fallback = fallback
self._include = include
def will_open_transaction_callback(self, state, tx):
world = state.platform
tx_cnt = len(world.all_transactions)
# Constrain input only once per tx, per plugin
if state.context.get('constrained%d' % id(self), 0) != tx_cnt:
state.context['constrained%d' % id(self)] = tx_cnt
if self._depth == 'human' and not tx.is_human:
return
if self._depth == 'internal' and tx.is_human:
return
#Get metadata if any for the target address of current tx
md = self.manticore.get_metadata(tx.address)
if md is None:
return
#Let's compile the list of interesting hashes
selected_functions = []
for func_hsh in md.hashes:
if func_hsh == '00000000':
continue
abi = md.get_abi(func_hsh)
func_name = md.get_func_name(func_hsh)
if self._mutability == 'constant' and not abi.get('constant', False):
continue
if self._mutability == 'mutable' and abi.get('constant', False):
continue
if not re.match(self._regexp, func_name):
continue
selected_functions.append(func_hsh)
if self._fallback:
selected_functions.append('00000000')
if self._include:
# constrain the input so it can take only the interesting values
constraint = reduce(Operators.OR, (tx.data[:4] == x for x in selected_functions))
state.constrain(constraint)
else:
#Avoid all not selected hashes
for func_hsh in md.hashes:
if func_hsh in selected_functions:
constraint = tx.data[:4] != func_hsh
state.constrain(constraint)
class LoopDepthLimiter(Plugin):
''' Aborts explorations that are too deep
'''
def __init__(self, loop_count_threshold=5, **kwargs):
super().__init__(**kwargs)
self.loop_count_threshold = loop_count_threshold
def will_start_run_callback(self, *args):
with self.manticore.locked_context('seen_rep', dict) as reps:
reps.clear()
def will_execute_instruction_callback(self, state, pc, insn):
world = state.platform
with self.manticore.locked_context('seen_rep', dict) as reps:
item = (world.current_transaction.sort == 'CREATE', world.current_transaction.address, pc)
if item not in reps:
reps[item] = 0
reps[item] += 1
if reps[item] > self.loop_count_threshold:
state.abandon()
class VerboseTrace(Plugin):
""" Instruction trace plugin
Plugin that collects information about instructions as they are executed by manticore. Computes coverage statistics. Writes output to the `str_trace` in the project directory.
"""
def will_evm_execute_instruction_callback(self, state, instruction, arguments):
current_vm = state.platform.current_vm
state.setdefault('str_trace', []).append(str(current_vm))
def on_finalize(self, state, testcase):
with testcase.open_stream('str_trace') as str_trace_f:
str_trace_f.write('\n'.join(state.context.get('str_trace', [])))
def calculate_coverage(runtime_bytecode, seen):
""" Calculates what percentage of runtime_bytecode has been seen """
count, total = 0, 0
bytecode = SolidityMetadata._without_metadata(runtime_bytecode)
for i in EVMAsm.disassemble_all(bytecode):
if i.pc in seen:
count += 1
total += 1
if total == 0:
#No runtime_bytecode
return 0
return count * 100.0 / total
class ManticoreEVM(Manticore):
""" Manticore EVM manager
Usage Ex::
from manticore.ethereum import ManticoreEVM, ABI
m = ManticoreEVM()
#And now make the contract account to analyze
source_code = '''
pragma solidity ^0.4.15;
contract AnInt {
uint private i=0;
function set(uint value){
i=value
}
}
'''
#Initialize user and contracts
user_account = m.create_account(balance=1000)
contract_account = m.solidity_create_contract(source_code, owner=user_account, balance=0)
contract_account.set(12345, value=100)
m.finalize()
"""
def make_symbolic_buffer(self, size, name=None):
""" Creates a symbolic buffer of size bytes to be used in transactions.
You can operate on it normally and add constraints to manticore.constraints
via manticore.constrain(constraint_expression)
Example use::
symbolic_data = m.make_symbolic_buffer(320)
m.constrain(symbolic_data[0] == 0x65)
m.transaction(caller=attacker_account,
address=contract_account,
data=symbolic_data,
value=100000 )
"""
avoid_collisions = False
if name is None:
name = 'TXBUFFER'
avoid_collisions = True
return self.constraints.new_array(index_bits=256, name=name, index_max=size, value_bits=8, taint=frozenset(), avoid_collisions=avoid_collisions)
def make_symbolic_value(self, nbits=256, name=None):
""" Creates a symbolic value, normally a uint256, to be used in transactions.
You can operate on it normally and add constraints to manticore.constraints
via manticore.constrain(constraint_expression)
Example use::
symbolic_value = m.make_symbolic_value()
m.constrain(symbolic_value > 100)
m.constrain(symbolic_value < 1000)
m.transaction(caller=attacker_account,
address=contract_account,
data=data,
value=symbolic_value )
"""
avoid_collisions = False
if name is None:
name = 'TXVALUE'
avoid_collisions = True
return self.constraints.new_bitvec(nbits, name=name, avoid_collisions=avoid_collisions)
def make_symbolic_address(self, name=None, select='both'):
""" Create symbolic representation of evm address
Create a symbolic variable reprensting an evm address. If no name is provided the variable will be named "TXADDR".
:param name: name for the address
:type name: str
:rtype: :obj:`Expression`
"""
if select not in ('both', 'normal', 'contract'):
raise EthereumError('Wrong selection type')
if select in ('normal', 'contract'):
# FIXME need to select contracts or normal accounts
raise NotImplemented
avoid_collisions = False
if name is None:
name = 'TXADDR'
avoid_collisions = True
return self.constraints.new_bitvec(160, name=name, avoid_collisions=avoid_collisions)
#XXX dead code?
constraint = symbolic_address == 0
for contract_account_i in map(int, self._accounts.values()):
constraint = Operators.OR(symbolic_address == contract_account_i, constraint)
self.constrain(constraint)
return symbolic_address
def constrain(self, constraint):
""" Add constraint
Add a constraint to the model. If the model contains multiple states they all inherit the constraint.
:param constraint: Constraint to add.
:type constraint: :obj:`Expression`
"""
if self.count_states() == 0:
self.constraints.add(constraint)
else:
for state in self.all_states:
state.constrain(constraint)
@staticmethod
def compile(source_code, contract_name=None, libraries=None, runtime=False, solc_bin=None, solc_remaps=[]):
""" Get initialization bytecode from a Solidity source code """
name, source_code, init_bytecode, runtime_bytecode, srcmap, srcmap_runtime, hashes, abi, warnings = ManticoreEVM._compile(source_code, contract_name, libraries, solc_bin, solc_remaps)
if runtime:
return runtime_bytecode
return init_bytecode
@staticmethod
def _link(bytecode, libraries=None):
has_dependencies = '_' in bytecode
hex_contract = bytecode
if has_dependencies:
deps = {}
pos = 0
while pos < len(hex_contract):
if hex_contract[pos] == '_':
# __/tmp/tmp_9k7_l:Manticore______________
lib_placeholder = hex_contract[pos:pos + 40]
lib_name = lib_placeholder.split(':')[1].split('_')[0]
deps.setdefault(lib_name, []).append(pos)
pos += 40
else:
pos += 2
if libraries is None:
raise DependencyError(deps.keys())
libraries = dict(libraries)
hex_contract_lst = list(hex_contract)
for lib_name, pos_lst in deps.items():
try:
lib_address = libraries[lib_name]
except KeyError:
raise DependencyError([lib_name])
for pos in pos_lst:
hex_contract_lst[pos:pos + 40] = '%040x' % int(lib_address)
hex_contract = ''.join(hex_contract_lst)
return bytearray(binascii.unhexlify(hex_contract))
@staticmethod
def _run_solc(source_file, solc_bin=None, solc_remaps=[]):
""" Compile a source file with the Solidity compiler
:param source_file: a file object for the source file
:param solc_bin: path to solc binary
:param solc_remaps: solc import remaps
:return: output, warnings
"""
if solc_bin is not None:
solc = solc_bin
else:
solc = "solc"
#check solc version
supported_versions = ('0.4.18', '0.4.21')
try:
installed_version_output = check_output([solc, "--version"])
except OSError:
raise EthereumError("Solidity compiler not installed.")
m = re.match(r".*Version: (?P<version>(?P<major>\d+)\.(?P<minor>\d+)\.(?P<build>\d+)).*\+(?P<commit>[^\s]+).*", installed_version_output.decode(), re.DOTALL | re.IGNORECASE)
if not m or m.groupdict()['version'] not in supported_versions:
#Fixme https://github.com/trailofbits/manticore/issues/847
#logger.warning("Unsupported solc version %s", installed_version)
pass
#shorten the path size so library placeholders wont fail.
#solc path search is a mess #fixme
#https://solidity.readthedocs.io/en/latest/layout-of-source-files.html
current_folder = os.getcwd()
abs_filename = os.path.abspath(source_file.name)
working_folder, filename = os.path.split(abs_filename)
solc_invocation = [solc] + list(solc_remaps) + [
'--combined-json', 'abi,srcmap,srcmap-runtime,bin,hashes,bin-runtime',
'--allow-paths', '.',
filename
]
p = Popen(solc_invocation, stdout=PIPE, stderr=PIPE, cwd=working_folder)
stdout, stderr = p.communicate()
stdout, stderr = stdout.decode(), stderr.decode()
# See #1123 - solc fails when run within snap
# and https://forum.snapcraft.io/t/interfaces-allow-access-tmp-directory/5129
if stdout == '' and '""%s"" is not found' % filename in stderr:
raise EthereumError(
'Solidity compilation failed with error: {}\n'
'Did you install solc from snap Linux universal packages?\n'
"If so, the problem is likely due to snap's sandbox restricting access to /tmp\n"
'\n'
'Here are some potential solutions:\n'
' 1) Remove solc from snap and install it different way\n'
' 2) Reinstall solc from snap in developer mode, so there is no sandbox\n'
" 3) Find a way to add /tmp to the solc's sandbox. If you do, "
"send us a PR so we could add it here!".format(stderr)
)
try:
return json.loads(stdout), stderr
except ValueError:
raise EthereumError('Solidity compilation error:\n\n{}'.format(stderr))
@staticmethod
def _compile(source_code, contract_name, libraries=None, solc_bin=None, solc_remaps=[]):
""" Compile a Solidity contract, used internally
:param source_code: solidity source as either a string or a file handle
:param contract_name: a string with the name of the contract to analyze
:param libraries: an itemizable of pairs (library_name, address)
:param solc_bin: path to solc binary
:param solc_remaps: solc import remaps
:return: name, source_code, bytecode, srcmap, srcmap_runtime, hashes
:return: name, source_code, bytecode, runtime, srcmap, srcmap_runtime, hashes, abi, warnings
"""
if isinstance(source_code, str):
with tempfile.NamedTemporaryFile('w+') as temp:
temp.write(source_code)
temp.flush()
output, warnings = ManticoreEVM._run_solc(temp, solc_bin, solc_remaps)
elif isinstance(source_code, io.IOBase):
output, warnings = ManticoreEVM._run_solc(source_code, solc_bin, solc_remaps)
source_code.seek(0)
source_code = source_code.read()
else:
raise TypeError(f'source code bad type: {type(source_code).__name__}')
contracts = output.get('contracts', [])
if len(contracts) != 1 and contract_name is None:
raise EthereumError('Solidity file must contain exactly one contract or you must use a contract parameter to specify one.')
name, contract = None, None
if contract_name is None:
name, contract = list(contracts.items())[0]
else:
for n, c in contracts.items():
if n.split(":")[1] == contract_name:
name, contract = n, c
break
if name is None:
raise ValueError('Specified contract not found')
name = name.split(':')[1]
if contract['bin'] == '':
raise EthereumError('Solidity failed to compile your contract.')
bytecode = ManticoreEVM._link(contract['bin'], libraries)
srcmap = contract['srcmap'].split(';')
srcmap_runtime = contract['srcmap-runtime'].split(';')
hashes = {str(x): str(y) for x, y in contract['hashes'].items()}
abi = json.loads(contract['abi'])
runtime = ManticoreEVM._link(contract['bin-runtime'], libraries)
return name, source_code, bytecode, runtime, srcmap, srcmap_runtime, hashes, abi, warnings
@property
def accounts(self):
return dict(self._accounts)
def account_name(self, address):
""" Get account name
If the account specified by `address` has a friendly name, return it. Otherwise return the address as a hexadecimal string.
:param address: address to lookup
:type address: int
:rtype: str
"""
for name, account in self._accounts.items():
if account.address == address:
return name
return '0x{:x}'.format(address)
@property
def normal_accounts(self):
return {name: account for name, account in self._accounts.items() if not isinstance(account, EVMContract)}
@property
def contract_accounts(self):
return {name: account for name, account in self._accounts.items() if isinstance(account, EVMContract)}
def get_account(self, name):
""" Get EVMAccount from name
Given a name, return the corresponding account.
:param name: name of account
:type name: str
:rtype: :class:`EVMAccount`
"""
return self._accounts[name]
def __init__(self, procs=10, **kwargs):
""" A Manticore EVM manager
:param int procs: number of workers to use in the exploration
"""
self._accounts = dict()
self._serializer = PickleSerializer()
self._config_procs = procs
# Make the constraint store
constraints = ConstraintSet()
# make the ethereum world state
world = evm.EVMWorld(constraints, initial_timestamp=1524785992)
initial_state = State(constraints, world)
super().__init__(initial_state, **kwargs)
self.constraints = ConstraintSet()
self.detectors = {}
self.metadata = {}
# The following should go to manticore.context so we can use multiprocessing
self.context['ethereum'] = {}
self.context['ethereum']['_saved_states'] = set()
self.context['ethereum']['_final_states'] = set()
self.context['ethereum']['_completed_transactions'] = 0
self.context['ethereum']['_sha3_states'] = dict()
self.context['ethereum']['_known_sha3'] = set()
self._executor.subscribe('did_load_state', self._load_state_callback)
self._executor.subscribe('will_terminate_state', self._terminate_state_callback)
self._executor.subscribe('did_evm_execute_instruction', self._did_evm_execute_instruction_callback)
self._executor.subscribe('did_read_code', self._did_evm_read_code)
self._executor.subscribe('on_symbolic_sha3', self._on_symbolic_sha3_callback)
self._executor.subscribe('on_concrete_sha3', self._on_concrete_sha3_callback)
@property
def world(self):
""" The world instance or None if there is more than one state """
return self.get_world()
@property
def completed_transactions(self):
with self.locked_context('ethereum') as context:
return context['_completed_transactions']
@property
def _running_state_ids(self):
""" IDs of the running states"""
with self.locked_context('ethereum') as context:
if self.initial_state is not None:
return (-1,) + tuple(context['_saved_states'])
else:
return tuple(context['_saved_states'])
@property
def _terminated_state_ids(self):
""" IDs of the terminated states """
with self.locked_context('ethereum') as context:
return tuple(context['_final_states'])
@property
def _all_state_ids(self):
""" IDs of the all states
Note: state with id -1 is already in memory and it is not backed on the storage
"""
return self._running_state_ids + self._terminated_state_ids
@property
def running_states(self):
""" Iterates over the running states"""
for state_id in self._running_state_ids:
state = self.load(state_id)
yield state
self.save(state, state_id=state_id) # overwrite old
@property
def terminated_states(self):
""" Iterates over the terminated states"""
for state_id in self._terminated_state_ids:
state = self.load(state_id)
yield state
self.save(state, state_id=state_id) # overwrite old
@property
def all_states(self):
""" Iterates over the all states (terminated and alive)"""
for state_id in self._all_state_ids:
state = self.load(state_id)
yield state
self.save(state, state_id=state_id) # overwrite old
def count_states(self):
""" Total states count """
return len(self._all_state_ids)
def count_running_states(self):
""" Running states count """
return len(self._running_state_ids)
def count_terminated_states(self):
""" Terminated states count """
return len(self._terminated_state_ids)
def _terminate_state_id(self, state_id):
""" Manually terminates a states by state_id.
Moves the state from the running list into the terminated list
"""
if state_id != -1:
# Move state from running to final
with self.locked_context('ethereum') as eth_context:
saved_states = eth_context['_saved_states']
final_states = eth_context['_final_states']
if state_id in saved_states:
saved_states.remove(state_id)
final_states.add(state_id)
eth_context['_saved_states'] = saved_states # TODO This two may be not needed in py3?
eth_context['_final_states'] = final_states
else:
assert state_id == -1
state_id = self.save(self._initial_state, final=True)
self._initial_state = None
return state_id
def _revive_state_id(self, state_id):
""" Manually revive a state by state_id.
Moves the state from the final list into the running list
"""
# Move state from final to running
if state_id != -1:
with self.locked_context('ethereum') as eth_context:
saved_states = eth_context['_saved_states']
final_states = eth_context['_final_states']
if state_id in final_states:
final_states.remove(state_id)
saved_states.add(state_id)
eth_context['_saved_states'] = saved_states
eth_context['_final_states'] = final_states
return state_id
# deprecate this 5 in favor of for sta in m.all_states: do stuff?
def get_world(self, state_id=None):
""" Returns the evm world of `state_id` state. """
state = self.load(state_id)
if state is None:
return None
else:
return state.platform
def get_balance(self, address, state_id=None):
""" Balance for account `address` on state `state_id` """
if isinstance(address, EVMAccount):
address = int(address)
return self.get_world(state_id).get_balance(address)
def get_storage_data(self, address, offset, state_id=None):
""" Storage data for `offset` on account `address` on state `state_id` """
if isinstance(address, EVMAccount):
address = int(address)
return self.get_world(state_id).get_storage_data(address, offset)
def get_code(self, address, state_id=None):
""" Storage data for `offset` on account `address` on state `state_id` """
if isinstance(address, EVMAccount):
address = int(address)
return self.get_world(state_id).get_code(address)
def last_return(self, state_id=None):
""" Last returned buffer for state `state_id` """
state = self.load(state_id)
return state.platform.last_return_data
def transactions(self, state_id=None):
""" Transactions list for state `state_id` """
state = self.load(state_id)
return state.platform.transactions
def make_symbolic_arguments(self, types):
"""
Make a reasonable serialization of the symbolic argument types
"""
# FIXME this is more naive than reasonable.
return ABI.deserialize(types, self.make_symbolic_buffer(32, name="INITARGS"))
def solidity_create_contract(self, source_code, owner, name=None, contract_name=None, libraries=None, balance=0, address=None, args=(), solc_bin=None, solc_remaps=[], gas=90000):
""" Creates a solidity contract and library dependencies
:param str source_code: solidity source code
:param owner: owner account (will be default caller in any transactions)
:type owner: int or EVMAccount
:param contract_name: Name of the contract to analyze (optional if there is a single one in the source code)
:type contract_name: str
:param balance: balance to be transferred on creation
:type balance: int or SValue
:param address: the address for the new contract (optional)
:type address: int or EVMAccount
:param tuple args: constructor arguments
:param solc_bin: path to solc binary
:type solc_bin: str
:param solc_remaps: solc import remaps
:type solc_remaps: list of str
:param gas: gas budget for each contract creation needed (may be more than one if several related contracts defined in the solidity source)
:type gas: int
:rtype: EVMAccount
"""
if libraries is None:
deps = {}
else:
deps = dict(libraries)
contract_names = [contract_name]
while contract_names:
contract_name_i = contract_names.pop()
try:
compile_results = self._compile(source_code, contract_name_i, libraries=deps, solc_bin=solc_bin, solc_remaps=solc_remaps)
md = SolidityMetadata(*compile_results)
if contract_name_i == contract_name:
constructor_types = md.get_constructor_arguments()
if args is None:
args = self.make_symbolic_arguments(constructor_types)
contract_account = self.create_contract(owner=owner,
balance=balance,
address=address,
init=md._init_bytecode + ABI.serialize(constructor_types, *args),
name=name,
gas=gas)
else:
contract_account = self.create_contract(owner=owner, init=md._init_bytecode)
if contract_account is None:
raise EthereumError("Failed to build contract %s" % contract_name_i)
self.metadata[int(contract_account)] = md
deps[contract_name_i] = contract_account
except DependencyError as e:
contract_names.append(contract_name_i)
for lib_name in e.lib_names:
if lib_name not in deps:
contract_names.append(lib_name)
if not self.count_running_states() or len(self.get_code(contract_account)) == 0:
return None
return contract_account
def create_contract(self, owner, balance=0, address=None, init=None, name=None, gas=21000):
""" Creates a contract
:param owner: owner account (will be default caller in any transactions)
:type owner: int or EVMAccount
:param balance: balance to be transferred on creation
:type balance: int or SValue
:param int address: the address for the new contract (optional)
:param str init: initializing evm bytecode and arguments
:param str name: a unique name for reference
:param gas: gas budget for the creation/initialization of the contract
:rtype: EVMAccount
"""
if not self.count_running_states():
raise NoAliveStates
if address is not None and address in map(int, self.accounts.values()):
# Address already used
raise EthereumError("Address already used")
# Let's just choose the address ourself. This is not yellow paper material
if address is None:
address = self.new_address()
# Name check
if name is None:
name = self._get_uniq_name("contract")
if name in self._accounts:
# Account name already used
raise EthereumError("Name already used")
self._transaction('CREATE', owner, balance, address, data=init, gaslimit=gas)
# TODO detect failure in the constructor
self._accounts[name] = EVMContract(address=address, manticore=self, default_caller=owner, name=name)
return self.accounts[name]
def _get_uniq_name(self, stem):
count = 0
for name_i in self.accounts.keys():
if name_i.startswith(stem):
try:
count = max(count, int(name_i[len(stem):]) + 1)
except:
pass
name = "{:s}{:d}".format(stem, count)
assert name not in self.accounts
return name
def new_address(self):
""" Create a fresh 160bit address """
new_address = random.randint(100, pow(2, 160))
if new_address in map(int, self.accounts.values()):
return self.new_address()
return new_address
def transaction(self, caller, address, value, data, gas=21000):
""" Issue a symbolic transaction in all running states
:param caller: the address of the account sending the transaction
:type caller: int or EVMAccount
:param address: the address of the contract to call
:type address: int or EVMAccount
:param value: balance to be transfered on creation
:type value: int or SValue
:param data: initial data
:param gas: gas budget
:raises NoAliveStates: if there are no alive states to execute
"""
self._transaction('CALL', caller, value=value, address=address, data=data, gaslimit=gas)
def create_account(self, balance=0, address=None, code=None, name=None):
""" Low level creates an account. This won't generate a transaction.
:param balance: balance to be set on creation (optional)
:type balance: int or SValue
:param address: the address for the new account (optional)
:type address: int
:param code: the runtime code for the new account (None means normal account) (optional)
:param name: a global account name eg. for use as reference in the reports (optional)
:type name: str
:return: an EVMAccount
"""
# Need at least one state where to apply this
if not self.count_running_states():
raise NoAliveStates
# Name check
if name is None:
if code is None:
name = self._get_uniq_name("normal")
else:
name = self._get_uniq_name("contract")
if name in self._accounts:
# Account name already used
raise EthereumError("Name already used")
#Balance check
if not isinstance(balance, int):
raise EthereumError("Balance invalid type")
if isinstance(code, str):
code = bytearray(code)
if code is not None and not isinstance(code, (bytearray, Array)):
raise EthereumError("code bad type")
# Address check
# Let's just choose the address ourself. This is not yellow paper material
if address is None:
address = self.new_address()
if not isinstance(address, int):
raise EthereumError("A concrete address is needed")
assert address is not None
if address in map(int, self.accounts.values()):
# Address already used
raise EthereumError("Address already used")
# To avoid going full crazy we maintain a global list of addresses
# Different states may CREATE a different set of accounts.
# Accounts created by a human have the same address in all states.
for state in self.running_states:
world = state.platform
if '_pending_transaction' in state.context:
raise EthereumError("This is bad. There should not be a pending transaction")
if address in world.accounts:
# Address already used
raise EthereumError("This is bad. Same address is used for different contracts in different states")
world.create_account(address, balance, code=code, storage=None)
self._accounts[name] = EVMAccount(address, manticore=self, name=name)
return self.accounts[name]
def _migrate_tx_expressions(self, state, caller, address, value, data):
# Copy global constraints into each state.
# We should somehow remember what has been copied to each state
# In a second transaction we should only add new constraints.
# And actually only constraints related to whatever we are using in
# the tx. This is a FIXME
global_constraints = self.constraints
# Normally users will be making these symbolic expressions by creating
# global symbolic variables via ManticoreEVM.make_.... and those
# global expressions need to be imported into each state when a tx
# actually happens
if issymbolic(caller):
caller = state.migrate_expression(caller)
if issymbolic(address):
address = state.migrate_expression(address)
if issymbolic(value):
value = state.migrate_expression(value)
if issymbolic(data):
if isinstance(data, ArrayProxy): # FIXME is this necessary here?
data = data.array
data = state.migrate_expression(data)
if isinstance(data, Array):
data = ArrayProxy(data)
for c in global_constraints:
state.constrain(c)
return caller, address, value, data
def _transaction(self, sort, caller, value=0, address=None, data=None, gaslimit=0, price=1):
""" Initiates a transaction
:param caller: caller account
:type caller: int or EVMAccount
:param int address: the address for the transaction (optional)
:param value: value to be transferred
:param price: the price of gas for this transaction. Mostly unused.
:type value: int or SValue
:param str data: initializing evm bytecode and arguments or transaction call data
:param gaslimit: gas budget
:rtype: EVMAccount
"""
#Type Forgiveness
if isinstance(address, EVMAccount):
address = int(address)
if isinstance(caller, EVMAccount):
caller = int(caller)
#Defaults, call data is empty
if data is None:
data = bytearray(b"")
if isinstance(data, (str, bytes)):
data = bytearray(data)
if not isinstance(data, (bytearray, Array)):
raise EthereumError("code bad type")
# Check types
if not isinstance(address, (int, BitVec)):
raise EthereumError("Caller invalid type")
if not isinstance(value, (int, BitVec)):
raise EthereumError("Value invalid type")
if not isinstance(address, (int, BitVec)):
raise EthereumError("address invalid type")
if not isinstance(price, int):
raise EthereumError("Price invalid type")
# Check argument consistency and set defaults ...
if sort not in ('CREATE', 'CALL'):
raise ValueError('unsupported transaction type')
if sort == 'CREATE':
#let's choose an address here for now #NOTYELLOW
if address is None:
address = self.new_address()
# When creating data is the init_bytecode + arguments
if len(data) == 0:
raise EthereumError("An initialization bytecode is needed for a CREATE")
assert address is not None
assert caller is not None
# Transactions (like everything else) need at least one running state
if not self.count_running_states():
raise NoAliveStates
# To avoid going full crazy, we maintain a global list of addresses
for state in self.running_states:
world = state.platform
if '_pending_transaction' in state.context:
raise EthereumError("This is bad. It should not be a pending transaction")
# Migrate any expression to state specific constraint set
caller, address, value, data = self._migrate_tx_expressions(state, caller, address, value, data)
# Different states may CREATE a different set of accounts. Accounts
# that were crated by a human have the same address in all states.
# This diverges from the yellow paper but at least we check that we
# are not trying to create an already used address here
if sort == 'CREATE':
if address in world.accounts:
# Address already used
raise EthereumError("This is bad. Same address is used for different contracts in different states")
state.context['_pending_transaction'] = (sort, caller, address, value, data, gaslimit, price)
# run over potentially several states and
# generating potentially several others
self.run(procs=self._config_procs)
return address
def multi_tx_analysis(self, solidity_filename, contract_name=None, tx_limit=None, tx_use_coverage=True, tx_send_ether=True, tx_account="attacker", args=None):
""" Perform symbilic exploration of contract
Execute symbolic transactions against the contract until all paths are explored or `tx_limit` is hit.
:param solidity_filename: Filename containing contract to analyze
:type solidity_filename: str
:param contract_name: Name of contract to analyze
:type contract_name: str
:param tx_limit: The maximum number of transactions to execute before halting. If left unspecified analysis will continue until no more code can be explored.
:type tx_limit: int optional [Default=None]
:param tx_use_coverage:
:type tx_use_coverage: bool [Default=True]
:param tx_send_ether:
:type tx_send_ether: bool [Default=True]
:param tx_account: Name of account initiating transactions against contract
:type tx_account: str [Default=attacker]
:param args: Named arguments to pass to :meth:`create_contract`
:type args: dict [Default=None]
:rtype: None
"""
owner_account = self.create_account(balance=1000, name='owner')
attacker_account = self.create_account(balance=1000, name='attacker')
# Pretty print
logger.info("Starting symbolic create contract")
with open(solidity_filename) as f:
contract_account = self.solidity_create_contract(f, contract_name=contract_name, owner=owner_account, args=args)
if tx_account == "attacker":
tx_account = [attacker_account]
elif tx_account == "owner":
tx_account = [owner_account]
elif tx_account == "combo1":
tx_account = [owner_account, attacker_account]
else:
raise EthereumError('The account to perform the symbolic exploration of the contract should be "attacker", "owner" or "combo1"')
if contract_account is None:
logger.info("Failed to create contract: exception in constructor")
return
prev_coverage = 0
current_coverage = 0
tx_no = 0
while (current_coverage < 100 or not tx_use_coverage) and not self.is_shutdown():
try:
logger.info("Starting symbolic transaction: %d", tx_no)
# run_symbolic_tx
symbolic_data = self.make_symbolic_buffer(320)
if tx_send_ether:
value = self.make_symbolic_value()
else:
value = 0
self.transaction(caller=tx_account[min(tx_no, len(tx_account) - 1)],
address=contract_account,
data=symbolic_data,
value=value,
gas=2100000)
logger.info("%d alive states, %d terminated states", self.count_running_states(), self.count_terminated_states())
except NoAliveStates:
break
# Check if the maximum number of tx was reached
if tx_limit is not None and tx_no + 1 == tx_limit:
break
# Check if coverage has improved or not
if tx_use_coverage:
prev_coverage = current_coverage
current_coverage = self.global_coverage(contract_account)
found_new_coverage = prev_coverage < current_coverage
if not found_new_coverage:
break
tx_no += 1
def run(self, **kwargs):
""" Run any pending transaction on any running state """
# Check if there is a pending transaction
with self.locked_context('ethereum') as context:
# there are no states added to the executor queue
assert len(self._executor.list()) == 0
for state_id in context['_saved_states']:
self._executor.put(state_id)
context['_saved_states'] = set()
# A callback will use _pending_transaction and issue the transaction
# in each state (see load_state_callback)
super().run(**kwargs)
with self.locked_context('ethereum') as context:
if len(context['_saved_states']) == 1:
self._initial_state = self._executor._workspace.load_state(context['_saved_states'].pop(), delete=True)
context['_saved_states'] = set()
assert self._running_state_ids == (-1,)
def save(self, state, state_id=None, final=False):
""" Save a state in secondary storage and add it to running or final lists
:param state: A manticore State
:param state_id: if not None force state_id (overwrite)
:param final: True if state is final
:returns: a state id
"""
# If overwriting then the state_id must be known
if state_id is not None:
if state_id not in self._all_state_ids:
raise EthereumError("Trying to overwrite unknown state_id")
with self.locked_context('ethereum') as context:
context['_final_states'].discard(state_id)
context['_saved_states'].discard(state_id)
if state_id != -1:
# save the state to secondary storage
state_id = self._executor._workspace.save_state(state, state_id=state_id)
with self.locked_context('ethereum') as context:
if final:
# Keep it on a private list
context['_final_states'].add(state_id)
else:
# Keep it on a private list
context['_saved_states'].add(state_id)
return state_id
def load(self, state_id=None):
""" Load one of the running or final states.
:param state_id: If None it assumes there is a single running state
:type state_id: int or None
"""
state = None
if state_id is None:
#a single state was assumed
if self.count_running_states() == 1:
#Get the ID of the single running state
state_id = self._running_state_ids[0]
else:
raise EthereumError("More than one state running; you must specify a state id.")
if state_id == -1:
state = self.initial_state
else:
state = self._executor._workspace.load_state(state_id, delete=False)
#froward events from newly loaded object
self._executor.forward_events_from(state, True)
return state
# Callbacks
def _on_symbolic_sha3_callback(self, state, data, known_hashes):
""" INTERNAL USE """
assert issymbolic(data), 'Data should be symbolic here!'
with self.locked_context('ethereum') as context:
known_sha3 = context.get('_known_sha3', None)
if known_sha3 is None:
known_sha3 = set()
sha3_states = context.get('_sha3_states', [])
results = []
# If know_hashes is true then there is a _known_ solution for the hash
known_hashes_cond = False
for key, value in known_sha3:
assert not issymbolic(key), "Saved sha3 data,hash pairs should be concrete"
cond = key == data
#TODO consider disabling this solver query.
if not state.can_be_true(cond):
continue
results.append((key, value))
known_hashes_cond = Operators.OR(cond, known_hashes_cond)
# adding a single random example so we can explore further in case
# there are not known sha3 pairs that match yet
if not results:
data_concrete = state.solve_one(data)
s = sha3.keccak_256(data_concrete)
data_hash = int(s.hexdigest(), 16)
results.append((data_concrete, data_hash))
known_hashes_cond = data_concrete == data
known_sha3.add((data_concrete, data_hash))
not_known_hashes_cond = Operators.NOT(known_hashes_cond)
# We need to fork/save the state
#################################
# save the state to secondary storage
# Build and enqueue a state for each solution
with state as temp_state:
if temp_state.can_be_true(not_known_hashes_cond):
temp_state.constrain(not_known_hashes_cond)
state_id = self._executor._workspace.save_state(temp_state)
sha3_states[state_id] = [hsh for buf, hsh in known_sha3]
context['_sha3_states'] = sha3_states
if not state.can_be_true(known_hashes_cond):
raise TerminateState("There is no matching sha3 pair, bailing out")
state.constrain(known_hashes_cond)
#send known hashes to evm
known_hashes.update(results)
def _on_concrete_sha3_callback(self, state, buf, value):
""" INTERNAL USE """
with self.locked_context('ethereum', dict) as ethereum_context:
known_sha3 = ethereum_context.get('_known_sha3', None)
if known_sha3 is None:
known_sha3 = set()
known_sha3.add((buf, value))
ethereum_context['_known_sha3'] = known_sha3
def _terminate_state_callback(self, state, state_id, e):
""" INTERNAL USE
Every time a state finishes executing the last transaction, we save it in
our private list
"""
if str(e) == 'Abandoned state':
#do nothing
return
world = state.platform
state.context['last_exception'] = e
e.testcase = False # Do not generate a testcase file
if not world.all_transactions:
logger.debug("Something went wrong: search terminated in the middle of an ongoing tx")
self.save(state, final=True)
return
tx = world.all_transactions[-1]
#we initiated the Tx; we need process the outcome for now.
#Fixme incomplete.
if tx.is_human():
if tx.sort == 'CREATE':
if tx.result == 'RETURN':
world.set_code(tx.address, tx.return_data)
else:
world.delete_account(tx.address)
else:
logger.info("Manticore exception: state should be terminated only at the end of the human transaction")
#Human tx that ends in this wont modify the storage so finalize and
# generate a testcase. FIXME This should be configurable as REVERT and
# THROW; it actually changes the balance and nonce? of some accounts
if tx.result in {'SELFDESTRUCT', 'REVERT', 'THROW', 'TXERROR'}:
self.save(state, final=True)
elif tx.result in {'RETURN', 'STOP'}:
# if not a revert, we save the state for further transactions
self.save(state) # Add to running states
else:
logger.debug("Exception in state. Discarding it")
#Callbacks
def _load_state_callback(self, state, state_id):
""" INTERNAL USE
If a state was just loaded from storage, we do the pending transaction
"""
if '_pending_transaction' not in state.context:
return
world = state.platform
ty, caller, address, value, data, gaslimit, price = state.context['_pending_transaction']
del state.context['_pending_transaction']
if ty == 'CALL':
world.transaction(address=address, caller=caller, data=data, value=value, price=price, gas=gaslimit)
else:
assert ty == 'CREATE'
world.create_contract(caller=caller, address=address, balance=value, init=data, price=price, gas=gaslimit)
def _did_evm_execute_instruction_callback(self, state, instruction, arguments, result):
""" INTERNAL USE """
#logger.debug("%s", state.platform.current_vm)
#TODO move to a plugin
at_init = state.platform.current_transaction.sort == 'CREATE'
if at_init:
coverage_context_name = 'init_coverage'
else:
coverage_context_name = 'runtime_coverage'
with self.locked_context(coverage_context_name, set) as coverage:
coverage.add((state.platform.current_vm.address, instruction.pc))
state.context.setdefault('evm.trace', []).append((state.platform.current_vm.address, instruction.pc, at_init))
def _did_evm_read_code(self, state, offset, size):
""" INTERNAL USE """
with self.locked_context('code_data', set) as code_data:
for i in range(offset, offset + size):
code_data.add((state.platform.current_vm.address, i))
def get_metadata(self, address):
""" Gets the solidity metadata for address.
This is available only if address is a contract created from solidity
"""
return self.metadata.get(int(address))
def register_detector(self, d):
""" Register detector plugin
Register a detector plugin. The plugin will run it's analusis as the contract is executing.
:param d: Instantiated detector object to be registered.
:type d: :obj:`Detector`
:return: Name of detector.
:rtype: str
"""
if not isinstance(d, Detector):
raise EthereumError("Not a Detector")
if d.name in self.detectors:
raise EthereumError("Detector already registered")
self.detectors[d.name] = d
self.register_plugin(d)
return d.name
def unregister_detector(self, d):
""" Remove registered detector
Unregister a detector plugin, thereby preventing additional analysis.
:param d: Detector object to be removed.
:type d: :obj:`Detector`
:rtype: None
"""
if not isinstance(d, (Detector, str)):
raise EthereumError("Not a Detector")
name = d
if isinstance(d, Detector):
name = d.name
if name not in self.detectors:
raise EthereumError("Detector not registered")
d = self.detectors[name]
del self.detectors[name]
self.unregister_plugin(d)
@property
def workspace(self):
return self._executor._workspace._store.uri
def generate_testcase(self, state, name, message=''):
""" Generate testcase for state
Generate reproducable, named, testcase for a given state.
:param state: state to generate testcase for
:type state: :class:`manticore.core.state.State`
:param name: name to give the state
:type name: str
:param message: message accompanying the state
:type message: optional str
:rtype: None
"""
self._generate_testcase_callback(state, name, message)
def current_location(self, state):
""" Get current location of EVM program counter
Returns the current location and brief analysis of EVM program counter.
:param state: State to introspect on
:type state: :class:`manticore.core.state.State`
:rtype: str
"""
world = state.platform
address = world.current_vm.address
pc = world.current_vm.pc
at_init = world.current_transaction.sort == 'CREATE'
output = io.StringIO()
output.write('Contract: 0x{:x}\n'.format(address))
output.write('EVM Program counter: 0x{:x}{:s}\n'.format(pc, at_init and " (at constructor)" or ""))
md = self.get_metadata(address)
if md is not None:
src = md.get_source_for(pc, runtime=not at_init)
output.write('Snippet:\n')
output.write(src.replace('\n', '\n ').strip())
output.write('\n')
return output.getvalue()
def _generate_testcase_callback(self, state, name, message=''):
"""
Create a serialized description of a given state.
:param state: The state to generate information about
:param message: Accompanying message
"""
# workspace should not be responsible for formating the output
# each object knows its secrets, and each class should be able to report its
# final state
#super()._generate_testcase_callback(state, name, message)
# TODO(mark): Refactor ManticoreOutput to let the platform be more in control
# so this function can be fully ported to EVMWorld.generate_workspace_files.
blockchain = state.platform
testcase = self._output.testcase(name.replace(' ', '_'))
last_tx = blockchain.last_transaction
if last_tx:
message = message + last_tx.result
logger.info("Generated testcase No. {} - {}".format(testcase.num, message))
local_findings = set()
for detector in self.detectors.values():
for address, pc, finding, at_init, constraint in detector.get_findings(state):
if (address, pc, finding, at_init) not in local_findings:
local_findings.add((address, pc, finding, at_init, constraint))
if len(local_findings):
with testcase.open_stream('findings') as findings:
for address, pc, finding, at_init, constraint in local_findings:
findings.write('- %s -\n' % finding)
findings.write(' Contract: 0x%x\n' % address)
findings.write(' EVM Program counter: 0x%x%s\n' % (pc, at_init and " (at constructor)" or ""))
md = self.get_metadata(address)
if md is not None:
src = md.get_source_for(pc, runtime=not at_init)
findings.write(' Snippet:\n')
findings.write(src.replace('\n', '\n ').strip())
findings.write('\n')
with testcase.open_stream('summary') as stream:
is_something_symbolic = state.platform.dump(stream, state, self, message)
with self.locked_context('ethereum') as context:
known_sha3 = context.get('_known_sha3', None)
if known_sha3:
stream.write("Known hashes:\n")
for key, value in known_sha3:
stream.write('%s::%x\n' % (binascii.hexlify(key), value))
if is_something_symbolic:
stream.write('\n\n(*) Example solution given. Value is symbolic and may take other values\n')
# Transactions
with testcase.open_stream('tx') as tx_summary:
with testcase.open_stream('tx.json') as txjson:
txlist = []
is_something_symbolic = False
for sym_tx in blockchain.human_transactions: # external transactions
tx_summary.write("Transactions No. %d\n" % blockchain.transactions.index(sym_tx))
conc_tx = sym_tx.concretize(state)
txlist.append(conc_tx.to_dict(self))
is_something_symbolic = sym_tx.dump(tx_summary, state, self, conc_tx=conc_tx)
if is_something_symbolic:
tx_summary.write('\n\n(*) Example solution given. Value is symbolic and may take other values\n')
json.dump(txlist, txjson)
# logs
with testcase.open_stream('logs') as logs_summary:
is_something_symbolic = False
for log_item in blockchain.logs:
is_log_symbolic = issymbolic(log_item.memlog)
is_something_symbolic = is_log_symbolic or is_something_symbolic
solved_memlog = state.solve_one(log_item.memlog)
printable_bytes = ''.join([c for c in map(chr, solved_memlog) if c in string.printable])
logs_summary.write("Address: %x\n" % log_item.address)
logs_summary.write("Memlog: %s (%s) %s\n" % (binascii.hexlify(solved_memlog).decode(), printable_bytes, flagged(is_log_symbolic)))
logs_summary.write("Topics:\n")
for i, topic in enumerate(log_item.topics):
logs_summary.write("\t%d) %x %s" % (i, state.solve_one(topic), flagged(issymbolic(topic))))
with testcase.open_stream('constraints') as smt_summary:
smt_summary.write(str(state.constraints))
with testcase.open_stream('pkl', binary=True) as statef:
self._serializer.serialize(state, statef)
trace = state.context.get('evm.trace')
if trace:
with testcase.open_stream('trace') as f:
self._emit_trace_file(f, trace)
return testcase
@staticmethod
def _emit_trace_file(filestream, trace):
"""
:param filestream: file object for the workspace trace file
:param trace: list of (contract address, pc) tuples
:type trace: list[tuple(int, int)]
"""
for contract, pc, at_init in trace:
if pc == 0:
filestream.write('---\n')
ln = '0x{:x}:0x{:x} {}\n'.format(contract, pc, '*' if at_init else '')
filestream.write(ln)
@property
def global_findings(self):
global_findings = set()
for detector in self.detectors.values():
for address, pc, finding, at_init in detector.global_findings:
if (address, pc, finding, at_init) not in global_findings:
global_findings.add((address, pc, finding, at_init))
return global_findings
def finalize(self):
"""
Terminate and generate testcases for all currently alive states (contract states that cleanly executed
to a STOP or RETURN in the last symbolic transaction).
"""
logger.debug("Finalizing %d states.", self.count_states())
def finalizer(state_id):
state_id = self._terminate_state_id(state_id)
st = self.load(state_id)
logger.debug("Generating testcase for state_id %d", state_id)
self._generate_testcase_callback(st, 'test', '')
def worker_finalize(q):
try:
while True:
finalizer(q.get_nowait())
except EmptyQueue:
pass
q = Queue()
for state_id in self._all_state_ids:
#we need to remove -1 state before forking because it may be in memory
if state_id == -1:
finalizer(-1)
else:
q.put(state_id)
report_workers = []
for _ in range(self._config_procs):
proc = Process(target=worker_finalize, args=(q,))
proc.start()
report_workers.append(proc)
for proc in report_workers:
proc.join()
#global summary
if len(self.global_findings):
with self._output.save_stream('global.findings') as global_findings:
for address, pc, finding, at_init in self.global_findings:
global_findings.write('- %s -\n' % finding)
global_findings.write(' Contract: %s\n' % address)
global_findings.write(' EVM Program counter: 0x%x%s\n' % (pc, at_init and " (at constructor)" or ""))
md = self.get_metadata(address)
if md is not None:
source_code_snippet = md.get_source_for(pc, runtime=not at_init)
global_findings.write(' Solidity snippet:\n')
global_findings.write(' '.join(source_code_snippet.splitlines(True)))
global_findings.write('\n')
with self._output.save_stream('manticore.yml') as f:
config.save(f)
with self._output.save_stream('global.summary') as global_summary:
# (accounts created by contract code are not in this list )
global_summary.write("Global runtime coverage:\n")
for address in self.contract_accounts.values():
global_summary.write("{:x}: {:2.2f}%\n".format(int(address), self.global_coverage(address)))
md = self.get_metadata(address)
if md is not None and len(md.warnings) > 0:
global_summary.write('\n\nCompiler warnings for %s:\n' % md.name)
global_summary.write(md.warnings)
for address, md in self.metadata.items():
with self._output.save_stream('global_%s.sol' % md.name) as global_src:
global_src.write(md.source_code)
with self._output.save_stream('global_%s_runtime.bytecode' % md.name, binary=True) as global_runtime_bytecode:
global_runtime_bytecode.write(md.runtime_bytecode)
with self._output.save_stream('global_%s_init.bytecode' % md.name, binary=True) as global_init_bytecode:
global_init_bytecode.write(md.init_bytecode)
with self._output.save_stream('global_%s.runtime_asm' % md.name) as global_runtime_asm:
runtime_bytecode = md.runtime_bytecode
with self.locked_context('runtime_coverage') as seen:
count, total = 0, 0
for i in EVMAsm.disassemble_all(runtime_bytecode):
if (address, i.pc) in seen:
count += 1
global_runtime_asm.write('*')
else:
global_runtime_asm.write(' ')
global_runtime_asm.write('%4x: %s\n' % (i.pc, i))
total += 1
with self._output.save_stream('global_%s.init_asm' % md.name) as global_init_asm:
with self.locked_context('init_coverage') as seen:
count, total = 0, 0
for i in EVMAsm.disassemble_all(md.init_bytecode):
if (address, i.pc) in seen:
count += 1
global_init_asm.write('*')
else:
global_init_asm.write(' ')
global_init_asm.write('%4x: %s\n' % (i.pc, i))
total += 1
with self._output.save_stream('global_%s.init_visited' % md.name) as f:
with self.locked_context('init_coverage') as seen:
visited = set((o for (a, o) in seen if a == address))
for o in sorted(visited):
f.write('0x%x\n' % o)
with self._output.save_stream('global_%s.runtime_visited' % md.name) as f:
with self.locked_context('runtime_coverage') as seen:
visited = set()
for (a, o) in seen:
if a == address:
visited.add(o)
for o in sorted(visited):
f.write('0x%x\n' % o)
# delete actual streams from storage
for state_id in self._all_state_ids:
# state_id -1 is always only on memory
if state_id != -1:
self._executor._workspace.rm_state(state_id)
# clean up lists
with self.locked_context('ethereum') as eth_context:
eth_context['_saved_states'] = set()
eth_context['_final_states'] = set()
logger.info("Results in %s", self.workspace)
def global_coverage(self, account):
""" Returns code coverage for the contract on `account_address`.
This sums up all the visited code lines from any of the explored
states.
"""
account_address = int(account)
runtime_bytecode = None
#Search one state in which the account_address exists
for state in self.all_states:
world = state.platform
if account_address in world:
code = world.get_code(account_address)
runtime_bytecode = state.solve_one(code)
break
else:
return 0.0
with self.locked_context('runtime_coverage') as coverage:
seen = {off for addr, off in coverage if addr == account_address}
return calculate_coverage(runtime_bytecode, seen)
# TODO: Find a better way to suppress execution of Manticore._did_finish_run_callback
# We suppress because otherwise we log it many times and it looks weird.
def _did_finish_run_callback(self):
pass
|
test_dataloader.py | import math
import sys
import errno
import os
import ctypes
import faulthandler
import torch
import gc
import time
import signal
import unittest
import itertools
import warnings
import tempfile
from torch import multiprocessing as mp
from torch.utils.data import (
ChainDataset,
ConcatDataset,
DataLoader,
DataLoader2,
Dataset,
IterableDataset,
Subset,
TensorDataset,
_utils
)
from torch.utils.data._utils import MP_STATUS_CHECK_INTERVAL
from torch.utils.data.dataset import random_split
from torch.utils.data.datapipes.iter import IterableAsDataPipe
from torch._utils import ExceptionWrapper
from torch.testing._internal.common_utils import (TestCase, run_tests, TEST_NUMPY, IS_WINDOWS,
IS_IN_CI, NO_MULTIPROCESSING_SPAWN, skipIfRocm, slowTest,
load_tests, TEST_WITH_TSAN, IS_SANDCASTLE)
try:
import psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
err_msg = ("psutil not found. Some critical data loader tests relying on it "
"(e.g., TestDataLoader.test_proper_exit) will not run.")
if IS_IN_CI:
raise ImportError(err_msg) from None
else:
warnings.warn(err_msg)
try:
import dill
# XXX: By default, dill writes the Pickler dispatch table to inject its
# own logic there. This globally affects the behavior of the standard library
# pickler for any user who transitively depends on this module!
# Undo this extension to avoid altering the behavior of the pickler globally.
dill.extend(use_dill=False)
HAS_DILL = True
except ImportError:
HAS_DILL = False
skipIfNoDill = unittest.skipIf(not HAS_DILL, "no dill")
# load_tests from torch.testing._internal.common_utils is used to automatically filter tests for
# sharding on sandcastle. This line silences flake warnings
load_tests = load_tests
# We cannot import TEST_CUDA from torch.testing._internal.common_cuda here, because if we do that,
# the TEST_CUDNN line from torch.testing._internal.common_cuda will be executed multiple times
# as well during the execution of this test suite, and it will cause
# CUDA OOM error on Windows.
TEST_CUDA = torch.cuda.is_available()
if not NO_MULTIPROCESSING_SPAWN:
# We want to use `spawn` if able because some of our tests check that the
# data loader terminiates gracefully. To prevent hanging in the testing
# process, such data loaders are run in a separate subprocess.
#
# We also want to test the `pin_memory=True` configuration, thus `spawn` is
# required to launch such processes and they initialize the CUDA context.
#
# Mixing different start method is a recipe for disaster (e.g., using a fork
# `mp.Event` with a spawn `mp.Process` segfaults). So we set this globally
# to avoid bugs.
#
# Get a multiprocessing context because some test / third party library will
# set start_method when imported, and setting again triggers `RuntimeError`.
mp = mp.get_context(method='spawn')
# 60s of timeout?
# Yes, in environments where physical CPU resources are shared, e.g., CI, the
# time for a inter-process communication can be highly varying. With 15~17s of
# timeout, we have observed flakiness in some CI builds (see
# pytorch/pytorch#14501, pytorch/pytorch#16608). We follow the CPython
# multiprocessing setup and set the timeout to 60s here:
#
# https://github.com/python/cpython/blob/e8113f51a8bdf33188ee30a1c038a298329e7bfa/Lib/test/_test_multiprocessing.py#L73
JOIN_TIMEOUT = 60.0 # seconds
supported_multiprocessing_contexts = [None] + list(torch.multiprocessing.get_all_start_methods())
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)")
class TestDatasetRandomSplit(TestCase):
def test_lengths_must_equal_dataset_size(self):
with self.assertRaises(ValueError):
random_split([1, 2, 3, 4], [1, 2])
def test_splits_have_correct_size(self):
splits = random_split([1, 2, 3, 4, 5, 6], [2, 4])
self.assertEqual(len(splits), 2)
self.assertEqual(len(splits[0]), 2)
self.assertEqual(len(splits[1]), 4)
def test_splits_are_mutually_exclusive(self):
data = [5, 2, 3, 4, 1, 6]
splits = random_split(data, [2, 4])
all_values = []
all_values.extend(list(splits[0]))
all_values.extend(list(splits[1]))
data.sort()
all_values.sort()
self.assertListEqual(data, all_values)
def test_splits_indexing_type(self):
r"""Indices generated by random_split
should be of integer type
"""
class CustomDataset():
def __init__(self, test_object, custom_list):
self.data = custom_list
self.test_object = test_object
def __getitem__(self, key):
self.test_object.assertEqual(type(key), type(0))
return self.data[key]
def __len__(self):
return len(self.data)
x = [1, 2, 3, 4, 5]
dataset = CustomDataset(self, x)
dataset = random_split(dataset, [5])[0]
data_loader = DataLoader(dataset)
for batch in data_loader:
pass
def test_splits_reproducibility(self):
self.assertEqual(
[list(x) for x in random_split(range(10), [3, 7], generator=torch.Generator().manual_seed(1))],
[[5, 6, 1], [2, 0, 8, 9, 3, 7, 4]],
)
self.assertEqual(
random_split(range(100), [60, 40], generator=torch.Generator().manual_seed(42)),
random_split(range(100), [60, 40], generator=torch.Generator().manual_seed(42)),
)
def test_splits_generator(self):
# A random_split without a specific generator should affect the default one
state = torch.get_rng_state()
a = torch.rand(10)
torch.set_rng_state(state)
random_split(range(10), [5, 5])
b = torch.rand(10)
self.assertNotEqual(a, b)
# A random_split with a specific generator should not affect the default one
state = torch.get_rng_state()
a = torch.rand(10)
torch.set_rng_state(state)
random_split(range(10), [5, 5], generator=torch.Generator().manual_seed(42))
b = torch.rand(10)
self.assertEqual(a, b)
def test_slicing_of_subset_of_dataset(self):
# Testing slicing a subset initialized with a dataset
dataset = TensorDataset(torch.tensor([1, 2, 3, 4, 5]))
subset_of_dataset = Subset(dataset, [0, 1, 2, 3, 4])
self.assertEqual(subset_of_dataset[:], dataset[:])
self.assertEqual(subset_of_dataset[1:2], dataset[1:2])
self.assertEqual(subset_of_dataset[0:-1:2], dataset[0:-1:2])
# Testing slicing of subset from random split
subset1, subset2 = random_split(dataset, [3, 2])
self.assertEqual(subset1[:], dataset[subset1.indices[:]])
self.assertEqual(subset1[0:2], dataset[subset1.indices[0:2]])
self.assertEqual(subset1[0:-1:2], dataset[subset1.indices[0:-1:2]])
def test_slicing_of_subset_of_subset(self):
# Testing slicing a subset initialized with a subset
dataset = TensorDataset(torch.tensor([1, 2, 3, 4, 5]))
subset_of_dataset = Subset(dataset, [0, 1, 2, 3, 4])
subset_of_subset = Subset(subset_of_dataset, [0, 1, 2, 3, 4])
self.assertEqual(subset_of_subset[:], dataset[:])
self.assertEqual(subset_of_subset[0:2], dataset[0:2])
self.assertEqual(subset_of_subset[0:-1:2], dataset[0:-1:2])
# Testing slicing of subset of subset from random split
subset1, subset2 = random_split(dataset, [4, 1])
subset_of_subset1, subset_of_subset2 = random_split(subset1, [3, 1])
idx = [subset1.indices[i] for i in subset_of_subset1.indices]
self.assertEqual(subset_of_subset1[:], dataset[idx[:]])
self.assertEqual(subset_of_subset1[0:2], dataset[idx[0:2]])
self.assertEqual(subset_of_subset1[0:-1:2], dataset[idx[0:-1:2]])
class CUDACountingDataset(Dataset):
def __init__(self, n):
super(CUDACountingDataset, self).__init__()
self.n = n
def __getitem__(self, i):
return torch.as_tensor(i, device='cuda')
def __len__(self):
return self.n
class CountingDataset(Dataset):
def __init__(self, n):
super(CountingDataset, self).__init__()
self.n = n
def __getitem__(self, i):
return i
def __len__(self):
return self.n
class CountingIterableDataset(IterableDataset):
def __init__(self, n):
super(CountingIterableDataset, self).__init__()
self.n = n
def __iter__(self):
return iter(range(self.n))
def __len__(self):
return self.n
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)")
class TestTensorDataset(TestCase):
def test_len(self):
source = TensorDataset(torch.randn(15, 10, 2, 3, 4, 5), torch.randperm(15))
self.assertEqual(len(source), 15)
def test_getitem(self):
t = torch.randn(15, 10, 2, 3, 4, 5)
l = torch.randn(15, 10)
source = TensorDataset(t, l)
for i in range(15):
self.assertEqual(t[i], source[i][0])
self.assertEqual(l[i], source[i][1])
def test_getitem_1d(self):
t = torch.randn(15)
l = torch.randn(15)
source = TensorDataset(t, l)
for i in range(15):
self.assertEqual(t[i], source[i][0])
self.assertEqual(l[i], source[i][1])
def test_single_tensor(self):
t = torch.randn(5, 10)
source = TensorDataset(t)
self.assertEqual(len(source), 5)
for i in range(5):
self.assertEqual(t[i], source[i][0])
def test_many_tensors(self):
t0 = torch.randn(5, 10, 2, 3, 4, 5)
t1 = torch.randn(5, 10)
t2 = torch.randn(5, 10, 2, 5)
t3 = torch.randn(5, 10, 3, 7)
source = TensorDataset(t0, t1, t2, t3)
self.assertEqual(len(source), 5)
for i in range(5):
self.assertEqual(t0[i], source[i][0])
self.assertEqual(t1[i], source[i][1])
self.assertEqual(t2[i], source[i][2])
self.assertEqual(t3[i], source[i][3])
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)")
class TestConcatDataset(TestCase):
def test_concat_two_singletons(self):
result = ConcatDataset([[0], [1]])
self.assertEqual(2, len(result))
self.assertEqual(0, result[0])
self.assertEqual(1, result[1])
def test_concat_two_non_singletons(self):
result = ConcatDataset([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
self.assertEqual(10, len(result))
self.assertEqual(0, result[0])
self.assertEqual(5, result[5])
def test_concat_two_non_singletons_with_empty(self):
# Adding an empty dataset somewhere is correctly handled
result = ConcatDataset([[0, 1, 2, 3, 4],
[],
[5, 6, 7, 8, 9]])
self.assertEqual(10, len(result))
self.assertEqual(0, result[0])
self.assertEqual(5, result[5])
def test_concat_raises_index_error(self):
result = ConcatDataset([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
with self.assertRaises(IndexError):
# this one goes to 11
result[11]
def test_add_dataset(self):
d1 = TensorDataset(torch.rand(7, 3, 28, 28), torch.rand(7))
d2 = TensorDataset(torch.rand(7, 3, 28, 28), torch.rand(7))
d3 = TensorDataset(torch.rand(7, 3, 28, 28), torch.rand(7))
result = d1 + d2 + d3
self.assertEqual(21, len(result))
self.assertEqual(0, (d1[0][0] - result[0][0]).abs().sum())
self.assertEqual(0, (d2[0][0] - result[7][0]).abs().sum())
self.assertEqual(0, (d3[0][0] - result[14][0]).abs().sum())
def test_iterable_dataset_err(self):
d1 = TensorDataset(torch.rand(7, 3, 28, 28), torch.rand(7))
it1 = CountingIterableDataset(5)
it2 = CountingIterableDataset(10)
with self.assertRaisesRegex(AssertionError, "does not support IterableDataset"):
ConcatDataset([d1, it2, it1])
with self.assertRaisesRegex(AssertionError, "does not support IterableDataset"):
ConcatDataset([it2])
with self.assertRaisesRegex(AssertionError, "does not support IterableDataset"):
ConcatDataset([it1, d1])
# takes in dummy var so this can also be used as a `worker_init_fn`
def set_faulthander_if_available(_=None):
faulthandler.enable(sys.__stderr__)
if not IS_WINDOWS:
# windows does not have faulthandler.register
# chain=False prevents the default behavior of killing the process
faulthandler.register(signal.SIGUSR1, file=sys.__stderr__, chain=False)
set_faulthander_if_available()
# Process `pid` must have called `set_faulthander_if_available`
def print_traces_of_all_threads(pid):
if not IS_WINDOWS:
# use the custom signal if available
os.kill(pid, signal.SIGUSR1)
else:
# otherwise we can still use the handler given by faulthandler.enable()
# at the cost of killing the process.
os.kill(pid, signal.SIGSEGV)
# wait in parent process to give subprocess some time to print
time.sleep(5)
# The following `ErrorTrackingProcess` stores the first encountered exception in
# its `.exception` attribute.
# Inspired by https://stackoverflow.com/a/33599967
class ErrorTrackingProcess(mp.Process):
# Why no *args?
# py2 doesn't support def fn(x, *args, key=val, **kwargs)
# Setting disable_stderr=True may generate a lot of unrelated error outputs
# but could be helpful for debugging.
def __init__(self, disable_stderr=True, **kwargs):
super(ErrorTrackingProcess, self).__init__(**kwargs)
self._pconn, self._cconn = mp.Pipe()
self._exception = None
self.disable_stderr = disable_stderr
def run(self):
set_faulthander_if_available()
if self.disable_stderr:
# Disable polluting stderr with errors that are supposed to happen.
with open(os.devnull, 'w') as devnull:
os.dup2(devnull.fileno(), sys.stderr.fileno())
try:
super(ErrorTrackingProcess, self).run()
self._cconn.send(None)
except Exception:
self._cconn.send(ExceptionWrapper(sys.exc_info()))
raise
def print_traces_of_all_threads(self):
assert self.is_alive(), "can only use print_traces_of_all_threads if the process is alive"
assert not self.disable_stderr, "do not disable stderr if you use print_traces_of_all_threads"
# On platforms without `SIGUSR1`, `set_faulthander_if_available` sets
# `faulthandler.enable()`, and `print_traces_of_all_threads` may kill
# the process. So let's poll the exception first
_ = self.exception
print_traces_of_all_threads(self.pid)
@property
def exception(self):
if self._pconn.poll():
self._exception = self._pconn.recv()
if self._exception is None:
return None
else:
return self._exception.exc_type(self._exception.exc_msg)
# ESRCH means that os.kill can't finds alive proc
def send_signal(self, signum, ignore_ESRCH=False):
try:
os.kill(self.pid, signum)
except OSError as e:
if not ignore_ESRCH or e.errno != errno.ESRCH:
raise
class ErrorDataset(Dataset):
def __init__(self, size):
self.size = size
def __len__(self):
return self.size
class SegfaultDataset(Dataset):
def __init__(self, size):
self.size = size
def __getitem__(self, idx):
return ctypes.string_at(0)
def __len__(self):
return self.size
class SleepDataset(Dataset):
def __init__(self, size, sleep_sec):
self.size = size
self.sleep_sec = sleep_sec
self.sleeped = False
def __getitem__(self, idx):
if not self.sleeped:
time.sleep(self.sleep_sec)
self.sleeped = True
return idx
def __len__(self):
return self.size
class SeedDataset(Dataset):
def __init__(self, size):
self.size = size
def __getitem__(self, idx):
return torch.initial_seed()
def __len__(self):
return self.size
class WorkerSpecificIterableDataset(IterableDataset):
def __init__(self, sizes_for_all_workers):
self.sizes_for_all_workers = sizes_for_all_workers
def __iter__(self):
worker_info = torch.utils.data.get_worker_info()
assert worker_info is not None
return iter(range(self.sizes_for_all_workers[worker_info.id]))
def __len__(self):
return sum(self.sizes_for_all_workers)
# Inspired by https://stackoverflow.com/a/26703365
# If all workers will call `sync_once`, they will be blocked until all workers
# reach the call (i.e., acting like a barrier).
# This can be used to ensure that each worker at least processes one data.
class SynchronizedDataset(Dataset):
def __init__(self, size, batch_size, num_workers):
assert size >= num_workers * batch_size
self.count = mp.Value('i', 0, lock=True)
self.barrier = mp.Semaphore(0)
self.num_workers = num_workers
self.size = size
def sync_once(self):
with self.count.get_lock():
self.count.value += 1
if self.count.value == self.num_workers:
self.barrier.release()
self.barrier.acquire()
self.barrier.release()
def __getitem__(self, idx):
raise NotImplementedError
def __len__(self):
return self.size
class EmptyTensorDataset(torch.utils.data.Dataset):
def __init__(self, len):
self.len = len
def __len__(self):
return self.len
def __getitem__(self, any):
return torch.empty(0)
class SynchronizedSeedDataset(SynchronizedDataset):
def __getitem__(self, idx):
self.sync_once()
return torch.initial_seed()
def _test_timeout(persistent_workers):
dataset = SleepDataset(10, 3)
dataloader = DataLoader(dataset, batch_size=2, num_workers=2, timeout=1,
persistent_workers=persistent_workers)
_ = next(iter(dataloader))
def _test_timeout_pin_memory(persistent_workers):
dataset = SleepDataset(10, 3)
dataloader = DataLoader(dataset, batch_size=2, num_workers=2, timeout=1, pin_memory=True,
persistent_workers=persistent_workers)
_ = next(iter(dataloader))
def _test_large_sampler_indices(persistent_workers):
# See
# test_large_sampler_indices
# https://github.com/pytorch/pytorch/issues/48666
dataloader = torch.utils.data.DataLoader(
EmptyTensorDataset(10000000),
batch_size=40960,
persistent_workers=persistent_workers,
num_workers=1)
it = iter(dataloader)
for x in it:
assert x.numel() == 0
raise RuntimeError('My Error')
def disable_stderr(worker_id):
r"""
Avoids printing "ERROR: Unexpected segmentation fault encountered in worker."
from workers. Since worker signal handler prints with low-level write(),
this has to be done on OS level via dup.
This is used as worker_init_fn for test_segfault.
"""
sys.stderr.flush() # flush library buffers that dup2 knows nothing about
# Can't use a with-block because otherwise the fd will be closed when this
# function ends.
with open(os.devnull, 'w') as devnull:
os.dup2(devnull.fileno(), sys.stderr.fileno())
def _test_segfault():
dataset = SegfaultDataset(10)
dataloader = DataLoader(dataset, batch_size=2, num_workers=2, worker_init_fn=disable_stderr)
_ = next(iter(dataloader))
def _test_no_segfault():
dataset = [1, 2, 3]
num_threads = torch.get_num_threads()
if num_threads < 4:
torch.set_num_threads(4)
else:
torch.set_num_threads(num_threads)
mp_ctx = torch.multiprocessing.get_context(method='fork')
dataloader = DataLoader(dataset, num_workers=1, worker_init_fn=disable_stderr,
multiprocessing_context=mp_ctx)
_ = next(iter(dataloader))
class TestProperExitDataset(Dataset):
def __init__(self, size, error_event):
self.size = size
self.error_event = error_event
def __len__(self):
return self.size
def __getitem__(self, idx):
worker_info = torch.utils.data.get_worker_info()
if self.error_event is not None and self.error_event.is_set() and \
worker_info.id == worker_info.num_workers - 1:
# only error in the last worker
raise RuntimeError('Worker error')
return torch.tensor([idx])
class TestProperExitIterableDataset(IterableDataset):
def __init__(self, size, error_event):
self.error_event = error_event
self.size = size
self.remaining = size
def __len__(self):
return self.size
def __iter__(self):
return self
def __next__(self):
worker_info = torch.utils.data.get_worker_info()
if self.error_event is not None and self.error_event.is_set() and \
worker_info.id == worker_info.num_workers - 1:
# only error in the last worker
raise RuntimeError('Worker error')
self.remaining -= 1
if self.remaining < 0:
raise StopIteration
return torch.tensor(-1000)
next = __next__ # py2 compatibility
# See TestDataLoader.test_proper_exit for usage
def _test_proper_exit(is_iterable_dataset, use_workers, pin_memory, exit_method,
hold_iter_reference, loader_setup_event, tester_setup_event,
persistent_workers):
num_workers = 2 if use_workers else 0
if exit_method == 'worker_error' or exit_method == 'worker_kill':
assert use_workers is True
if exit_method == 'worker_error':
worker_error_event = mp.Event()
else:
worker_error_event = None
if is_iterable_dataset:
ds = TestProperExitIterableDataset(7, worker_error_event)
else:
ds = TestProperExitDataset(12, worker_error_event)
loader = DataLoader(ds, batch_size=1, shuffle=False,
num_workers=num_workers, pin_memory=pin_memory,
worker_init_fn=set_faulthander_if_available,
persistent_workers=persistent_workers)
error_it = 2
if use_workers:
# 2 is the magical per-worker prefetch number...
# FIXME: change this after the number becomes configurable.
if is_iterable_dataset:
assert len(ds) * num_workers > (error_it + 2 + 1)
else:
assert len(loader) > (error_it + 2 + 1) * num_workers
else:
if is_iterable_dataset:
assert len(ds) > error_it + 1
else:
assert len(loader) > error_it + 1
it = iter(loader)
if use_workers:
workers = it._workers
def kill_pid(pid):
psutil_p = psutil.Process(pid)
psutil_p.kill()
psutil_p.wait(JOIN_TIMEOUT)
assert not psutil_p.is_running()
for i, _ in enumerate(it):
if i == 0:
if not hold_iter_reference:
del it
del loader
loader_setup_event.set()
tester_setup_event.wait()
# ensure that the workers are still alive
if use_workers:
for w in workers:
assert w.is_alive()
if worker_error_event is not None:
worker_error_event.set()
if i == error_it:
if exit_method == 'loader_error':
raise RuntimeError('Loader error')
elif exit_method == 'loader_kill':
kill_pid(os.getpid())
elif exit_method == 'worker_kill':
kill_pid(workers[-1].pid) # kill last worker
if not hold_iter_reference:
# Tries to trigger the __del__ clean-up rather than the automatic
# exiting of daemonic children. Technically it should be automatically
# triggered, but I don't want to rely on the implementation detail of
# Python gc.
gc.collect()
class TestWorkerInfoDataset(SynchronizedDataset):
def __getitem__(self, idx):
self.sync_once()
return torch.tensor(self.value)
# Should be used as worker_init_fn with TestWorkerInfoDataset.
# See _test_get_worker_info below for usage.
def test_worker_info_init_fn(worker_id):
worker_info = torch.utils.data.get_worker_info()
assert worker_id == worker_info.id, "worker_init_fn and worker_info should have consistent id"
assert worker_id < worker_info.num_workers, "worker_init_fn and worker_info should have valid id"
assert worker_info.seed == torch.initial_seed(), "worker_init_fn and worker_info should have consistent seed"
dataset = worker_info.dataset
assert isinstance(dataset, TestWorkerInfoDataset), "worker_info should have correct dataset copy"
assert not hasattr(dataset, 'value'), "worker_info should have correct dataset copy"
# test that WorkerInfo attributes are read-only
try:
worker_info.id = 3999
except RuntimeError as e:
assert str(e) == "Cannot assign attributes to WorkerInfo objects"
try:
worker_info.a = 3
except RuntimeError as e:
assert str(e) == "Cannot assign attributes to WorkerInfo objects"
for k in ['id', 'num_workers', 'seed', 'dataset']:
assert "{}=".format(k) in repr(worker_info)
dataset.value = [worker_id, os.getpid()]
def _test_get_worker_info():
# get_worker_info returns None in main proc
assert torch.utils.data.get_worker_info() is None
num_workers = 2
batch_size = 2
dataset = TestWorkerInfoDataset(6, batch_size, num_workers)
dataloader = DataLoader(dataset, batch_size=batch_size,
num_workers=num_workers,
worker_init_fn=test_worker_info_init_fn)
it = iter(dataloader)
data = []
for d in it:
data.append(d)
worker_pids = [w.pid for w in it._workers]
data = torch.cat(data, 0)
for d in data:
# each `d` is a [worker_id, worker_pid] pair, which is set in
# test_worker_info_init_fn
assert d[1] == worker_pids[d[0]]
# get_worker_info returns None in main proc after data loading
assert torch.utils.data.get_worker_info() is None
# main proc dataset was never assigned this attribute
assert not hasattr(dataset, 'value')
try:
_ = dataset[0]
except AttributeError:
return
raise RuntimeError('Expected AttributeError')
# test custom init function
def init_fn(worker_id):
torch.manual_seed(12345)
# used with test_error_in_init
class ErrorIterableDataset(IterableDataset):
def __iter__(self):
raise RuntimeError("Error in __iter__")
# used with test_error_in_init
def error_worker_init_fn(_):
raise RuntimeError("Error in worker_init_fn")
class BulkLoadingDataset(Dataset):
def __init__(self, length):
self.length = length
def __getitem__(self, indices):
assert isinstance(indices, (list, tuple))
return torch.as_tensor(indices)
def __len__(self):
return self.length
class BulkLoadingSampler(torch.utils.data.Sampler):
def __init__(self, dataset, batch_size):
self.dataset = dataset
self.batch_size = batch_size
def __iter__(self):
for x in torch.randperm(len(self.dataset)).split(self.batch_size):
yield x.tolist()
def __len__(self):
return int(math.ceil(len(self.dataset) / float(self.batch_size)))
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)")
class TestDataLoader(TestCase):
def setUp(self):
super(TestDataLoader, self).setUp()
self.data = torch.randn(100, 2, 3, 5)
self.labels = torch.randperm(50).repeat(2)
self.dataset = TensorDataset(self.data, self.labels)
self.persistent_workers = False
def _get_data_loader(self, dataset, **kwargs):
persistent_workers = kwargs.get('persistent_workers', self.persistent_workers)
if persistent_workers and kwargs.get('num_workers', 0) == 0:
persistent_workers = False
kwargs['persistent_workers'] = persistent_workers
return DataLoader(dataset, **kwargs)
def _test_sequential(self, loader):
batch_size = loader.batch_size
if batch_size is None:
for idx, (sample, target) in enumerate(loader):
self.assertEqual(sample, self.data[idx])
self.assertEqual(target, self.labels[idx])
self.assertEqual(idx, len(self.dataset) - 1)
else:
for i, (sample, target) in enumerate(loader):
idx = i * batch_size
self.assertEqual(sample, self.data[idx:idx + batch_size])
self.assertEqual(target, self.labels[idx:idx + batch_size])
self.assertEqual(i, math.floor((len(self.dataset) - 1) / batch_size))
def _test_shuffle(self, loader):
found_data = {i: 0 for i in range(self.data.size(0))}
found_labels = {i: 0 for i in range(self.labels.size(0))}
batch_size = loader.batch_size
if batch_size is None:
for i, (batch_samples, batch_targets) in enumerate(loader):
sample, target = (batch_samples, batch_targets)
for data_point_idx, data_point in enumerate(self.data):
if data_point.eq(sample).all():
self.assertFalse(found_data[data_point_idx])
found_data[data_point_idx] += 1
break
self.assertEqual(target, self.labels[data_point_idx])
found_labels[data_point_idx] += 1
self.assertEqual(sum(found_data.values()), (i + 1))
self.assertEqual(sum(found_labels.values()), (i + 1))
self.assertEqual(i, (len(self.dataset) - 1))
else:
for i, (batch_samples, batch_targets) in enumerate(loader):
for sample, target in zip(batch_samples, batch_targets):
for data_point_idx, data_point in enumerate(self.data):
if data_point.eq(sample).all():
self.assertFalse(found_data[data_point_idx])
found_data[data_point_idx] += 1
break
self.assertEqual(target, self.labels[data_point_idx])
found_labels[data_point_idx] += 1
self.assertEqual(sum(found_data.values()), (i + 1) * batch_size)
self.assertEqual(sum(found_labels.values()), (i + 1) * batch_size)
self.assertEqual(i, math.floor((len(self.dataset) - 1) / batch_size))
def _test_error(self, loader):
it = iter(loader)
errors = 0
while True:
try:
next(it)
except NotImplementedError:
errors += 1
except StopIteration:
self.assertEqual(errors,
math.ceil(float(len(loader.dataset)) / loader.batch_size))
return
def test_error_in_init(self):
for num_workers in [0, 2]:
loader = self._get_data_loader(ErrorIterableDataset(), num_workers=num_workers)
with self.assertRaisesRegex(RuntimeError, 'Error in __iter__'):
list(iter(loader))
loader = self._get_data_loader(self.dataset, num_workers=2, worker_init_fn=error_worker_init_fn)
with self.assertRaisesRegex(RuntimeError, 'Error in worker_init_fn'):
list(iter(loader))
def test_typing(self):
from typing import List
# Make sure there is no TypeError
class SomeDatasetClass(Dataset[List[torch.Tensor]]):
pass
def _create_dataloader(is_train: bool) -> DataLoader[List[torch.Tensor]]:
pass
@unittest.skipIf(IS_SANDCASTLE, "subprocess doesn't work in FB internal CI")
@unittest.skipIf(IS_WINDOWS, "No 'resource' module on Windows")
def test_fd_limit_exceeded(self):
# See NOTE [ DataLoader on Linux and open files limit ]
import subprocess
subprocess.check_output([sys.executable, '-c', """\
import torch
import resource
from torch.utils.data import DataLoader, IterableDataset
class RandomDataset(IterableDataset):
def __init__(self, len, size):
super(RandomDataset).__init__()
self.len = len
self.size = size
def __iter__(self):
return self
def __next__(self):
if self.len <= 0:
raise StopIteration
self.len -= 1
return torch.randn(self.size)
try:
keep_fds_alive = []
resource.setrlimit(resource.RLIMIT_NOFILE, (100, 100))
for random_t in DataLoader(RandomDataset(200, (2,2)), multiprocessing_context="fork",
num_workers=1):
random_t.max(dim=0)
keep_fds_alive.append(random_t)
except RuntimeError as e:
assert "ulimit -n" in str(e)
assert "set_sharing_strategy" in str(e)
"""])
def test_invalid_assign_after_init(self):
dl = self._get_data_loader(self.dataset)
for attr in ('batch_size', 'sampler', 'batch_sampler', 'drop_last', 'dataset'):
def fn():
setattr(dl, attr, {})
self.assertRaises(ValueError, fn)
def test_sequential_nonbatch(self):
self._test_sequential(self._get_data_loader(self.dataset, batch_size=None))
def test_sequential_batch(self):
self._test_sequential(self._get_data_loader(self.dataset))
self._test_sequential(self._get_data_loader(self.dataset, batch_size=2))
def test_bulk_loading_nobatch(self):
n = 35
bs = 4
ds = BulkLoadingDataset(n)
sampler = BulkLoadingSampler(ds, batch_size=4)
for num_workers in [0, 4]:
dl = self._get_data_loader(ds, num_workers=num_workers, batch_size=None, sampler=sampler, pin_memory=TEST_CUDA)
self.assertFalse(dl._auto_collation)
samples = list(dl)
self.assertEqual(samples[0].is_pinned(), TEST_CUDA)
self.assertEqual(set(torch.cat(samples, 0).tolist()), set(range(n)))
def test_growing_dataset(self):
dataset = [torch.ones(4) for _ in range(4)]
dataloader_seq = self._get_data_loader(dataset, shuffle=False)
dataloader_shuffle = self._get_data_loader(dataset, shuffle=True)
dataset.append(torch.ones(4))
self.assertEqual(len(dataloader_seq), 5)
self.assertEqual(len(dataloader_shuffle), 5)
@unittest.skipIf(not TEST_CUDA, "CUDA unavailable")
def test_sequential_pin_memory(self):
loader = self._get_data_loader(self.dataset, batch_size=2, pin_memory=True)
for input, target in loader:
self.assertTrue(input.is_pinned())
self.assertTrue(target.is_pinned())
def test_multiple_dataloaders(self):
for multiprocessing_context in supported_multiprocessing_contexts:
loader1_it = iter(self._get_data_loader(self.dataset, num_workers=1))
loader2_it = iter(self._get_data_loader(self.dataset, num_workers=2, multiprocessing_context=multiprocessing_context))
next(loader1_it)
next(loader1_it)
next(loader2_it)
next(loader2_it)
next(loader1_it)
next(loader2_it)
def test_segfault(self):
p = ErrorTrackingProcess(target=_test_segfault)
p.start()
p.join(JOIN_TIMEOUT)
try:
self.assertFalse(p.is_alive())
self.assertNotEqual(p.exitcode, 0)
if IS_WINDOWS:
self.assertIsInstance(p.exception, OSError)
self.assertRegex(str(p.exception), r'access violation reading ')
else:
self.assertIsInstance(p.exception, RuntimeError)
self.assertRegex(str(p.exception), r'DataLoader worker \(pid \d+\) is killed by signal: ')
finally:
p.terminate()
# Tests if the child process forked by the DataLoader segfaults due to having more than 3 threads
# in the parent process after at least one set_num_threads invocation in the parent process.
# After forking, set_num_threads(1) in the child process entails handling some inherited data-structures
# of the Caffe2 thread-pool of the parent process, culminating in a segfault.
# Reference: https://github.com/pytorch/pytorch/issues/54752
@unittest.skipIf(IS_WINDOWS, "Needs fork")
def test_no_segfault(self):
p = ErrorTrackingProcess(target=_test_no_segfault)
p.start()
p.join(JOIN_TIMEOUT)
try:
self.assertFalse(p.is_alive())
if p.exception:
self.assertIsInstance(p.exception, RuntimeError)
self.assertRegex(str(p.exception), r'DataLoader worker \(pid \d+\) is killed by signal: ')
self.fail("Segfault occurred in worker process after fork")
finally:
p.terminate()
def test_timeout(self):
if TEST_CUDA and not NO_MULTIPROCESSING_SPAWN:
# This test runs in a subprocess, which can only initialize CUDA with spawn.
# _test_timeout_pin_memory with pin_memory=True initializes CUDA when the iterator is
# constructed.
targets = (_test_timeout, _test_timeout_pin_memory)
else:
targets = (_test_timeout,)
for target in targets:
p = ErrorTrackingProcess(target=target, args=(self.persistent_workers,))
p.start()
p.join(JOIN_TIMEOUT)
try:
self.assertFalse(p.is_alive())
self.assertNotEqual(p.exitcode, 0)
self.assertIsInstance(p.exception, RuntimeError)
self.assertRegex(str(p.exception), r'DataLoader timed out after \d+ seconds')
finally:
p.terminate()
def test_large_sampler_indices(self):
# Test that the data loader cleanly exit when the process errors
# 1. having an reference to the iterator
# 2. using a sampler that yields big elements s.t. _index_queues putters block
#
# More context: https://github.com/pytorch/pytorch/issues/48666
p = ErrorTrackingProcess(target=_test_large_sampler_indices, args=(self.persistent_workers,))
p.start()
p.join(JOIN_TIMEOUT)
try:
self.assertFalse(p.is_alive())
self.assertNotEqual(p.exitcode, 0)
self.assertIsInstance(p.exception, RuntimeError)
self.assertRegex(str(p.exception), r'My Error')
finally:
p.terminate()
def test_invalid_ctor_args_combinations(self):
# general
with self.assertRaisesRegex(ValueError, "num_workers option should be non-negative"):
self._get_data_loader(self.dataset, num_workers=-1)
with self.assertRaisesRegex(ValueError, "timeout option should be non-negative"):
self._get_data_loader(self.dataset, timeout=-1)
# disable auto-batching
with self.assertRaisesRegex(ValueError,
"batch_size=None option disables auto-batching and is mutually exclusive"):
self._get_data_loader(self.dataset, batch_size=None, drop_last=True)
valid_ctx = list(torch.multiprocessing.get_all_start_methods())[-1]
with self.assertRaisesRegex(ValueError, r"multi-process loading \(num_workers > 0\), but got"):
self._get_data_loader(self.dataset, num_workers=0, multiprocessing_context=valid_ctx)
with self.assertRaisesRegex(ValueError, "should specify a valid start method in"):
self._get_data_loader(self.dataset, num_workers=1, multiprocessing_context='bad')
with self.assertRaisesRegex(TypeError, "multiprocessing_context option should be a valid context "):
self._get_data_loader(self.dataset, num_workers=1, multiprocessing_context=object())
# map-style
sampler = torch.utils.data.SequentialSampler(self.dataset)
batch_sampler = torch.utils.data.BatchSampler(sampler, 3, False)
with self.assertRaisesRegex(ValueError, "sampler option is mutually exclusive with shuffle"):
self._get_data_loader(self.dataset, batch_size=11, sampler=sampler, shuffle=True)
with self.assertRaisesRegex(ValueError, "sampler option is mutually exclusive with shuffle"):
self._get_data_loader(self.dataset, batch_sampler=batch_sampler, sampler=sampler, shuffle=True)
with self.assertRaisesRegex(ValueError, "sampler option is mutually exclusive with shuffle"):
self._get_data_loader(self.dataset, batch_sampler=batch_sampler, sampler=sampler, shuffle=3)
with self.assertRaisesRegex(ValueError, "batch_sampler option is mutually exclusive with"):
self._get_data_loader(self.dataset, batch_size=11, batch_sampler=batch_sampler)
with self.assertRaisesRegex(ValueError, "batch_sampler option is mutually exclusive with"):
self._get_data_loader(self.dataset, shuffle=True, batch_sampler=batch_sampler)
with self.assertRaisesRegex(ValueError, "batch_sampler option is mutually exclusive with"):
self._get_data_loader(self.dataset, drop_last=True, batch_sampler=batch_sampler)
with self.assertRaisesRegex(ValueError, "batch_sampler option is mutually exclusive with"):
self._get_data_loader(self.dataset, drop_last=3, batch_sampler=batch_sampler)
# iterable-style
dataset = CountingIterableDataset(20)
with self.assertRaisesRegex(ValueError, "DataLoader with IterableDataset: expected unspecified shuffle"):
self._get_data_loader(dataset, shuffle=True)
with self.assertRaisesRegex(ValueError, "DataLoader with IterableDataset: expected unspecified shuffle"):
self._get_data_loader(dataset, shuffle=3)
with self.assertRaisesRegex(ValueError, "DataLoader with IterableDataset: expected unspecified sampler"):
self._get_data_loader(dataset, sampler=torch.utils.data.SequentialSampler(dataset))
with self.assertRaisesRegex(ValueError, "DataLoader with IterableDataset: expected unspecified sampler"):
self._get_data_loader(dataset, sampler=3)
with self.assertRaisesRegex(ValueError, "DataLoader with IterableDataset: expected unspecified batch_sampler"):
self._get_data_loader(dataset, batch_sampler=torch.utils.data.BatchSampler(
torch.utils.data.SequentialSampler(dataset), 3, False))
with self.assertRaisesRegex(ValueError, "DataLoader with IterableDataset: expected unspecified batch_sampler"):
self._get_data_loader(dataset, batch_sampler=3)
def test_builtin_collection_conversion(self):
for coll_ty in (list, tuple):
for num_workers in (0, 1):
# map-style dataset
dataset = CountingDataset(20)
# no auto-batching
fetched = coll_ty(self._get_data_loader(dataset, batch_size=None, num_workers=num_workers))
self.assertEqual(fetched, coll_ty(range(20)))
# auto-batching
fetched = coll_ty(self._get_data_loader(dataset, batch_size=2, num_workers=num_workers))
self.assertEqual(fetched, coll_ty(torch.tensor([i, i + 1]) for i in range(0, 20, 2)))
# iterable-style dataset
dataset = CountingIterableDataset(20)
# no auto-batching
fetched = coll_ty(self._get_data_loader(dataset, batch_size=None, num_workers=num_workers))
self.assertEqual(fetched, coll_ty(range(20)))
# auto-batching
# this IterableDataset isn't configured for each worker, so for
# the equality test below to be valid, we cannot have more than 1 workers.
assert num_workers in [0, 1], "invalid test"
fetched = coll_ty(self._get_data_loader(dataset, batch_size=2, num_workers=num_workers))
self.assertEqual(fetched, coll_ty(torch.tensor([i, i + 1]) for i in range(0, 20, 2)))
def test_iterable_style_dataset(self):
# [no auto-batching] single process loading
dataset = CountingIterableDataset(20)
dataloader = self._get_data_loader(dataset, batch_size=None)
fetched = list(dataloader)
self.assertEqual(len(fetched), 20)
for i, d in enumerate(fetched):
# non-batched should not convert ints into tensors
self.assertIsInstance(d, int)
self.assertEqual(d, i)
# DataLoader should match len of the iterable-style dataset (if implemented)
self.assertEqual(len(dataloader), len(dataset))
# [no auto-batching] multiprocessing loading
num_workers = 3
sizes_for_all_workers = [0, 4, 20]
expected = sorted(sum((list(range(s)) for s in sizes_for_all_workers), []))
assert len(sizes_for_all_workers) == num_workers, 'invalid test case'
for prefetch_factor in [2, 3, 4]:
dataset = WorkerSpecificIterableDataset(sizes_for_all_workers)
dataloader = self._get_data_loader(dataset, num_workers=num_workers, batch_size=None,
worker_init_fn=set_faulthander_if_available,
prefetch_factor=prefetch_factor)
dataloader_iter = iter(dataloader)
fetched = sorted(dataloader_iter)
for a, b in zip(fetched, expected):
# non-batched should not convert ints into tensors
self.assertIsInstance(a, int)
self.assertEqual(a, b)
# DataLoader should match len of the iterable-style dataset (if implemented)
self.assertEqual(len(dataloader), len(dataset))
# When loading more than len(dataset) data, after accessing len(dataloader),
# we should get a warning. See NOTE [ IterableDataset and __len__ ].
dataset = CountingIterableDataset(20)
dataloader = self._get_data_loader(dataset, num_workers=num_workers,
worker_init_fn=set_faulthander_if_available,
prefetch_factor=prefetch_factor)
it = iter(dataloader)
for _ in range(40):
self.assertNotWarn(lambda: next(it), "Should not warn before accessing len(dataloader)")
self.assertEqual(len(dataloader), len(dataset))
self.assertEqual(len(dataloader), 20)
it = iter(dataloader)
for _ in range(20):
self.assertNotWarn(lambda: next(it), "Should not warn before exceeding length")
for _ in range(3):
with self.assertWarnsRegex(
UserWarning,
r"but [0-9]+ samples have been fetched\. For multiprocessing data-loading, this",
msg="Should always warn after exceeding length"):
next(it)
# [no auto-batching] test that workers exit gracefully
workers = dataloader_iter._workers
del dataloader_iter
del dataloader
try:
for w in workers:
w.join(JOIN_TIMEOUT)
self.assertFalse(w.is_alive())
self.assertEqual(w.exitcode, 0)
finally:
for w in workers:
w.terminate()
# [auto-batching] single process loading
dataset = CountingIterableDataset(20)
fetched = list(self._get_data_loader(dataset, batch_size=7))
self.assertEqual(len(fetched), 3)
self.assertEqual(fetched[0].tolist(), list(range(7)))
self.assertEqual(fetched[1].tolist(), list(range(7, 14)))
self.assertEqual(fetched[2].tolist(), list(range(14, 20)))
# [auto-batching] multiprocessing loading
num_workers = 3
sizes_for_all_workers = [0, 4, 20]
expected = sorted(sum((list(range(s)) for s in sizes_for_all_workers), []))
assert len(sizes_for_all_workers) == num_workers, 'invalid test case'
for prefetch_factor in [2, 3, 4]:
dataset = WorkerSpecificIterableDataset(sizes_for_all_workers)
# worker 0 should return 0 batches
# worker 1 should return 1 batches
# worker 2 should return 3 batches
dataloader = self._get_data_loader(dataset, num_workers=num_workers, batch_size=7, prefetch_factor=prefetch_factor)
dataloader_iter = iter(dataloader)
fetched = list(dataloader_iter)
self.assertEqual(len(fetched), 4)
fetched = set(tuple(t.tolist()) for t in fetched)
self.assertEqual(fetched, {tuple(range(4)), tuple(range(7)), tuple(range(7, 14)), tuple(range(14, 20))})
# [auto-batching] test that workers exit gracefully
workers = dataloader_iter._workers
del dataloader_iter
del dataloader
try:
for w in workers:
w.join(JOIN_TIMEOUT)
self.assertFalse(w.is_alive())
self.assertEqual(w.exitcode, 0)
finally:
for w in workers:
w.terminate()
# [auto-batching & drop_last] single process loading
dataset = CountingIterableDataset(20)
fetched = list(self._get_data_loader(dataset, batch_size=7, drop_last=True))
self.assertEqual(len(fetched), 2)
self.assertEqual(fetched[0].tolist(), list(range(7)))
self.assertEqual(fetched[1].tolist(), list(range(7, 14)))
# [auto-batching & drop_last] multiprocessing loading
num_workers = 3
sizes_for_all_workers = [0, 4, 20]
expected = sorted(sum((list(range(s)) for s in sizes_for_all_workers), []))
assert len(sizes_for_all_workers) == num_workers, 'invalid test case'
for prefetch_factor in [2, 3, 4]:
dataset = WorkerSpecificIterableDataset(sizes_for_all_workers)
# worker 0 should return 0 batches
# worker 1 should return 1 batches
# worker 2 should return 3 batches
dataloader = self._get_data_loader(dataset, num_workers=num_workers, batch_size=7, drop_last=True,
worker_init_fn=set_faulthander_if_available,
prefetch_factor=prefetch_factor)
dataloader_iter = iter(dataloader)
fetched = list(dataloader_iter)
self.assertEqual(len(fetched), 2)
fetched = set(tuple(t.tolist()) for t in fetched)
self.assertEqual(fetched, {tuple(range(7)), tuple(range(7, 14))})
# [auto-batching & drop_last] test that workers exit gracefully
workers = dataloader_iter._workers
del dataloader_iter
del dataloader
try:
for w in workers:
w.join(JOIN_TIMEOUT)
self.assertFalse(w.is_alive())
self.assertEqual(w.exitcode, 0)
finally:
for w in workers:
w.terminate()
def test_chain_iterable_style_dataset(self):
# chaining (concatenation)
dataset1 = CountingIterableDataset(20)
dataset2 = CountingIterableDataset(15)
expected = list(range(20)) + list(range(15))
for num_workers in [0, 1]:
for chained_dataset in [dataset1 + dataset2, ChainDataset([dataset1, dataset2])]:
fetched = list(self._get_data_loader(chained_dataset, num_workers=num_workers))
self.assertEqual(len(fetched), len(expected))
for e, d in zip(expected, fetched):
self.assertIsInstance(d, torch.Tensor)
self.assertEqual(e, d)
with self.assertRaisesRegex(AssertionError, "ChainDataset only supports IterableDataset"):
list(iter(dataset1 + self.dataset))
with self.assertRaisesRegex(AssertionError, "ChainDataset only supports IterableDataset"):
list(iter(ChainDataset([dataset1, self.dataset])))
def test_multiprocessing_contexts(self):
reference = [
torch.arange(3),
torch.arange(3, 6),
torch.arange(6, 9),
torch.arange(9, 11),
]
counting_ds_n = 11
dl_common_args = dict(num_workers=3, batch_size=3, pin_memory=(not TEST_CUDA))
for ctx in supported_multiprocessing_contexts:
# windows doesn't support sharing cuda tensor; ROCm does not yet fully support IPC
if ctx in ['spawn', 'forkserver'] and TEST_CUDA and not IS_WINDOWS:
ds_cls = CUDACountingDataset
else:
ds_cls = CountingDataset
self.assertEqual(
reference, list(self._get_data_loader(ds_cls(counting_ds_n), multiprocessing_context=ctx, **dl_common_args)))
if ctx is not None:
# test ctx object
ctx = mp.get_context(ctx)
self.assertEqual(
reference, list(self._get_data_loader(ds_cls(counting_ds_n), multiprocessing_context=ctx, **dl_common_args)))
def test_worker_seed(self):
num_workers = 6
batch_size = 1
dataset = SynchronizedSeedDataset(num_workers, batch_size, num_workers)
dataloader = self._get_data_loader(dataset, batch_size=batch_size, num_workers=num_workers)
seeds = set()
for batch in dataloader:
seeds.add(batch[0])
self.assertEqual(len(seeds), num_workers)
def test_worker_seed_reproducibility(self):
def get_dataloader():
return DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, generator=torch.Generator().manual_seed(42))
num_workers = 6
batch_size = 1
dataset = SynchronizedSeedDataset(num_workers, batch_size, num_workers)
self.assertEqual(set(int(batch) for batch in get_dataloader()), set(int(batch) for batch in get_dataloader()))
def test_worker_init_fn(self):
dataset = SeedDataset(4)
dataloader = self._get_data_loader(dataset, batch_size=2, num_workers=2,
worker_init_fn=init_fn)
for batch in dataloader:
self.assertEqual(12345, batch[0])
self.assertEqual(12345, batch[1])
def test_get_worker_info(self):
p = ErrorTrackingProcess(target=_test_get_worker_info)
p.start()
p.join(JOIN_TIMEOUT)
try:
self.assertFalse(p.is_alive())
self.assertEqual(p.exitcode, 0)
finally:
p.terminate()
def test_shuffle(self):
self._test_shuffle(self._get_data_loader(self.dataset, shuffle=True))
def test_shuffle_batch_none(self):
self._test_shuffle(DataLoader(self.dataset, batch_size=None, shuffle=True))
def test_shuffle_batch(self):
self._test_shuffle(self._get_data_loader(self.dataset, batch_size=2, shuffle=True))
def test_shuffle_reproducibility(self):
for fn in (
lambda: DataLoader(self.dataset, shuffle=True, num_workers=0, generator=torch.Generator().manual_seed(42)),
lambda: DataLoader(self.dataset, shuffle=True, num_workers=2, generator=torch.Generator().manual_seed(42)),
):
self.assertEqual(list(fn()), list(fn()))
def test_sequential_workers(self):
self._test_sequential(self._get_data_loader(self.dataset, num_workers=4))
def test_seqential_batch_workers(self):
self._test_sequential(self._get_data_loader(self.dataset, batch_size=2, num_workers=4))
def test_seqential_batch_workers_prefetch(self):
self._test_sequential(DataLoader(self.dataset, batch_size=2, num_workers=4, prefetch_factor=3))
def test_shuffle_workers(self):
self._test_shuffle(self._get_data_loader(self.dataset, shuffle=True, num_workers=4))
def test_shuffle_batch_workers(self):
self._test_shuffle(self._get_data_loader(self.dataset, batch_size=2, shuffle=True, num_workers=4))
def test_shuffle_batch_workers_prefetch(self):
self._test_shuffle(DataLoader(self.dataset, batch_size=2, shuffle=True, num_workers=4, prefetch_factor=3))
def test_random_sampler(self):
from collections import Counter
from torch.utils.data import RandomSampler
def sample_stat(sampler, num_samples):
counts = Counter(sampler)
count_repeated = sum(val > 1 for val in counts.values())
return (count_repeated, min(counts.keys()), max(counts.keys()), sum(counts.values()))
# test sample with replacement
n = len(self.dataset) + 1 # ensure at least one sample is drawn more than once
sampler_with_replacement = RandomSampler(self.dataset, replacement=True, num_samples=n)
count_repeated, minval, maxval, count_total = sample_stat(sampler_with_replacement, n)
self.assertTrue(count_repeated > 0)
self.assertTrue(minval >= 0)
self.assertTrue(maxval < len(self.dataset))
self.assertTrue(count_total == n)
# test sample without replacement
sampler_without_replacement = RandomSampler(self.dataset)
count_repeated, minval, maxval, count_total = sample_stat(sampler_without_replacement, len(self.dataset))
self.assertTrue(count_repeated == 0)
self.assertTrue(minval == 0)
self.assertTrue(maxval == len(self.dataset) - 1)
self.assertTrue(count_total == len(self.dataset))
# raise error when replacement=False and num_samples is not None
self.assertRaises(ValueError, lambda: RandomSampler(self.dataset, num_samples=len(self.dataset)))
self.assertRaises(ValueError, lambda: RandomSampler(self.dataset, num_samples=0))
# raise error when replacement is non-boolean
with self.assertRaisesRegex(TypeError, "replacement should be a boolean value, but got replacement=0"):
RandomSampler(self.dataset, replacement=0)
def test_random_sampler_len_with_replacement(self):
from torch.utils.data import RandomSampler
# add 5 extra samples
num_samples = len(self.dataset) + 5
sampler = RandomSampler(self.dataset,
replacement=True,
num_samples=num_samples)
# test len method
self.assertEqual(num_samples, len(sampler))
# test with iteration
count_num_samples = sum(1 for _ in sampler)
self.assertEqual(num_samples, count_num_samples)
# test with dataloader, batch_size = 1
batch_size = 1
count_num_samples_in_data_loader = len(self._get_data_loader(
self.dataset, batch_size=batch_size, sampler=sampler))
self.assertEqual(num_samples, count_num_samples_in_data_loader)
# test with dataloader, batch_size = 6
batch_size = 6
count_num_samples_in_data_loader = len(self._get_data_loader(
self.dataset, batch_size=batch_size, sampler=sampler))
self.assertEqual(int(math.ceil(float(num_samples) / batch_size)),
count_num_samples_in_data_loader)
def test_distributed_sampler_invalid_rank(self):
from torch.utils.data.distributed import DistributedSampler
dataset = torch.IntTensor(range(10))
with self.assertRaisesRegex(ValueError, "Invalid rank"):
sampler = DistributedSampler(dataset, 3, 3)
with self.assertRaisesRegex(ValueError, "Invalid rank"):
sampler = DistributedSampler(dataset, 3, -1)
def test_duplicating_data_with_drop_last(self):
from torch.utils.data.distributed import DistributedSampler
num_processes = 4
num_batches = 9
data_set = torch.IntTensor(range(num_batches))
scanned_data = torch.IntTensor([])
for i in range(num_processes):
s = DistributedSampler(data_set, num_processes, i)
d_loader = self._get_data_loader(data_set, batch_size=int(num_batches / num_processes), drop_last=True, sampler=s)
for data in d_loader:
scanned_data = torch.cat((scanned_data, data), 0)
self.assertEqual(scanned_data.size(), scanned_data.unique().size())
def test_sampler_reproducibility(self):
from torch.utils.data import RandomSampler, WeightedRandomSampler, SubsetRandomSampler
weights = [0.1, 0.9, 0.4, 0.7, 3.0, 0.6]
for fn in (
lambda: RandomSampler(self.dataset, num_samples=5, replacement=True, generator=torch.Generator().manual_seed(42)),
lambda: RandomSampler(self.dataset, replacement=False, generator=torch.Generator().manual_seed(42)),
lambda: WeightedRandomSampler(weights, num_samples=5, replacement=True, generator=torch.Generator().manual_seed(42)),
lambda: WeightedRandomSampler(weights, num_samples=5, replacement=False, generator=torch.Generator().manual_seed(42)),
lambda: SubsetRandomSampler(range(10), generator=torch.Generator().manual_seed(42)),
):
self.assertEqual(list(fn()), list(fn()))
def _test_sampler(self, **kwargs):
indices = range(2, 12) # using a regular iterable
dl = self._get_data_loader(self.dataset, sampler=indices, batch_size=2, **kwargs)
self.assertEqual(len(dl), 5)
for i, (input, _target) in enumerate(dl):
self.assertEqual(len(input), 2)
self.assertEqual(input, self.data[i * 2 + 2:i * 2 + 4])
def test_sampler(self):
self._test_sampler()
self._test_sampler(num_workers=4)
if not NO_MULTIPROCESSING_SPAWN:
self._test_batch_sampler(num_workers=4, multiprocessing_context='spawn')
def _test_batch_sampler(self, **kwargs):
# [(0, 1), (2, 3, 4), (5, 6), (7, 8, 9), ...]
batches = [] # using a regular iterable
for i in range(0, 20, 5):
batches.append(tuple(range(i, i + 2)))
batches.append(tuple(range(i + 2, i + 5)))
dl = self._get_data_loader(self.dataset, batch_sampler=batches, **kwargs)
self.assertEqual(len(dl), 8)
for i, (input, _target) in enumerate(dl):
if i % 2 == 0:
offset = i * 5 // 2
self.assertEqual(len(input), 2)
self.assertEqual(input, self.data[offset:offset + 2])
else:
offset = i * 5 // 2
self.assertEqual(len(input), 3)
self.assertEqual(input, self.data[offset:offset + 3])
def test_batch_sampler(self):
self._test_batch_sampler()
self._test_batch_sampler(num_workers=4)
if not NO_MULTIPROCESSING_SPAWN:
self._test_batch_sampler(num_workers=4, multiprocessing_context='spawn')
@unittest.skipIf(not TEST_CUDA, "CUDA unavailable")
def test_shuffle_pin_memory(self):
loader = self._get_data_loader(self.dataset, batch_size=2, shuffle=True, num_workers=4, pin_memory=True)
for input, target in loader:
self.assertTrue(input.is_pinned())
self.assertTrue(target.is_pinned())
@unittest.skipIf(not TEST_NUMPY, "numpy unavailable")
def test_numpy(self):
import numpy as np
class TestDataset(torch.utils.data.Dataset):
def __getitem__(self, i):
return np.ones((2, 3, 4)) * i
def __len__(self):
return 1000
loader = self._get_data_loader(TestDataset(), batch_size=12)
batch = next(iter(loader))
self.assertIsInstance(batch, torch.DoubleTensor)
self.assertEqual(batch.size(), torch.Size([12, 2, 3, 4]))
@unittest.skipIf(not TEST_NUMPY, "numpy unavailable")
def test_numpy_gen_state(self):
from torch.utils.data._utils.worker import _generate_state
# Using NumPy generated states as the reference to test `_generate_state`
# having the same result.
# Test case: ((worker_id, base_seed), expected_state)
test_cases = [
((4, 13434589827475259383), (2884386318, 1088094898, 3523808998, 3860348662)),
((1, 15014285634777110771), (1934848465, 763213760, 2959016433, 179751970)),
((10, 978296274032934101), (1759791917, 3550927336, 1225977135, 1036538043)),
((12, 11868770762134256968), (3974661794, 3331131333, 3630387033, 2885815368)),
((9, 15378787925219019706), (3815056996, 3162224466, 2735102421, 3190253477)),
((5, 9055612723125076328), (3522565701, 3368424109, 959377806, 621878693)),
((15, 14617792358407278405), (3402479508, 1588702753, 1169536393, 3675067356)),
((9, 17363320784006640087), (957989458, 2518334477, 1421725660, 3086155459)),
((12, 480002904169484764), (2732851467, 1762620729, 4055801988, 1277640511)),
((15, 16803975943592702950), (3479415043, 4022359553, 295994005, 3358606349)),
((9, 11704776406047813044), (1968928009, 710113752, 2442656196, 1587420279)),
((10, 16357891985431864516), (1271733898, 4197047399, 3727213786, 2338547348)),
((2, 17423369006318065007), (544294336, 1911284083, 3299147734, 3231058347)),
((2, 2889492011444113593), (3721591783, 2595811276, 2212881745, 977682627)),
((0, 8979703111668486195), (4276723937, 2556068849, 2962827292, 233130238)),
((6, 6269787272229682235), (2548857855, 1216457374, 1012973562, 2999759647))
]
for (worker_id, base_seed), exp in test_cases:
self.assertEqual(exp, _generate_state(base_seed, worker_id))
def test_error(self):
self._test_error(self._get_data_loader(ErrorDataset(100), batch_size=2, shuffle=True))
def test_error_workers(self):
self._test_error(self._get_data_loader(ErrorDataset(41), batch_size=2, shuffle=True, num_workers=4))
@unittest.skipIf(IS_WINDOWS, "FIXME: stuck test")
def test_partial_workers(self):
r"""Check that workers exit even if the iterator is not exhausted."""
if TEST_CUDA:
pin_memory_configs = (True, False)
else:
pin_memory_configs = (False,)
for pin_memory in pin_memory_configs:
loader = iter(self._get_data_loader(self.dataset, batch_size=2, num_workers=4, pin_memory=pin_memory))
workers = loader._workers
if pin_memory:
pin_memory_thread = loader._pin_memory_thread
for i, _ in enumerate(loader):
if i == 10:
break
assert i == 10
del loader
for w in workers:
w.join(JOIN_TIMEOUT)
self.assertFalse(w.is_alive(), 'subprocess not terminated')
if pin_memory:
pin_memory_thread.join(JOIN_TIMEOUT)
self.assertFalse(pin_memory_thread.is_alive())
# Takes 2.5min to finish, see https://github.com/pytorch/pytorch/issues/46065
@skipIfRocm
@unittest.skipIf(not HAS_PSUTIL, "psutil not found")
@slowTest
def test_proper_exit(self):
(r'''There might be ConnectionResetError or leaked semaphore warning '''
r'''(due to dirty process exit), but they are all safe to ignore''')
# TODO: test the case where the pin_memory_thread triggers an
# error/fatal signal. I haven't found out how to properly do that.
for is_iterable_dataset, use_workers, pin_memory, hold_iter_reference in \
itertools.product([True, False], repeat=4):
# `hold_iter_reference` specifies whether we hold a reference to the
# iterator. This is interesting because Python3 error traces holds a
# reference to the frames, which hold references to all the local
# variables including the iterator, and then the iterator dtor may
# not be called before process end. It is important to see that the
# processes still exit in both cases.
if pin_memory and (not TEST_CUDA or NO_MULTIPROCESSING_SPAWN or IS_WINDOWS):
# This test runs in a subprocess, which can only initialize CUDA with spawn.
# DataLoader with pin_memory=True initializes CUDA when its iterator is constructed.
# For windows, pin_memory sometimes causes CUDA oom.
continue
# `exit_method` controls the way the loader process ends.
# - `*_kill` means that `*` is killed by OS.
# - `*_error` means that `*` raises an error.
# - `None` means that no error happens.
# In all cases, all processes should end properly.
if use_workers:
exit_methods = [None, 'loader_error', 'loader_kill', 'worker_error', 'worker_kill']
persistent_workers = self.persistent_workers
else:
exit_methods = [None, 'loader_error', 'loader_kill']
persistent_workers = False
for exit_method in exit_methods:
if exit_method == 'worker_kill':
# FIXME: This sometimes hangs. See #16608.
continue
desc = []
desc.append('is_iterable_dataset={}'.format(is_iterable_dataset))
desc.append('use_workers={}'.format(use_workers))
desc.append('pin_memory={}'.format(pin_memory))
desc.append('hold_iter_reference={}'.format(hold_iter_reference))
desc.append('exit_method={}'.format(exit_method))
desc = 'test_proper_exit with ' + ', '.join(desc)
# Event that the loader process uses to signal testing process
# that various things are setup, including that the worker pids
# are specified in `worker_pids` array.
loader_setup_event = mp.Event()
# Event that this process has finished setting up, and the
# loader process can now proceed to trigger error events or
# finish normally.
tester_setup_event = mp.Event()
loader_p = ErrorTrackingProcess(target=_test_proper_exit,
args=(is_iterable_dataset, use_workers, pin_memory,
exit_method, hold_iter_reference,
loader_setup_event, tester_setup_event,
persistent_workers),
disable_stderr=False)
loader_p.start()
loader_psutil_p = psutil.Process(loader_p.pid)
# Wait for loader process to set everything up, e.g., starting
# workers.
loader_setup_event.wait(timeout=JOIN_TIMEOUT)
if not loader_setup_event.is_set():
fail_msg = desc + ': loader process failed to setup within given time'
if loader_p.exception is not None:
fail_msg += ', and had exception {}'.format(loader_p.exception)
elif not loader_p.is_alive():
fail_msg += ', and exited with code {} but had no exception'.format(loader_p.exitcode)
else:
fail_msg += ', and is still alive.'
if loader_p.is_alive():
# this may kill the process, needs to run after the above lines
loader_p.print_traces_of_all_threads()
self.fail(fail_msg)
# We are certain that the workers have started now.
worker_psutil_ps = loader_psutil_p.children()
def fail(reason):
report_psutil_attrs = ['pid', 'name', 'cpu_times', 'io_counters',
'memory_full_info', 'num_ctx_switches',
'open_files', 'threads', 'status',
'nice', 'ionice']
if reason is None:
err_msg = desc
else:
err_msg = '{}: {}'.format(desc, reason)
err_msg += '\nLoader info:\n\t'
if loader_psutil_p.is_running():
err_msg += str(loader_psutil_p.as_dict(attrs=report_psutil_attrs))
# this may kill the process, needs to run after the above line
loader_p.print_traces_of_all_threads()
else:
err_msg += 'exited with code {}'.format(loader_p.exitcode)
if use_workers:
err_msg += '\nWorker(s) info:'
for idx, worker_psutil_p in enumerate(worker_psutil_ps):
err_msg += '\n\tWorker {}:\n\t\t'.format(idx)
if worker_psutil_p.is_running():
err_msg += str(worker_psutil_p.as_dict(attrs=report_psutil_attrs))
# this may kill the process, needs to run after the above line
print_traces_of_all_threads(worker_psutil_p.pid)
else:
err_msg += 'exited with unknown code'
self.fail(err_msg)
tester_setup_event.set()
try:
loader_p.join(JOIN_TIMEOUT + MP_STATUS_CHECK_INTERVAL)
if loader_p.is_alive():
fail_reason = 'loader process did not terminate'
if loader_p.exception is not None:
fail(fail_reason + ', and had exception {}'.format(loader_p.exception))
else:
fail(fail_reason + ', and had no exception')
_, alive = psutil.wait_procs(worker_psutil_ps, timeout=(MP_STATUS_CHECK_INTERVAL + JOIN_TIMEOUT))
if len(alive) > 0:
fail('worker process (pid(s) {}) did not terminate'.format(
', '.join(str(p.pid) for p in alive)))
if exit_method is None:
if loader_p.exitcode != 0:
fail('loader process had nonzero exitcode {}'.format(loader_p.exitcode))
else:
if loader_p.exitcode == 0:
fail('loader process had zero exitcode')
if exit_method == 'loader_error':
if not isinstance(loader_p.exception, RuntimeError) or \
'Loader error' not in str(loader_p.exception):
fail('loader process did not raise expected exception, but had {}'.format(
loader_p.exception))
elif exit_method == 'worker_kill':
if isinstance(loader_p.exception, RuntimeError):
if 'DataLoader worker (pid' not in str(loader_p.exception):
fail('loader process did not raise expected exception, but had {}'.format(
loader_p.exception))
elif isinstance(loader_p.exception, ConnectionRefusedError):
# Sometimes, when the worker is being killed and is freeing its
# resources, the unpickling in loader process will be met an
# a `ConnectionRefusedError` as it can not open a socket to receive
# resource. In such cases, the worker may not have fully exited,
# and the loader can't know this via `is_alive` check or `SIGCHLD`
# handler. So we permit this as an allowed error as well.
# After all, we are happy as long as it terminates.
pass
else:
fail('loader process did not raise expected exception, but had {}'.format(
loader_p.exception))
elif exit_method == 'worker_error':
if not isinstance(loader_p.exception, RuntimeError) or \
'Worker error' not in str(loader_p.exception):
fail('loader process did not raise expected exception, but had {}'.format(
loader_p.exception))
finally:
loader_p.terminate()
def test_len(self):
def check_len(dl, expected):
self.assertEqual(len(dl), expected)
n = 0
for _ in dl:
n += 1
self.assertEqual(n, expected)
check_len(self.dataset, 100)
check_len(self._get_data_loader(self.dataset, batch_size=2), 50)
check_len(self._get_data_loader(self.dataset, batch_size=3), 34)
def test_iterabledataset_len(self):
class IterableDataset(torch.utils.data.IterableDataset):
def __len__(self):
return 10
def __iter__(self):
return iter(range(10))
iterable_loader = DataLoader(IterableDataset(), batch_size=1)
self.assertEqual(len(iterable_loader), 10)
iterable_loader = DataLoader(IterableDataset(), batch_size=1, drop_last=True)
self.assertEqual(len(iterable_loader), 10)
iterable_loader = DataLoader(IterableDataset(), batch_size=2)
self.assertEqual(len(iterable_loader), 5)
iterable_loader = DataLoader(IterableDataset(), batch_size=2, drop_last=True)
self.assertEqual(len(iterable_loader), 5)
iterable_loader = DataLoader(IterableDataset(), batch_size=3)
self.assertEqual(len(iterable_loader), 4)
iterable_loader = DataLoader(IterableDataset(), batch_size=3, drop_last=True)
self.assertEqual(len(iterable_loader), 3)
@unittest.skipIf(not TEST_NUMPY, "numpy unavailable")
def test_numpy_scalars(self):
import numpy as np
class ScalarDataset(torch.utils.data.Dataset):
def __init__(self, dtype):
self.dtype = dtype
def __getitem__(self, i):
return self.dtype()
def __len__(self):
return 4
dtypes = {
np.float64: torch.DoubleTensor,
np.float32: torch.FloatTensor,
np.float16: torch.HalfTensor,
np.int64: torch.LongTensor,
np.int32: torch.IntTensor,
np.int16: torch.ShortTensor,
np.int8: torch.CharTensor,
np.uint8: torch.ByteTensor,
}
for dt, tt in dtypes.items():
dset = ScalarDataset(dt)
loader = self._get_data_loader(dset, batch_size=2)
batch = next(iter(loader))
self.assertIsInstance(batch, tt)
def test_default_collate_dtype(self):
arr = [1, 2, -1]
collated = _utils.collate.default_collate(arr)
self.assertEqual(collated, torch.tensor(arr))
self.assertEqual(collated.dtype, torch.int64)
arr = [1.1, 2.3, -0.9]
collated = _utils.collate.default_collate(arr)
# TODO(#38095): Replace assertEqualIgnoreType. See issue #38095
self.assertEqualIgnoreType(collated, torch.tensor(arr))
self.assertEqual(collated.dtype, torch.float64)
arr = [True, False]
collated = _utils.collate.default_collate(arr)
self.assertEqual(collated, torch.tensor(arr))
self.assertEqual(collated.dtype, torch.bool)
# Should be a no-op
arr = ['a', 'b', 'c']
self.assertEqual(arr, _utils.collate.default_collate(arr))
@unittest.skipIf(not TEST_NUMPY, "numpy unavailable")
def test_default_collate_bad_numpy_types(self):
import numpy as np
# Should be a no-op
arr = np.array(['a', 'b', 'c'])
self.assertEqual(arr, _utils.collate.default_collate(arr))
arr = np.array([[['a', 'b', 'c']]])
self.assertRaises(TypeError, lambda: _utils.collate.default_collate(arr))
arr = np.array([object(), object(), object()])
self.assertRaises(TypeError, lambda: _utils.collate.default_collate(arr))
arr = np.array([[[object(), object(), object()]]])
self.assertRaises(TypeError, lambda: _utils.collate.default_collate(arr))
@unittest.skipIf(not TEST_NUMPY, "numpy unavailable")
def test_default_collate_numpy_memmap(self):
import numpy as np
with tempfile.TemporaryFile() as f:
arr = np.array([[0, 1], [2, 3], [4, 5], [6, 7]])
arr_memmap = np.memmap(f, dtype=arr.dtype, mode='w+', shape=arr.shape)
arr_memmap[:] = arr[:]
arr_new = np.memmap(f, dtype=arr.dtype, mode='r', shape=arr.shape)
tensor = _utils.collate.default_collate(list(arr_new))
self.assertTrue((tensor == tensor.new_tensor([[0, 1], [2, 3], [4, 5], [6, 7]])).all().item())
def test_default_collate_bad_sequence_type(self):
batch = [['X'], ['X', 'X']]
self.assertRaises(RuntimeError, lambda: _utils.collate.default_collate(batch))
self.assertRaises(RuntimeError, lambda: _utils.collate.default_collate(batch[::-1]))
@unittest.skipIf(not TEST_NUMPY, "numpy unavailable")
def test_default_collate_shared_tensor(self):
import numpy as np
t_in = torch.zeros(1)
n_in = np.zeros(1)
self.assertEqual(t_in.is_shared(), False)
self.assertEqual(_utils.collate.default_collate([t_in]).is_shared(), False)
self.assertEqual(_utils.collate.default_collate([n_in]).is_shared(), False)
# FIXME: fix the following hack that makes `default_collate` believe
# that it is in a worker process (since it tests
# `get_worker_info() != None`), even though it is not.
old = _utils.worker._worker_info
try:
_utils.worker._worker_info = 'x'
self.assertEqual(_utils.collate.default_collate([t_in]).is_shared(), True)
self.assertEqual(_utils.collate.default_collate([n_in]).is_shared(), True)
finally:
_utils.worker._worker_info = old
def test_excessive_thread_creation_warning(self):
with self.assertWarnsRegex(
UserWarning,
r"excessive worker creation might get DataLoader running slow or even freeze"):
dataloader = DataLoader(self.dataset, batch_size=2, num_workers=1000)
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)")
class TestDataLoader2(TestCase):
@skipIfNoDill
def test_basics(self):
dp = IterableAsDataPipe(list(range(10)))
dl = DataLoader(dp, batch_size=3, collate_fn=lambda x: x, num_workers=2)
dl2 = DataLoader2(dp, batch_size=3, collate_fn=lambda x: x, num_workers=2)
self.assertEquals(list(dl), list(dl2))
class StringDataset(Dataset):
def __init__(self):
self.s = '12345'
def __len__(self):
return len(self.s)
def __getitem__(self, ndx):
return (self.s[ndx], ndx)
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)")
class TestStringDataLoader(TestCase):
def setUp(self):
super(TestStringDataLoader, self).setUp()
self.dataset = StringDataset()
@unittest.skipIf(not TEST_CUDA, "CUDA unavailable")
def test_shuffle_pin_memory(self):
loader = DataLoader(self.dataset, batch_size=2, shuffle=True, num_workers=4, pin_memory=True)
for (s, n) in loader:
self.assertIsInstance(s[0], str)
self.assertTrue(n.is_pinned())
class DictDataset(Dataset):
def __len__(self):
return 4
def __getitem__(self, ndx):
return {
'a_tensor': torch.empty(4, 2).fill_(ndx),
'another_dict': {
'a_number': ndx,
},
}
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)")
class TestDictDataLoader(TestCase):
def setUp(self):
super(TestDictDataLoader, self).setUp()
self.dataset = DictDataset()
def test_sequential_batch(self):
for persistent_workers in (False, True):
if persistent_workers:
loader = DataLoader(self.dataset, batch_size=2, shuffle=False,
persistent_workers=persistent_workers, num_workers=1)
else:
loader = DataLoader(self.dataset, batch_size=2, shuffle=False,
persistent_workers=persistent_workers)
batch_size = loader.batch_size
for i, sample in enumerate(loader):
idx = i * batch_size
self.assertEqual(set(sample.keys()), {'a_tensor', 'another_dict'})
self.assertEqual(set(sample['another_dict'].keys()), {'a_number'})
t = sample['a_tensor']
self.assertEqual(t.size(), torch.Size([batch_size, 4, 2]))
self.assertTrue((t[0] == idx).all())
self.assertTrue((t[1] == idx + 1).all())
n = sample['another_dict']['a_number']
self.assertEqual(n.size(), torch.Size([batch_size]))
self.assertEqual(n[0], idx)
self.assertEqual(n[1], idx + 1)
@unittest.skipIf(not TEST_CUDA, "CUDA unavailable")
def test_pin_memory(self):
loader = DataLoader(self.dataset, batch_size=2, pin_memory=True)
for sample in loader:
self.assertTrue(sample['a_tensor'].is_pinned())
self.assertTrue(sample['another_dict']['a_number'].is_pinned())
class DummyDataset(torch.utils.data.Dataset):
def __init__(self):
self.data = list(range(10))
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
# The persistent workers always maintain the original
# dataset through the dataloader lifetime
# so the attributes will remain the same as the
# first time the workers where spawned (dataloader iteration)
assert self.start == 0
return self.data[idx]
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)")
class TestDataLoaderPersistentWorkers(TestDataLoader):
def setUp(self):
super(TestDataLoaderPersistentWorkers, self).setUp()
self.persistent_workers = True
@unittest.skipIf(IS_SANDCASTLE, "subprocess doesn't work in FB internal CI")
@unittest.skipIf(IS_WINDOWS, "No 'resource' module on Windows")
def test_fd_limit_exceeded(self):
# See NOTE [ DataLoader on Linux and open files limit ]
import subprocess
subprocess.check_output([sys.executable, '-c', """\
import torch
import resource
from torch.utils.data import DataLoader, IterableDataset
class RandomDataset(IterableDataset):
def __init__(self, len, size):
super(RandomDataset).__init__()
self.len = len
self.size = size
def __iter__(self):
return self
def __next__(self):
if self.len <= 0:
raise StopIteration
self.len -= 1
return torch.randn(self.size)
try:
keep_fds_alive = []
resource.setrlimit(resource.RLIMIT_NOFILE, (100, 100))
for random_t in DataLoader(RandomDataset(200, (2,2)), multiprocessing_context="fork",
num_workers=1, persistent_workers=True):
random_t.max(dim=0)
keep_fds_alive.append(random_t)
except RuntimeError as e:
assert "ulimit -n" in str(e)
assert "set_sharing_strategy" in str(e)
"""])
def test_dataset_not_reset(self):
dataset = DummyDataset()
pin_memory_configs = [False]
if TEST_CUDA:
pin_memory_configs.append(True)
for pin_memory in pin_memory_configs:
dataloader = self._get_data_loader(dataset, num_workers=2, pin_memory=pin_memory)
dataset.start = 0
for i in range(10):
for x in dataloader:
pass
# Changing the start value here doesn't have any effect in the dataset
# cached by the workers. since they are not recreated between epochs
# and can cache values safely
dataset.start = i
class NamedTupleDataset(Dataset):
from collections import namedtuple
Batch = namedtuple('Batch', ['data', 'label', 'random_tensor'])
Data = namedtuple('Data', ['positive', 'negative'])
def __len__(self):
return 4
def __getitem__(self, ndx):
return self.Batch(data=self.Data(positive=ndx, negative=-ndx),
label=str(ndx), random_tensor=torch.randn(3))
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)")
class TestNamedTupleDataLoader(TestCase):
def setUp(self):
super(TestNamedTupleDataLoader, self).setUp()
self.dataset = NamedTupleDataset()
def test_dataloader_with_namedtuple(self):
# auto-collation
loader = DataLoader(self.dataset, batch_size=2, pin_memory=TEST_CUDA)
for batch in loader:
self.assertIsInstance(batch, NamedTupleDataset.Batch)
self.assertEqual(batch.random_tensor.is_pinned(), TEST_CUDA)
self.assertIsInstance(batch.data, NamedTupleDataset.Data)
self.assertIsInstance(batch.data.positive, torch.Tensor)
self.assertEqual(batch.data.positive.is_pinned(), TEST_CUDA)
# no auto-collation
loader = DataLoader(self.dataset, batch_size=None, pin_memory=TEST_CUDA)
for batch in loader:
self.assertIsInstance(batch, NamedTupleDataset.Batch)
self.assertEqual(batch.random_tensor.is_pinned(), TEST_CUDA)
self.assertIsInstance(batch.data, NamedTupleDataset.Data)
self.assertNotIsInstance(batch.data.positive, torch.Tensor)
class SimpleCustomBatch(object):
def __init__(self, data):
transposed_data = list(zip(*data))
self.inp = torch.stack(transposed_data[0], 0)
self.tgt = torch.stack(transposed_data[1], 0)
def pin_memory(self):
self.inp = self.inp.pin_memory()
self.tgt = self.tgt.pin_memory()
return self
def is_pinned(self):
return self.inp.is_pinned() and self.tgt.is_pinned()
# Workaround for https://github.com/pytorch/pytorch/issues/50661
# Classes from `__main__` can not be correctly unpickled from spawned module
# See https://docs.python.org/3/library/multiprocessing.html#multiprocessing-programming
self_module = __import__(os.path.splitext(os.path.basename(__file__))[0])
def collate_wrapper(batch):
return self_module.SimpleCustomBatch(batch)
def collate_into_packed_sequence(batch):
data = torch.stack([sample[0] for sample in batch], 1)
t, b = data.size()
lengths = torch.randint(1, t, size=(b,), dtype=torch.int64)
return torch.nn.utils.rnn.pack_padded_sequence(data, lengths, enforce_sorted=False)
def collate_into_packed_sequence_batch_first(batch):
data = torch.stack([sample[0] for sample in batch], 0)
b, t = data.size()
lengths = torch.randint(1, t, size=(b,), dtype=torch.int64)
return torch.nn.utils.rnn.pack_padded_sequence(data, lengths, batch_first=True, enforce_sorted=False)
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)")
class TestCustomPinFn(TestCase):
def setUp(self):
super(TestCustomPinFn, self).setUp()
inps = torch.arange(10 * 5, dtype=torch.float32).view(10, 5)
tgts = torch.arange(10 * 5, dtype=torch.float32).view(10, 5)
self.dataset = TensorDataset(inps, tgts)
@unittest.skipIf(not TEST_CUDA, "CUDA unavailable")
def test_custom_batch_pin(self):
test_cases = [
(collate_wrapper, self_module.SimpleCustomBatch),
(collate_into_packed_sequence, torch.nn.utils.rnn.PackedSequence),
(collate_into_packed_sequence_batch_first, torch.nn.utils.rnn.PackedSequence),
]
for collate_fn, elem_cls in test_cases:
loader = DataLoader(self.dataset, batch_size=2, collate_fn=collate_fn,
pin_memory=True)
for sample in loader:
self.assertIsInstance(sample, elem_cls)
self.assertTrue(sample.is_pinned())
@unittest.skipIf(not TEST_CUDA, "CUDA unavailable")
def test_custom_batch_pin_worker(self):
test_cases = [
(collate_wrapper, self_module.SimpleCustomBatch),
(collate_into_packed_sequence, torch.nn.utils.rnn.PackedSequence),
(collate_into_packed_sequence_batch_first, torch.nn.utils.rnn.PackedSequence),
]
for collate_fn, elem_cls in test_cases:
loader = DataLoader(self.dataset, batch_size=2, collate_fn=collate_fn,
pin_memory=True, num_workers=1)
for sample in loader:
self.assertIsInstance(sample, elem_cls)
self.assertTrue(sample.is_pinned())
class TestWorkerQueueDataset(Dataset):
def __init__(self, data):
self.data = data
self.worker_id = None
def worker_init_fn(self, worker_id):
self.worker_id = worker_id
def __getitem__(self, item):
return self.worker_id, self.data[item]
def __len__(self):
return len(self.data)
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)")
class TestIndividualWorkerQueue(TestCase):
def setUp(self):
super(TestIndividualWorkerQueue, self).setUp()
self.dataset = TestWorkerQueueDataset(list(range(128)))
def _run_ind_worker_queue_test(self, batch_size, num_workers):
loader = DataLoader(
self.dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers,
worker_init_fn=self.dataset.worker_init_fn
)
current_worker_idx = 0
for i, (worker_ids, sample) in enumerate(loader):
self.assertEqual(worker_ids.tolist(), [current_worker_idx] * batch_size)
self.assertEqual(sample.tolist(), list(range(i * batch_size, (i + 1) * batch_size)))
current_worker_idx += 1
if current_worker_idx == num_workers:
current_worker_idx = 0
def test_ind_worker_queue(self):
for batch_size in (8, 16, 32, 64):
for num_workers in range(1, 6):
self._run_ind_worker_queue_test(batch_size=batch_size, num_workers=num_workers)
class SetAffinityDataset(IterableDataset):
def __iter__(self):
torch.randperm(1)
after = os.sched_getaffinity(0)
return iter(after)
def worker_set_affinity(_):
os.sched_setaffinity(0, [2])
@unittest.skipIf(
not hasattr(os, 'sched_setaffinity'),
"os.sched_setaffinity is not available")
class TestSetAffinity(TestCase):
def test_set_affinity_in_worker_init(self):
dataset = SetAffinityDataset()
dataloader = torch.utils.data.DataLoader(
dataset, num_workers=2, worker_init_fn=worker_set_affinity)
for sample in dataloader:
self.assertEqual(sample, [2])
class ConvDataset(Dataset):
def __init__(self):
self.x = torch.ones(1, 1, 24000)
# Call convolution on parent process
self[0]
def __len__(self):
return 1
def __getitem__(self, index):
return torch.nn.functional.conv1d(self.x, torch.ones(1, 1, 2))
@unittest.skipIf(IS_WINDOWS, "Needs fork")
class TestConvAfterFork(TestCase):
# Tests crash reported in https://github.com/pytorch/pytorch/issues/53565
def test_conv_after_fork(self):
loader = DataLoader(ConvDataset(), num_workers=1)
for x in loader:
self.assertEqual(x.shape, (1, 1, 1, 23999))
if __name__ == '__main__':
run_tests()
|
test_flask_redis_sentinel.py | # Copyright 2015, 2016, 2017 Exponea s r.o. <info@exponea.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import threading
from unittest import TestCase
from flask import Flask
from mock import MagicMock
import redis
from flask_redis_sentinel import SentinelExtension
class FakeRedis(MagicMock):
def __init__(self, host='localhost', port=6379,
db=0, password=None, socket_timeout=None,
socket_connect_timeout=None,
socket_keepalive=None, socket_keepalive_options=None,
connection_pool=None, unix_socket_path=None,
encoding='utf-8', encoding_errors='strict',
charset=None, errors=None,
decode_responses=False, retry_on_timeout=False,
ssl=False, ssl_keyfile=None, ssl_certfile=None,
ssl_cert_reqs=None, ssl_ca_certs=None):
super(FakeRedis, self).__init__()
self.kwargs = {
'host': host,
'port': port,
'db': db,
'password': password,
'socket_timeout': socket_timeout,
'socket_connect_timeout': socket_connect_timeout,
'socket_keepalive': socket_keepalive,
'socket_keepalive_options': socket_keepalive_options,
'connection_pool': connection_pool,
'unix_socket_path': unix_socket_path,
'encoding': encoding,
'encoding_errors': encoding_errors,
'charset': charset,
'errors': errors,
'decode_responses': decode_responses,
'retry_on_timeout': retry_on_timeout,
'ssl': ssl,
'ssl_keyfile': ssl_keyfile,
'ssl_certfile': ssl_certfile,
'ssl_cert_reqs': ssl_cert_reqs,
'ssl_ca_certs': ssl_ca_certs
}
@classmethod
def from_url(cls, url, **kwargs):
i = cls()
i.kwargs = {'url': url}
i.kwargs.update(kwargs)
return i
class FakeSentinel(object):
def __init__(self, sentinels, min_other_sentinels=0, sentinel_kwargs=None,
**connection_kwargs):
self._sentinels = sentinels
self.min_other_sentinels = min_other_sentinels
self.sentinel_kwargs = sentinel_kwargs
self.connection_kwargs = connection_kwargs
def _update_kwargs(self, kwargs, connection_kwargs):
connection = dict(self.connection_kwargs)
connection.update(connection_kwargs)
kwargs['connection_kwargs'] = connection
def master_for(self, service_name, redis_class=redis.StrictRedis,
connection_pool_class=redis.sentinel.SentinelConnectionPool, **kwargs):
i = FakeRedis()
i.kwargs = {
'is_master': True,
'service_name': service_name,
'redis_class': redis_class,
'connection_pool_class': connection_pool_class
}
self._update_kwargs(i.kwargs, kwargs)
return i
def slave_for(self, service_name, redis_class=redis.StrictRedis,
connection_pool_class=redis.sentinel.SentinelConnectionPool, **kwargs):
i = FakeRedis()
i.kwargs = {
'is_master': False,
'service_name': service_name,
'redis_class': redis_class,
'connection_pool_class': connection_pool_class
}
self._update_kwargs(i.kwargs, kwargs)
return i
class TestWithApp(TestCase):
def setUp(self):
self.app = Flask('test')
def test_default_connection(self):
sentinel = SentinelExtension(client_class=FakeRedis)
sentinel.init_app(self.app)
conn = sentinel.default_connection
with self.app.app_context():
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['url'], 'redis://localhost/0')
def test_default_connection_with_config_class(self):
sentinel = SentinelExtension()
self.app.config['REDIS_CLASS'] = FakeRedis
sentinel.init_app(self.app)
conn = sentinel.default_connection
with self.app.app_context():
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['url'], 'redis://localhost/0')
def test_default_connection_with_init_class(self):
sentinel = SentinelExtension()
sentinel.init_app(self.app, client_class=FakeRedis)
conn = sentinel.default_connection
with self.app.app_context():
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['url'], 'redis://localhost/0')
def test_default_connection_with_config_class_string(self):
sentinel = SentinelExtension()
self.app.config['REDIS_CLASS'] = 'test_flask_redis_sentinel.FakeRedis'
sentinel.init_app(self.app)
conn = sentinel.default_connection
with self.app.app_context():
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['url'], 'redis://localhost/0')
def test_default_connection_redis_url(self):
sentinel = SentinelExtension(client_class=FakeRedis)
self.app.config['REDIS_URL'] = 'redis://hostname:7001/3'
self.app.config['REDIS_HOST'] = 'ignored' # should be ignored
self.app.config['REDIS_PORT'] = 5000 # should be ignored
self.app.config['REDIS_DB'] = 7 # should be ignored
sentinel.init_app(self.app)
conn = sentinel.default_connection
with self.app.app_context():
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['url'], 'redis://hostname:7001/3')
self.assertNotIn('host', inst.kwargs)
self.assertNotIn('port', inst.kwargs)
self.assertNotIn('db', inst.kwargs)
def test_default_connection_redis_vars(self):
sentinel = SentinelExtension(client_class=FakeRedis)
self.app.config['REDIS_URL'] = 'redis://hostname:7001/3'
self.app.config['REDIS_DECODE_RESPONSES'] = True
sentinel.init_app(self.app)
conn = sentinel.default_connection
with self.app.app_context():
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['url'], 'redis://hostname:7001/3')
self.assertEqual(inst.kwargs['decode_responses'], True)
def test_sentinel_kwargs_from_config(self):
sentinel = SentinelExtension(client_class=FakeRedis, sentinel_class=FakeSentinel)
self.app.config['REDIS_URL'] = 'redis+sentinel://hostname:7001/mymaster/3'
self.app.config['REDIS_SENTINEL_SOCKET_CONNECT_TIMEOUT'] = 0.3
sentinel.init_app(self.app)
with self.app.app_context():
self.assertIsNotNone(sentinel.sentinel)
self.assertEquals(sentinel.sentinel.sentinel_kwargs, {'socket_connect_timeout': 0.3})
def test_default_connection_sentinel_url_master(self):
sentinel = SentinelExtension(client_class=FakeRedis, sentinel_class=FakeSentinel)
self.app.config['REDIS_URL'] = 'redis+sentinel://hostname:7001/mymaster/3'
self.app.config['REDIS_DECODE_RESPONSES'] = True
sentinel.init_app(self.app)
conn = sentinel.default_connection
with self.app.app_context():
self.assertIsNotNone(sentinel.sentinel)
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['is_master'], True)
self.assertEqual(inst.kwargs['service_name'], 'mymaster')
self.assertEqual(inst.kwargs['connection_kwargs']['db'], 3)
self.assertEqual(inst.kwargs['connection_kwargs']['decode_responses'], True)
def test_default_connection_sentinel_url_slave(self):
sentinel = SentinelExtension(client_class=FakeRedis, sentinel_class=FakeSentinel)
self.app.config['REDIS_URL'] = 'redis+sentinel://hostname:7001/myslave/3?client_type=slave'
self.app.config['REDIS_DECODE_RESPONSES'] = True
self.app.config['REDIS_SENTINEL_SOCKET_CONNECT_TIMEOUT'] = 0.3
sentinel.init_app(self.app)
conn = sentinel.default_connection
with self.app.app_context():
self.assertIsNotNone(sentinel.sentinel)
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['is_master'], False)
self.assertEqual(inst.kwargs['service_name'], 'myslave')
self.assertEqual(inst.kwargs['connection_kwargs']['db'], 3)
self.assertEqual(inst.kwargs['connection_kwargs']['decode_responses'], True)
def test_unsupported_url_scheme(self):
sentinel = SentinelExtension(client_class=FakeRedis, sentinel_class=FakeSentinel)
self.app.config['REDIS_URL'] = 'redis+something://hostname:7001/myslave/3?slave=true'
with self.assertRaisesRegexp(ValueError, r'Unsupported redis URL scheme: redis\+something'):
sentinel.init_app(self.app)
def test_default_connection_with_init_sentinel_class(self):
sentinel = SentinelExtension(client_class=FakeRedis)
self.app.config['REDIS_URL'] = 'redis+sentinel://hostname:7001/mymaster/3'
sentinel.init_app(self.app, sentinel_class=FakeSentinel)
conn = sentinel.default_connection
with self.app.app_context():
self.assertIsNotNone(sentinel.sentinel)
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['is_master'], True)
def test_default_connection_with_config_sentinel_class(self):
sentinel = SentinelExtension(client_class=FakeRedis)
self.app.config['REDIS_SENTINEL_CLASS'] = FakeSentinel
self.app.config['REDIS_URL'] = 'redis+sentinel://hostname:7001/mymaster/3'
sentinel.init_app(self.app)
conn = sentinel.default_connection
with self.app.app_context():
self.assertIsNotNone(sentinel.sentinel)
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['is_master'], True)
def test_default_connection_with_config_sentinel_class_string(self):
sentinel = SentinelExtension(client_class=FakeRedis)
self.app.config['REDIS_SENTINEL_CLASS'] = 'test_flask_redis_sentinel.FakeSentinel'
self.app.config['REDIS_URL'] = 'redis+sentinel://hostname:7001/mymaster/3'
sentinel.init_app(self.app)
conn = sentinel.default_connection
with self.app.app_context():
self.assertIsNotNone(sentinel.sentinel)
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['is_master'], True)
def test_duplicate_prefix_registration(self):
sentinel = SentinelExtension()
sentinel2 = SentinelExtension()
sentinel.init_app(self.app)
msg = 'Redis sentinel extension with config prefix REDIS is already registered'
with self.assertRaisesRegexp(RuntimeError, msg):
sentinel2.init_app(self.app)
def test_multiple_prefix_registration(self):
sentinel = SentinelExtension()
sentinel2 = SentinelExtension()
sentinel.init_app(self.app)
sentinel2.init_app(self.app, config_prefix='ANOTHER_REDIS')
def test_init_app_in_constructor(self):
self.app.config['REDIS_URL'] = 'redis://hostname:7001/3'
sentinel = SentinelExtension(app=self.app, client_class=FakeRedis)
conn = sentinel.default_connection
with self.app.app_context():
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['url'], 'redis://hostname:7001/3')
def test_init_app_with_prefix_in_constructor(self):
self.app.config['REDIS_URL'] = 'redis://hostname:7001/3'
self.app.config['CUSTOM_REDIS_URL'] = 'redis://hostname2:7003/5'
sentinel = SentinelExtension(app=self.app, client_class=FakeRedis, config_prefix='CUSTOM_REDIS')
conn = sentinel.default_connection
with self.app.app_context():
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['url'], 'redis://hostname2:7003/5')
def _check_threads(self, sentinel):
connections = {}
with self.app.app_context():
connections['from_main_thread'] = sentinel.default_connection._get_current_object()
def in_another_thread():
with self.app.app_context():
connections['from_another_thread'] = sentinel.default_connection._get_current_object()
thread = threading.Thread(target=in_another_thread)
thread.start()
thread.join()
with self.app.app_context():
connections['from_main_thread_later'] = sentinel.default_connection._get_current_object()
return connections
def test_sentinel_threads(self):
sentinel = SentinelExtension(client_class=FakeRedis, sentinel_class=FakeSentinel)
self.app.config['REDIS_URL'] = 'redis+sentinel://hostname:7001/myslave/0'
sentinel.init_app(self.app)
connections = self._check_threads(sentinel)
self.assertIsNot(connections['from_another_thread'], connections['from_main_thread'])
self.assertIsNot(connections['from_another_thread'], connections['from_main_thread_later'])
self.assertIs(connections['from_main_thread'], connections['from_main_thread_later'])
def test_redis_threads(self):
sentinel = SentinelExtension(client_class=FakeRedis, sentinel_class=FakeSentinel)
self.app.config['REDIS_URL'] = 'redis://hostname:7001/0'
sentinel.init_app(self.app)
connections = self._check_threads(sentinel)
self.assertIs(connections['from_another_thread'], connections['from_main_thread'])
self.assertIs(connections['from_another_thread'], connections['from_main_thread_later'])
self.assertIs(connections['from_main_thread'], connections['from_main_thread_later'])
def test_mixed_apps(self):
sentinel1 = SentinelExtension(app=self.app, client_class=FakeRedis)
conn1 = sentinel1.default_connection
self.app2 = Flask('test2')
sentinel2 = SentinelExtension(app=self.app2, config_prefix='CUSTOM_REDIS', client_class=FakeRedis)
conn2 = sentinel2.default_connection
self.app3 = Flask('test3')
with self.app2.app_context():
msg = 'Redis sentinel extension with config prefix REDIS was not initialized for application test2'
with self.assertRaisesRegexp(RuntimeError, msg):
conn1._get_current_object()
with self.app3.app_context():
msg = 'Redis sentinel extension with config prefix REDIS was not initialized for application test3'
with self.assertRaisesRegexp(RuntimeError, msg):
conn1._get_current_object()
def test_named_master(self):
sentinel = SentinelExtension(client_class=FakeRedis, sentinel_class=FakeSentinel)
self.app.config['REDIS_URL'] = 'redis+sentinel://hostname:7001/mymaster/3'
self.app.config['REDIS_DECODE_RESPONSES'] = True
sentinel.init_app(self.app)
conn = sentinel.master_for('othermaster', db=6)
with self.app.app_context():
self.assertIsNotNone(sentinel.sentinel)
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['is_master'], True)
self.assertEqual(inst.kwargs['service_name'], 'othermaster')
self.assertEqual(inst.kwargs['connection_kwargs']['db'], 6)
self.assertEqual(inst.kwargs['connection_kwargs']['decode_responses'], True)
def test_named_master_no_sentinel(self):
sentinel = SentinelExtension(client_class=FakeRedis, sentinel_class=FakeSentinel)
self.app.config['REDIS_URL'] = 'redis://hostname:7001/3'
sentinel.init_app(self.app)
conn = sentinel.master_for('othermaster', db=6)
with self.app.app_context():
self.assertIsNone(sentinel.sentinel._get_current_object())
with self.assertRaisesRegexp(RuntimeError, 'Cannot get master othermaster using non-sentinel configuration'):
inst = conn._get_current_object()
def test_named_slave(self):
sentinel = SentinelExtension(client_class=FakeRedis, sentinel_class=FakeSentinel)
self.app.config['REDIS_URL'] = 'redis+sentinel://hostname:7001/mymaster/3'
self.app.config['REDIS_DECODE_RESPONSES'] = True
sentinel.init_app(self.app)
conn = sentinel.slave_for('otherslave', db=6)
with self.app.app_context():
self.assertIsNotNone(sentinel.sentinel)
inst = conn._get_current_object()
self.assertEqual(inst.kwargs['is_master'], False)
self.assertEqual(inst.kwargs['service_name'], 'otherslave')
self.assertEqual(inst.kwargs['connection_kwargs']['db'], 6)
self.assertEqual(inst.kwargs['connection_kwargs']['decode_responses'], True)
def test_named_slave_no_sentinel(self):
sentinel = SentinelExtension(client_class=FakeRedis, sentinel_class=FakeSentinel)
self.app.config['REDIS_URL'] = 'redis://hostname:7001/3'
sentinel.init_app(self.app)
conn = sentinel.slave_for('otherslave', db=6)
with self.app.app_context():
self.assertIsNone(sentinel.sentinel._get_current_object())
with self.assertRaisesRegexp(RuntimeError, 'Cannot get slave otherslave using non-sentinel configuration'):
inst = conn._get_current_object()
|
__init__.py | from threading import Event, RLock
class CountdownLatch:
def __init__(self, count):
assert count >= 0
self._lock = RLock()
self._count = count
def dec(self):
with self._lock:
assert self._count > 0
self._count -= 1
# Return inside lock to return the correct value,
# otherwise an other thread could already have
# decremented again.
return self._count
@property
def count(self):
return self._count
class Promise:
"""
This is a class that attempts to comply with the
Promises/A+ specification and test suite:
http://promises-aplus.github.io/promises-spec/
"""
# These are the potential states of a promise
PENDING = -1
REJECTED = 0
FULFILLED = 1
def __init__(self):
"""
Initialize the Promise into a pending state.
"""
self._state = self.PENDING
self._value = None
self._reason = None
self._cb_lock = RLock()
self._callbacks = []
self._errbacks = []
self._event = Event()
@staticmethod
def fulfilled(x):
p = Promise()
p.fulfill(x)
return p
@staticmethod
def rejected(reason):
p = Promise()
p.reject(reason)
return p
def fulfill(self, x):
"""
Fulfill the promise with a given value.
"""
if self is x:
raise TypeError("Cannot resolve promise with itself.")
elif _isPromise(x):
try:
_promisify(x).done(self.fulfill, self.reject)
except Exception as e:
self.reject(e)
else:
self._fulfill(x)
def _fulfill(self, value):
with self._cb_lock:
if self._state != Promise.PENDING:
return
self._value = value
self._state = self.FULFILLED
callbacks = self._callbacks
# We will never call these callbacks again, so allow
# them to be garbage collected. This is important since
# they probably include closures which are binding variables
# that might otherwise be garbage collected.
#
# Prevent future appending
self._callbacks = None
# Notify all waiting
self._event.set()
for callback in callbacks:
try:
callback(value)
except Exception:
# Ignore errors in callbacks
pass
def reject(self, reason):
"""
Reject this promise for a given reason.
"""
assert isinstance(reason, Exception)
with self._cb_lock:
if self._state != Promise.PENDING:
return
self._reason = reason
self._state = self.REJECTED
errbacks = self._errbacks
# We will never call these errbacks again, so allow
# them to be garbage collected. This is important since
# they probably include closures which are binding variables
# that might otherwise be garbage collected.
#
# Prevent future appending
self._errbacks = None
# Notify all waiting
self._event.set()
for errback in errbacks:
try:
errback(reason)
except Exception:
# Ignore errors in errback
pass
@property
def isPending(self):
"""Indicate whether the Promise is still pending. Could be wrong the moment the function returns."""
return self._state == self.PENDING
@property
def isFulfilled(self):
"""Indicate whether the Promise has been fulfilled. Could be wrong the moment the function returns."""
return self._state == self.FULFILLED
@property
def isRejected(self):
"""Indicate whether the Promise has been rejected. Could be wrong the moment the function returns."""
return self._state == self.REJECTED
@property
def value(self):
return self._value
@property
def reason(self):
return self._reason
def get(self, timeout=None):
"""Get the value of the promise, waiting if necessary."""
self.wait(timeout)
if self._state == self.PENDING:
raise ValueError("Value not available, promise is still pending")
elif self._state == self.FULFILLED:
return self._value
else:
raise self._reason
def wait(self, timeout=None):
"""
An implementation of the wait method which doesn't involve
polling but instead utilizes a "real" synchronization
scheme.
"""
self._event.wait(timeout)
def addCallback(self, f):
"""
Add a callback for when this promis is fulfilled. Note that
if you intend to use the value of the promise somehow in
the callback, it is more convenient to use the 'then' method.
"""
assert _isFunction(f)
with self._cb_lock:
if self._state == self.PENDING:
self._callbacks.append(f)
return
# This is a correct performance optimization in case of concurrency.
# State can never change once it is not PENDING anymore and is thus safe to read
# without acquiring the lock.
if self._state == self.FULFILLED:
f(self._value)
else:
pass
def addErrback(self, f):
"""
Add a callback for when this promis is rejected. Note that
if you intend to use the rejection reason of the promise
somehow in the callback, it is more convenient to use
the 'then' method.
"""
assert _isFunction(f)
with self._cb_lock:
if self._state == self.PENDING:
self._errbacks.append(f)
return
# This is a correct performance optimization in case of concurrency.
# State can never change once it is not PENDING anymore and is thus safe to read
# without acquiring the lock.
if self._state == self.REJECTED:
f(self._reason)
else:
pass
def done(self, success=None, failure=None):
"""
This method takes two optional arguments. The first argument
is used if the "self promise" is fulfilled and the other is
used if the "self promise" is rejected. In contrast to then,
the return value of these callback is ignored and nothing is
returned.
"""
with self._cb_lock:
if success is not None:
self.addCallback(success)
if failure is not None:
self.addErrback(failure)
def done_all(self, *handlers):
"""
:type handlers: list[(object) -> object] | list[((object) -> object, (object) -> object)]
"""
if len(handlers) == 0:
return
elif len(handlers) == 1 and isinstance(handlers[0], list):
handlers = handlers[0]
for handler in handlers:
if isinstance(handler, tuple):
s, f = handler
self.done(s, f)
elif isinstance(handler, dict):
s = handler.get('success')
f = handler.get('failure')
self.done(s, f)
else:
self.done(success=handler)
def then(self, success=None, failure=None):
"""
This method takes two optional arguments. The first argument
is used if the "self promise" is fulfilled and the other is
used if the "self promise" is rejected. In either case, this
method returns another promise that effectively represents
the result of either the first of the second argument (in the
case that the "self promise" is fulfilled or rejected,
respectively).
Each argument can be either:
* None - Meaning no action is taken
* A function - which will be called with either the value
of the "self promise" or the reason for rejection of
the "self promise". The function may return:
* A value - which will be used to fulfill the promise
returned by this method.
* A promise - which, when fulfilled or rejected, will
cascade its value or reason to the promise returned
by this method.
* A value - which will be assigned as either the value
or the reason for the promise returned by this method
when the "self promise" is either fulfilled or rejected,
respectively.
:type success: (object) -> object
:type failure: (object) -> object
:rtype : Promise
"""
ret = Promise()
def callAndFulfill(v):
"""
A callback to be invoked if the "self promise"
is fulfilled.
"""
try:
if _isFunction(success):
ret.fulfill(success(v))
else:
ret.fulfill(v)
except Exception as e:
ret.reject(e)
def callAndReject(r):
"""
A callback to be invoked if the "self promise"
is rejected.
"""
try:
if _isFunction(failure):
ret.fulfill(failure(r))
else:
ret.reject(r)
except Exception as e:
ret.reject(e)
self.done(callAndFulfill, callAndReject)
return ret
def then_all(self, *handlers):
"""
Utility function which calls 'then' for each handler provided. Handler can either
be a function in which case it is used as success handler, or a tuple containing
the success and the failure handler, where each of them could be None.
:type handlers: list[(object) -> object] | list[((object) -> object, (object) -> object)]
:param handlers
:rtype : list[Promise]
"""
if len(handlers) == 0:
return []
elif len(handlers) == 1 and isinstance(handlers[0], list):
handlers = handlers[0]
promises = []
for handler in handlers:
if isinstance(handler, tuple):
s, f = handler
promises.append(self.then(s, f))
elif isinstance(handler, dict):
s = handler.get('success')
f = handler.get('failure')
promises.append(self.then(s, f))
else:
promises.append(self.then(success=handler))
return promises
def _isFunction(v):
"""
A utility function to determine if the specified
value is a function.
"""
return v is not None and hasattr(v, "__call__")
def _isPromise(obj):
"""
A utility function to determine if the specified
object is a promise using "duck typing".
"""
return isinstance(obj, Promise) or (
hasattr(obj, "done") and _isFunction(getattr(obj, "done"))) or (
hasattr(obj, "then") and _isFunction(getattr(obj, "then")))
def _promisify(obj):
if isinstance(obj, Promise):
return obj
elif hasattr(obj, "done") and _isFunction(getattr(obj, "done")):
p = Promise()
obj.done(p.fulfill, p.reject)
return p
elif hasattr(obj, "then") and _isFunction(getattr(obj, "then")):
p = Promise()
obj.then(p.fulfill, p.reject)
return p
else:
raise TypeError("Object is not a Promise like object.")
def listPromise(*promises):
"""
A special function that takes a bunch of promises
and turns them into a promise for a vector of values.
In other words, this turns an list of promises for values
into a promise for a list of values.
"""
if len(promises) == 1 and isinstance(promises[0], list):
promises = promises[0]
if len(promises) == 0:
return Promise.fulfilled([])
ret = Promise()
counter = CountdownLatch(len(promises))
def handleSuccess(_):
if counter.dec() == 0:
value = list(map(lambda p: p.value, promises))
ret.fulfill(value)
for p in promises:
assert _isPromise(p)
_promisify(p).done(handleSuccess, ret.reject)
return ret
def dictPromise(m):
"""
A special function that takes a dictionary of promises
and turns them into a promise for a dictionary of values.
In other words, this turns an dictionary of promises for values
into a promise for a dictionary of values.
"""
if len(m) == 0:
return Promise.fulfilled({})
ret = Promise()
counter = CountdownLatch(len(m))
def handleSuccess(_):
if counter.dec() == 0:
value = {}
for k in m:
value[k] = m[k].value
ret.fulfill(value)
for p in m.values():
assert _isPromise(p)
_promisify(p).done(handleSuccess, ret.reject)
return ret
def _process(p, f):
try:
val = f()
p.fulfill(val)
except Exception as e:
p.reject(e)
try:
import gevent
def spawn(f):
p = Promise()
g = gevent.spawn(lambda: _process(p, f))
return p
except ImportError:
pass
if "spawn" not in dir():
try:
import concurrent.futures
executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
def spawn(f):
p = Promise()
executor.submit(_process, p, f)
return p
except ImportError:
pass
if "spawn" not in dir():
from threading import Thread
def spawn(f):
p = Promise()
t = Thread(target=_process, args=(p, f))
t.start()
return p
|
vec_env.py | import redis
import time
import subprocess
# from torch.multiprocessing import Process, Pipe
import multiprocessing as mp
def start_redis():
print('Starting Redis')
subprocess.Popen(['redis-server', '--save', '\"\"', '--appendonly', 'no'])
time.sleep(1)
def start_openie(install_path):
print('Starting OpenIE from', install_path)
subprocess.Popen(['java', '-mx8g', '-cp', '*', \
'edu.stanford.nlp.pipeline.StanfordCoreNLPServer', \
'-port', '8002', '-timeout', '15000', '-quiet'], cwd=install_path)
time.sleep(1)
def worker(remote, parent_remote, env):
parent_remote.close()
env.create()
try:
done = False
while True:
cmd, data = remote.recv()
if cmd == 'step':
if done:
ob, info, graph_info = env.reset()
rew = 0
done = False
remote.send((ob, rew, done, info))
else:
ob, rew, done, info = env.step(data)
# ob, rew, done, info,graph_infos = env.step(data)
remote.send((ob, rew, done, info))
elif cmd == 'graph':
if done:
remote.send((graph_info))
else:
graph_info = env.step_graph(data[0], data[1], data[2], data[3])
remote.send(graph_info)
elif cmd == 'reset':
ob, info, graph_info = env.reset()
remote.send((ob, info, graph_info))
elif cmd == 'close':
env.close()
break
else:
raise NotImplementedError
except KeyboardInterrupt:
print('SubprocVecEnv worker: got KeyboardInterrupt')
finally:
env.close()
class VecEnv:
def __init__(self, num_envs, env, openie_path):
start_redis()
start_openie(openie_path)
self.conn_valid = redis.Redis(host='localhost', port=6379, db=0)
# print(self.conn_valid)
self.closed = False
self.total_steps = 0
self.num_envs = num_envs
self.remotes, self.work_remotes = zip(*[mp.Pipe() for _ in range(num_envs)])
self.ps = [mp.Process(target=worker, args=(work_remote, remote, env))
for (work_remote, remote) in zip(self.work_remotes, self.remotes)]
for p in self.ps:
p.daemon = True # if the main process crashes, we should not cause things to hang
p.start()
for remote in self.work_remotes:
remote.close()
def step(self, actions, obs = None, done = None, make_graph = 0, cs_graph = None, use_cs = False):
if self.total_steps % 1024 == 0:
self.conn_valid.flushdb()
self.total_steps += 1
self._assert_not_closed()
assert len(actions) == self.num_envs, "Error: incorrect number of actions."
idx = 0
for remote, action in (zip(self.remotes, actions)):
if(make_graph == 0):
remote.send(('step', action))
elif(make_graph == 1 and use_cs == False):
remote.send(('graph', [action, obs[idx],done[idx], None]))
elif(make_graph == 1 and use_cs == True):
remote.send(('graph', [action, obs[idx], done[idx],cs_graph[idx]]))
idx += 1
results = [remote.recv() for remote in self.remotes]
self.waiting = False
if(make_graph == 0):
return zip(*results)
else:
return results
def reset(self):
self._assert_not_closed()
for remote in self.remotes:
remote.send(('reset', None))
results = [remote.recv() for remote in self.remotes]
return zip(*results)
def close_extras(self):
self.closed = True
for remote in self.remotes:
remote.send(('close', None))
for p in self.ps:
p.join()
def _assert_not_closed(self):
assert not self.closed, "Trying to operate on a SubprocVecEnv after calling close()"
|
algo_one.py | from functools import reduce
from sys import *
import numpy as np
import random as r
import socket
import struct
import subprocess as sp
import threading
from threading import Thread
import ast
import time
import datetime as dt
import os
import psutil
from netifaces import interfaces, ifaddresses, AF_INET
import paho.mqtt.client as mqtt
import smtplib
import config
import paramiko
# update required not done
hosts = {} # {hostname: ip}
_tasks = {'t1': {'wcet': 3, 'period': 20, 'deadline': 15},
't2': {'wcet': 1, 'period': 5, 'deadline': 4},
't3': {'wcet': 2, 'period': 10, 'deadline': 8},
't4': {'wcet': 1, 'period': 10, 'deadline': 9},
't5': {'wcet': 3, 'period': 15, 'deadline': 12}
}
# mat = {'p0': ['cpu', 'mem', 'storage']}
_need = {
't1': [7, 4, 3],
't2': [1, 2, 2],
't3': [6, 0, 0],
't4': [0, 1, 1],
't5': [4, 3, 1]
}
allocation = {
't1': [0, 1, 0],
't2': [2, 0, 0],
't3': [3, 0, 2],
't4': [2, 1, 1],
't5': [0, 0, 2]
}
_cpu = [] # cpu plot list
prev_t = 0 # variable for cpu util
_off_mec = 0 # used to keep a count of tasks offloaded from local mec to another mec
_off_cloud = 0 # used to keep a count of tasks offloaded to cloud
_loc = 0 # used to keep a count of tasks executed locally
_inward_mec = 0 # used to keep a count of tasks offloaded from another mec to local mec
outward_mec = 0 # keeps count of tasks sent back to another mec after executing
deadlock = [1] # keeps count of how many deadlock is resolved
memory = []
mec_waiting_time = {} # {ip : [moving (waiting time + rtt)]}
mec_rtt = {} # {ip: [RTT]}
offload_register = {} # {task: host_ip} to keep track of tasks sent to mec for offload
reoffload_list = [[], {}] # [[task_list],{wait_time}] => records that’s re-offloaded to mec to execute.
discovering = 0 # if discovering == 0 update host
test = []
_time = []
_pos = 0
received_task_queue = [] # [[(task_list,wait_time), host_ip], ....]
received_time = []
_port_ = 64000
cloud_register = {} # ={client_id:client_ip} keeps address of task offloaded to cloud
cloud_port = 63000
shared_resource_lock = threading.Lock()
t_track = 1
task_record = {} # keeps record of task reoffloaded
task_id = 0 # id for each task reoffloaded
def ping(host):
cmd = [f'ping -c 1 {host}']
output = str(sp.check_output(cmd, shell=True), 'utf-8').split('\n')
try:
value = float(output[-2].split('=')[-1].split('/')[0])
except ValueError:
value = None
return value
def discovering_group():
global sock1
multicast_group = '224.3.29.71'
server_address = ('', 10000)
# Create the socket
sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind to the server address
sock1.bind(server_address)
# Tell the operating system to add the socket to the multicast group
# on all interfaces.
group = socket.inet_aton(multicast_group)
mreq = struct.pack('4sL', group, socket.INADDR_ANY)
sock1.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
def offloading_group():
global sock2
multicast_group = '224.5.5.55'
server_address = ('', 20000)
# Create the socket
sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind to the server address
sock2.bind(server_address)
# Tell the operating system to add the socket to the multicast group
# on all interfaces.
group = socket.inet_aton(multicast_group)
mreq = struct.pack('4sL', group, socket.INADDR_ANY)
sock2.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
def ip_address():
try:
cmd = ['ifconfig eth1 | grep inet | cut -d ":" -f 2 | cut -d " " -f 1']
address = str(sp.check_output(cmd, shell=True), 'utf-8')[0:-1]
if len(address.strip().split('.')) == 4:
return address.strip()
else:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
except Exception as e:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
def _memory():
global memory
memory.append(round(my_algo.memory_percent(), 4))
def m_cpu():
global prev_t
# get cpu
next_t = psutil.cpu_percent(percpu=False)
delta = abs(prev_t - next_t)
prev_t = next_t
_cpu.append(round(delta, 4))
def get_mec_rtts():
for i in mec_rtt:
mec_rtt[i].append(get_rtt(i))
def generate_results():
_memory()
m_cpu()
get_mec_rtts()
def host_ip_set():
global ip_set
ip_set = set()
for ifaceName in interfaces():
addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr': 'No IP addr'}])]
ip_set.add(', '.join(addresses))
def get_time():
_time_ = []
d = str(dt.datetime.utcnow()).split()
_time_ += d[0].split('-')
g = d[1].split('.')
_time_ += g[0].split(':')
_time_.append(g[1])
return _time_
def get_rtt(host):
rtt = ping(host)
if rtt:
return round(rtt, 4)
else:
return get_rtt(host)
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def _lcm(a, b):
return int(a * b / gcd(a, b))
def lcm(_list):
return reduce(_lcm, _list)
def gosh_dist(_range):
return ((23 ** r.randrange(1, 1331)) % r.randrange(1, 1777)) % _range
def on_connect(connect_client, userdata, flags, rc):
# print("Connected with Code :" +str(rc))
# Subscribe Topic from here
connect_client.subscribe(node_id, )
# Callback Function on Receiving the Subscribed Topic/Message
def on_message(message_client, userdata, msg):
global run
data = str(msg.payload, 'utf-8')
if data[0] == 'c': # receive from cloud
received_task = data[2:]
# send_client({received_task: get_time()}, cloud_register[received_task.split('.')[2]])
if received_task in task_record:
del task_record[received_task]
received_task = '.'.join(received_task.split('.')[:-1])
_client.publish(topic=received_task.split('.')[2], payload=str({received_task: get_time() + ['cloud']}), )
cooperate['cloud'] += 1
count_task_sent(received_task)
elif data[0] == 't': # receive from client
received_task = ast.literal_eval(data[2:])
received_task_queue.append(received_task)
received_time.append(time.time())
elif data.strip() == 'stop': # stop {hostname: ip}
print('sending stop alert')
run = 0
def connect_to_broker(stop):
global _client
username = 'mec'
password = 'password'
broker_port_no = 1883
_client = mqtt.Client()
_client.on_connect = on_connect
_client.on_message = on_message
_client.username_pw_set(username, password)
_client.connect(broker_ip, broker_port_no, 60)
_client.loop_start()
while True:
if stop():
_client.loop_stop()
_client.disconnect()
print('broker loop terminated')
break
def task_time_map(seq, process):
exe_seq = []
capacity_sum = 0
for job in process:
capacity_sum += process[job]['wcet']
while capacity_sum > 0:
for job in seq:
if process[job]['wcet'] > 0:
exe_seq.append(job)
process[job]['wcet'] -= 1
capacity_sum -= 1
return exe_seq
def load_tasks():
period_list = [tasks[i]['period'] for i in tasks]
lcm_period = lcm(period_list)
# insert idle task
s_task = {**tasks, 'idle': {'wcet': lcm_period, 'period': lcm_period + 1}}
return lcm_period, s_task
total_received_task = 0
def scheduler(_lcm_, s_tasks): # RMS algorithm
global total_received_task
queue = list(s_tasks.keys()) # initialize task queue
schedule = []
rms = []
curr = '' # current task
prev = '' # previous task
tmp = {}
for task in s_tasks.keys():
tmp[task] = {} # temporary data for each task
tmp[task]['deadline'] = s_tasks[task]['period']
tmp[task]['executed'] = 0
# start scheduling...
# proceed by one timestamp to handle preemption
for _time_ in range(_lcm_):
# insert new tasks into the queue
for t in tmp.keys():
if _time_ == tmp[t]['deadline']:
if s_tasks[t]['wcet'] > tmp[t]['executed']:
# print('Scheduling Failed at %d' % time)
exit(1)
else:
tmp[t]['deadline'] += s_tasks[t]['period']
tmp[t]['executed'] = 0
queue.append(t)
# select next task to be scheduled
_min_ = _lcm_ * 2
for task in queue:
if tmp[task]['deadline'] < _min_:
_min_ = tmp[task]['deadline']
curr = task
tmp[curr]['executed'] += 1
# print(time, queue, curr)
# dequeue the execution-completed task
if tmp[curr]['executed'] == s_tasks[curr]['wcet']:
for i in range(len(queue)):
if curr == queue[i]:
del queue[i]
break
# record to the schedule trace
if prev != curr:
if prev in queue and prev != 'idle': # previous task is preempted..
s = schedule.pop()
schedule.append([s[0], s[1], '*'])
rms.append(s[1])
schedule.append([_time_, curr])
if curr != 'idle':
rms.append(curr)
prev = curr
process = {task: {'wcet': tasks[task]['wcet']} for task in tasks}
rms = task_time_map(seq=rms, process=process)
total_received_task += len(rms)
return rms
# generate execution sequence
def is_safe(processes, avail, _need_, allot, p): # bankers algorithm
need = [_need_[i] for i in _need_]
_allot_ = [allot[i] for i in allot]
# tasks to offload if exit
offload = []
# Number of resources
res = 3
# Mark all processes as unfinished
finish = [0] * p
# To store safe sequence
safe_seq = [0] * p
# Make a copy of available resources
work = [0] * res
for i in range(res):
work[i] = avail[i]
# While all processes are not finished
# or system is not in safe state.
count = 0
while count < p:
# Find a process which is not finish
# and whose needs can be satisfied
# with current work[] resources.
found = False
for t in range(p):
# First check if a process is finished,
# if no, go for next condition
if finish[t] == 0:
# Check if for all resources
# of current P need is less
# than work
for j in range(res):
if need[t][j] > work[j]:
break
# If all needs of p were satisfied.
if j == res - 1:
# Add the allocated resources of
# current P to the available/work
# resources i.e.free the resources
for k in range(res):
work[k] += _allot_[t][k]
# Add this process to safe sequence.
safe_seq[count] = processes[t]
count += 1
# Mark this p as finished
finish[t] = 1
found = True
# If we could not find a next process
# in safe sequence.
if not found:
print("System is not in safe state")
a = list(set(processes) - set(safe_seq) - set(offload))
_max = np.array([0, 0, 0])
n = {}
for i in a:
n[i] = sum(allocation[i[:2]])
_max = max(n, key=n.get)
print('work: ', work, 'need: ', _need[_max[:2]])
offload.append(_max)
work = np.array(work) + np.array(allocation[_max[:2]])
count += 1
# Mark this p as finished
finish[processes.index(_max)] = 1
found = True
# If system is in safe state then
# safe sequence will be as below
if len(offload) > 0:
safe_seq = safe_seq[:safe_seq.index(0)]
print('offloading tasks: ', offload)
cooperative_mec(offload)
deadlock[0] += 1
print("System is in safe state.",
"\nSafe sequence is: ", end=" ")
print('safe seq: ', safe_seq)
return safe_seq
def get_exec_seq(pro):
# Number of processes
p = len(pro)
processes = ['{}_{}'.format(pro[i], i) for i in range(len(pro))]
# Available instances of resources
avail = [6, 5, 5]
n_need = {i: _need[i[:2]] for i in processes}
# print('need', n_need)
# Resources allocated to processes
allot = {i: allocation[i[:2]] for i in processes}
# return execution sequence
return is_safe(processes, avail, n_need, allot, p)
def calc_wait_time(list_seq):
pre = 0
time_dic = {}
for i in list_seq:
j = i.split('_')[0]
time_dic[i] = round(t_time[j][0] + pre, 3)
pre += t_time[j][0]
# waiting time = total waiting time ÷ 2 average waiting time might be too tight
w_send = round(time_dic[list(time_dic.keys())[-1]] / 2, 3)
send_message('wt {} {}'.format(ip_address(), str(w_send))) # Broadcasting waiting time to cooperative MECs
return time_dic
timed_out_tasks = 0
def compare_local_mec(list_seq):
global received_time, timed_out_tasks
execute_mec = []
execute_locally = []
diff = time.time() - received_time.pop(0)
checking_times = {}
for i in list_seq:
t_time[i.split('_')[0]][1] -= diff
# if t_time[i.split('_')[0]][1] < 0:
# _client.publish(i.split('_')[0].split('.')[2], str({i.split('_')[0]: get_time() + ['local']}), )
# timed_out_tasks += 1
if t_time[i.split('_')[0]][1] > list_seq[i]:
execute_locally.append(i)
else:
execute_mec.append(i)
checking_times[i] = {'Latency': t_time[i.split('_')[0]][1], 'Expected_exec_time': list_seq[i]}
print('Execution time comparison:= ', checking_times)
return execute_mec, execute_locally
def calculate_mov_avg(ma1, a1):
if ma1 in mec_waiting_time:
_count = len(mec_waiting_time[ma1])
avg1 = mec_waiting_time[ma1][-1]
else:
_count = 0
avg1 = 0
_count += 1
avg1 = ((_count - 1) * avg1 + a1) / _count
# ma1.append(avg1) #cumulative average formula
# μ_n=((n-1) μ_(n-1) + x_n)/n
return round(avg1, 4)
def send_message(mg):
_multicast_group = ('224.3.29.71', 10000)
try:
# Send data to the multicast group
if mg == 'hello':
smg = mg + ' ' + str([get_hostname(), ip_address()])
sock1.sendto(str.encode(smg), _multicast_group)
print('\nHello message sent')
else:
sock1.sendto(str.encode(mg), _multicast_group)
except Exception as e:
print(e)
def get_hostname():
cmd = ['cat /etc/hostname']
hostname = str(sp.check_output(cmd, shell=True), 'utf-8')[0:-1]
return hostname
def receive_message(stop): # used for multi-cast message exchange among MEC
global hosts
while True:
if stop():
print('Stopped: receive_message()')
break
else:
data, address = sock1.recvfrom(1024)
_d = data.decode()
if _d[:5] == 'hello':
_data = ast.literal_eval(_d[6:])
hosts[_data[0]] = _data[1]
# print('received: ', hosts)
if _data[1] != host_ip:
mec_rtt[_data[1]] = []
elif (_d[:6] == 'update') and (discovering == 0):
hosts = ast.literal_eval(_d[7:])
# print('received: ', hosts)
for i in hosts:
if i != host_ip:
mec_rtt[i] = []
elif _d[:2] == 'wt':
split_data = _d.split()
if split_data[1] != host_ip:
w_time = calculate_mov_avg(split_data[1], float(split_data[2]) + get_rtt(
address[0])) # calcuate moving average of mec wait time => w_time = wait time + rtt
if split_data[1] in mec_waiting_time:
mec_waiting_time[split_data[1]].append(w_time)
else:
mec_waiting_time[split_data[1]] = [w_time]
def mec_comparison():
# returns min average waiting for all mecs
if len(mec_waiting_time) == 0:
return 0
min_mec = {i: mec_waiting_time[i][-1] for i in mec_waiting_time}
min_wt = min(min_mec, key=min_mec.get)
return min_wt
def cooperative_mec(mec_list):
global _off_cloud
global _off_mec
global task_id, task_record
for i in mec_list:
_host = mec_comparison()
if _host == 0:
# send_cloud([i.split('_')[0], t_time[i.split('_')[0]][0]]) # [task_id,exec_time]
_send_task = f"{i.split('_')[0]}.{task_id}"
_client.publish(cloud_ip, str([_send_task, t_time[i.split('_')[0]][0]]), )
task_record[_send_task] = 'cloud'
task_id += 1
_off_cloud += 1
# cloud_register[i.split('_')[0].split('.')[2]] = send_back_host
print('\n=========SENDING {} TO CLOUD==========='.format(i))
else:
j = i.split('_')[0]
_max = np.array([6, 5, 5])
send = 'false'
if not (False in list(np.greater_equal(_max, _need[j[:2]]))):
send = 'true'
# CHECK IF THE MINIMUM MEC WAIT TIME IS LESS THAN LATENCY
if mec_waiting_time[_host][-1] < t_time[j][1] and send == 'true':
_send_task = f"{j}.{task_id}"
send_offloaded_task_mec('{} {} {}'.format('ex', mec_id(_host), [_send_task, t_time[j][0]]))
task_record[_send_task] = 'mec'
task_id += 1
_off_mec += 1
# SENDS TASK TO MEC FOR EXECUTION
w_send = mec_waiting_time[_host][-1] + 0.001
mec_waiting_time[_host].append(w_send) # adds a new average waiting time
print('\n======SENDING {} TO MEC {}========='.format(i, _host))
elif send == 'true' and (get_rtt(_host) < get_rtt(cloud_ip)):
_send_task = f"{j}.{task_id}"
send_offloaded_task_mec('{} {} {}'.format('ex', mec_id(_host), [_send_task, t_time[j][0]]))
task_record[_send_task] = 'mec'
task_id += 1
_off_mec += 1
# SENDS TASK TO MEC FOR EXECUTION
w_send = mec_waiting_time[_host][-1] + 0.001
mec_waiting_time[_host].append(w_send) # adds a new average waiting time
print('\n======SENDING {} TO MEC {}========='.format(i, _host))
else:
_send_task = f"{j}.{task_id}"
_client.publish(cloud_ip, str([_send_task, t_time[j][0]]), )
task_record[_send_task] = 'cloud'
task_id += 1
_off_cloud += 1
# send_cloud([j, t_time[j][0]]) # # [task_id,exec_time]
# cloud_register[j.split('.')[2]] = send_back_host
print('\n=========SENDING {} TO CLOUD==========='.format(i))
offload_check = [0, 0]
def execute_re_offloaded_task(offloaded_task):
global outward_mec, offload_check
exec_list = get_exec_seq(offloaded_task[0])
# if len(exec_list) != len(offloaded_task[0]):
# print('\n\n', '@ ' * 50)
# print('exec: ', exec_list, 'off: ', offloaded_task[0])
# print('\n\n', '@ ' * 50)
# offload_check.append((exec_list, offloaded_task[0]))
outward_mec += len(exec_list)
for i in offloaded_task[0]: # i = 't1.1.2.3*1_3'
j = i.split('_')[0]
time.sleep(offloaded_task[1][j] / 2)
# print('j task: ', j)
send_offloaded_task_mec('{} {}'.format(j.split('.')[1], i.split('*')[0]))
clients_record = {}
def count_task_sent(task):
global clients_record
c_id = task.split('.')[2]
if c_id in clients_record:
clients_record[c_id] += 1
else:
clients_record[c_id] = 1
def execute(local):
print('\nExecuting :', local)
for i in local:
j = i.split('_')[0]
_t = t_time[j][0] / 2
time.sleep(_t)
print('#{}'.format(local.index(i) + 1), ' Executed: ', i)
_client.publish(j.split('.')[2], str({j: get_time() + ['local']}), )
count_task_sent(j)
# if j.split('.')[1] != node_id:
# send_offloaded_task_mec('{} {}'.format(j.split('.')[1], j))
# outward_mec += 1
# elif j.split('.')[1] == node_id:
# # send_client({j: get_time()}, send_back_host)
# _client.publish(j.split('.')[2], str({j: get_time() + ['local']}), )
# count_task_sent(j)
# else:
# print('else execute: ', j)
print('============== EXECUTION DONE ===============')
cooperate = {'mec': 0, 'cloud': 0}
def receive_offloaded_task_mec(stop): # run as a thread
global _inward_mec
global t_track
while True:
if stop():
print('Stopped: receive_offloaded_task_mec()')
break
else:
data, address = sock2.recvfrom(1024)
if len(data.decode()) > 0:
da = data.decode().split(' ')
if (address[0] not in ip_set) and (da[0] == node_id): # send back to client
# send_client({da[1]: get_time()}, offload_register[da[1]]) # send back to client
if da[1] in task_record:
del task_record[da[1]]
task_new = '.'.join(da[1].split('.')[:-1])
_client.publish(da[1].split('.')[2], str({task_new: get_time() + ['mec']}), )
count_task_sent(da[1])
cooperate['mec'] += 1
else:
print('*' * 30 + f'\n{da[1]} Not in Task Record\n' + '*' * 30)
elif (address[0] not in ip_set) and (da[0] == 'ex') and (da[1] == node_id):
_received = ast.literal_eval(da[2] + da[3])
shared_resource_lock.acquire()
task = _received[0] + '*{}'.format(t_track)
reoffload_list[0].append(task)
reoffload_list[1][task] = _received[1]
shared_resource_lock.release()
t_track += 1
_inward_mec += 1
def call_execute_re_offload(stop):
global reoffload_list, outward_mec
global offload_check
while True:
if stop():
print('Stopped: call_execute_re_offload()')
break
else:
if len(reoffload_list[0]) == 1:
t = reoffload_list[0][-1]
time.sleep(reoffload_list[1][t] / 2)
shared_resource_lock.acquire()
reoffload_list[0].remove(t)
del reoffload_list[1][t]
shared_resource_lock.release()
send_offloaded_task_mec('{} {}'.format(t.split('.')[1], t.split('*')[0]))
offload_check[0] += 1
outward_mec += 1
elif len(reoffload_list[0]) > 1:
o = reoffload_list.copy()
offload_check[1] += len(o)
execute_re_offloaded_task(o)
for i in o[0]:
shared_resource_lock.acquire()
reoffload_list[0].remove(i)
del reoffload_list[1][i]
shared_resource_lock.release()
def send_email(msg, send_path):
try:
server = smtplib.SMTP_SSL('smtp.gmail.com')
server.ehlo()
server.login(config.email_address, config.password)
subject = 'Deadlock results rms+bankers {} {}'.format(get_hostname(), send_path)
# msg = 'Attendance done for {}'.format(_timer)
_message = 'Subject: {}\n\n{}\n\n SENT BY RIHANNA \n\n'.format(subject, msg)
server.sendmail(config.email_address, config.send_email, _message)
server.quit()
print("Email sent!")
except Exception as e:
print(e)
def send_offloaded_task_mec(msg):
_multicast_group = ('224.5.5.55', 20000)
try:
sock2.sendto(str.encode(msg), _multicast_group)
except Exception as e:
print(e)
def send_result(host_, data):
try:
c = paramiko.SSHClient()
un = 'mec'
pw = 'password'
port = 22
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(host_, port, un, pw)
for i in data:
cmd = ('echo "{}" >> /home/mec/result/data.py'.format(i)) # task share : host ip task
stdin, stdout, stderr = c.exec_command(cmd)
c.close()
except Exception as e:
print(e)
def mec_id(client_ip):
_id = client_ip.split('.')[-1]
if len(_id) == 1:
return '00' + _id
elif len(_id) == 2:
return '0' + _id
else:
return _id
def save_and_send(send_path):
_id_ = get_hostname()[-1]
result = f"\nwt{_id_}_2_{mec_no} = {mec_waiting_time} " \
f"\nrtt{_id_}_2_{mec_no} = {mec_rtt} \ncpu{_id_}_2_{mec_no} = {_cpu} " \
f"\noff_mec{_id_}_2_{mec_no} = {_off_mec} " \
f"\noff_cloud{_id_}_2_{mec_no} = {_off_cloud} " \
f"\ninward_mec{_id_}_2_{mec_no} = {_inward_mec}" \
f"\nloc{_id_}_2_{mec_no} = {_loc} " \
f"\ndeadlock{_id_}_2_{mec_no} = {deadlock} \nmemory{_id_}_2_{mec_no} = {memory}" \
f"\ntask_received{_id_}_2_{mec_no} = {total_received_task} \nsent_t{_id_}_2_{mec_no} = {clients_record}" \
f"\ncooperate{_id_}_2_{mec_no} = {cooperate} \ntask_record{_id_}_2_{mec_no} = {task_record}" \
f"\noutward_mec{_id_}_2_{mec_no} = {outward_mec}" \
f"\noffload_check{_id_}_2_{mec_no} = {offload_check}\n" \
f"\ntimed_out_tasks{_id_}_2_{mec_no} = {timed_out_tasks}\n"
list_result = [
f"\nwt{_id_}_2_{mec_no} = {mec_waiting_time} ",
f"\nrtt{_id_}_2_{mec_no} = {mec_rtt} \ncpu{_id_}_2_{mec_no} = {_cpu} ",
f"\noff_mec{_id_}_2_{mec_no} = {_off_mec} \noff_cloud{_id_}_2_{mec_no} = {_off_cloud} ",
f"\ninward_mec{_id_}_2_{mec_no} = {_inward_mec}",
f"\nloc{_id_}_2_{mec_no} = {_loc} ",
f"\ndeadlock{_id_}_2_{mec_no} = {deadlock} \nmemory{_id_}_2_{mec_no} = {memory}",
f"\ntask_received{_id_}_2_{mec_no} = {total_received_task} \nsent_t{_id_}_2_{mec_no} = {clients_record}",
f"\ncooperate{_id_}_2_{mec_no} = {cooperate} \ntask_record{_id_}_2_{mec_no} = {task_record} "
f"\noutward_mec{_id_}_2_{mec_no} = {outward_mec}",
f"\noffload_check{_id_}_2_{mec_no} = {offload_check}"
f"\ntimed_out_tasks{_id_}_2_{mec_no} = {timed_out_tasks}"
]
path_ = 'data/raw/'
if os.path.exists(path_):
cmd = f"echo '' > {path_}{_id_}_2_{mec_no}datal.py"
os.system(cmd)
cmd = f"echo '' > {path_}{_id_}_2_{mec_no}datap.py"
os.system(cmd)
else:
os.mkdir(path_)
cmd = f"echo '' > {path_}{_id_}_2_{mec_no}datal.py"
os.system(cmd)
cmd = f"echo '' > {path_}{_id_}_2_{mec_no}datap.py"
os.system(cmd)
file_ = open(f'{path_}{_id_}_2_{mec_no}datap.py', 'w')
for i in list_result:
cmd = f'echo "{i}" >> {path_}{_id_}_2_{mec_no}datal.py'
file_.write(i)
os.system(cmd)
file_.close()
sp.run(
["scp", f"{path_}{_id_}_2_{mec_no}datap.py", f"mec@{hosts['osboxes-0']}:{send_path}"])
send_result(hosts['osboxes-0'], list_result)
send_email(result, send_path)
if len(task_record) > 0:
for _task_ in task_record:
task_new = '.'.join(_task_.split('.')[:-1])
_client.publish(task_new.split('.')[2], str({task_new: get_time() + [task_record[_task_]]}), )
def terminate_process():
global prev_t, _loc, _off_mec, _off_cloud, _inward_mec, outward_mec, deadlock, memory, mec_waiting_time, mec_rtt
global offload_register, reoffload_list, discovering, test, _time, _pos, received_task_queue, received_time
global cloud_register, t_track, task_record, task_id, cooperate, clients_record, offload_check
global timed_out_tasks, total_received_task, _cpu
# reinitialize #
_cpu = [] # cpu plot list
prev_t = 0 # variable for cpu util
_off_mec = 0 # used to keep a count of tasks offloaded from local mec to another mec
_off_cloud = 0 # used to keep a count of tasks offloaded to cloud
_loc = 0 # used to keep a count of tasks executed locally
_inward_mec = 0 # used to keep a count of tasks offloaded from another mec to local mec
outward_mec = 0 # keeps count of tasks sent back to another mec after executing
deadlock = [1] # keeps count of how many deadlock is resolved
memory = []
mec_waiting_time = {} # {ip : [moving (waiting time + rtt)]}
mec_rtt = {} # {ip: [RTT]}
offload_register = {} # {task: host_ip} to keep track of tasks sent to mec for offload
reoffload_list = [[], {}] # [[task_list],{wait_time}] => records that’s re-offloaded to mec to execute.
discovering = 0 # if discovering == 0 update host
test = []
_time = []
_pos = 0
received_task_queue = [] # [[(task_list,wait_time), host_ip], ....]
received_time = []
cloud_register = {} # ={client_id:client_ip} keeps address of task offloaded to cloud
t_track = 1
task_record = {} # keeps record of task reoffloaded
task_id = 0 # id for each task reoffloaded
cooperate = {'mec': 0, 'cloud': 0}
clients_record = {}
offload_check = [0, 0]
timed_out_tasks = 0
total_received_task = 0
time.sleep(1)
run = 1 # tell agents child when to stop
def start_loop():
global _loc
global tasks
global t_time
global node_id
global run
print('\n============* WELCOME TO THE DEADLOCK EMULATION PROGRAM *=============\n')
node_id = mec_id(ip_address())
# print('node id: ', node_id)
func_to_thread = [receive_message, receive_offloaded_task_mec, call_execute_re_offload, connect_to_broker]
threads_ = []
stop = False
for i in func_to_thread:
threads_.append(Thread(target=i, args=(lambda: stop,)))
threads_[-1].daemon = True
threads_[-1].start()
print('algorithm is starting....')
print('========= Waiting for tasks ==========')
while run == 1:
try:
if len(received_task_queue) > 0:
info = received_task_queue.pop(0)
tasks, t_time = info
print('RMS List of Processes: ', tasks, '\n')
print('\n========= Running Deadlock Algorithm ===========')
lcm_result, task_load = load_tasks()
list_seq = get_exec_seq(scheduler(lcm_result, task_load))
if len(list_seq) > 0: # do only when there is a task in safe sequence
wait_list = calc_wait_time(list_seq)
print('\nWaiting Time List: ', wait_list)
compare_result = compare_local_mec(wait_list)
print('\nExecute Locally: ', compare_result[1])
_loc += len(compare_result[1]) # total number of tasks to be executed locally
print('\nExecute in MEC: ', compare_result[0])
if len(compare_result[0]) > 0:
print('\nSending to cooperative platform')
cooperative_mec(compare_result[0])
execute(compare_result[1])
generate_results()
else:
send_message(str('wt {} 0.0'.format(ip_address())))
time.sleep(0.4)
except KeyboardInterrupt:
print('\nProgramme Terminated')
stop = False
for th in threads_:
th.join()
time.sleep(1)
print('done')
# os.system('kill -9 {}'.format(os.getpid()))
break
print('algo stopped!')
run = 1
stop = True
time.sleep(20)
for th in threads_:
th.join()
def run_me(hosts_, mec_no_, cloud_ip_, send_path, broker_ip_): # call this from agent
global discovering
global hosts
global mec_no
global host_ip
global cloud_ip
global my_algo
global broker_ip
print('mec ip: ', ip_address())
my_algo = psutil.Process()
discovering_group()
offloading_group()
host_ip_set()
hosts = hosts_
mec_no = mec_no_
cloud_ip = cloud_ip_
broker_ip = broker_ip_
host_ip = ip_address()
print('MEC Details: ', hosts)
discovering = 1
time.sleep(2)
for host in hosts:
if hosts[host] != host_ip:
mec_rtt[hosts[host]] = []
start_loop()
print('saving data')
save_and_send(send_path)
print('Terminating process')
terminate_process()
|
includes.py | import json
import os
import random
import sys
import time
from multiprocessing import Process, Pipe
import threading
import redis
from numpy.random import default_rng
import numpy as np
from skimage.io import imread
from skimage.transform import resize
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../opt/readies"))
import paella
ROOT = os.environ.get("ROOT", None)
TESTMOD_PATH = os.environ.get("TESTMOD", None)
MAX_ITERATIONS = 2 if os.environ.get("MAX_ITERATIONS") == None else os.environ.get("MAX_ITERATIONS")
TEST_TF = os.environ.get("TEST_TF") != "0" and os.environ.get("WITH_TF") != "0"
TEST_TFLITE = os.environ.get("TEST_TFLITE") != "0" and os.environ.get("WITH_TFLITE") != "0"
TEST_PT = os.environ.get("TEST_PT") != "0" and os.environ.get("WITH_PT") != "0"
TEST_ONNX = os.environ.get("TEST_ONNX") != "0" and os.environ.get("WITH_ORT") != "0"
COV = os.environ.get("COV") != "0" and os.environ.get("COV") != "0"
DEVICE = os.environ.get('DEVICE', 'CPU').upper().encode('utf-8', 'ignore').decode('utf-8')
print(f'\nRunning inference sessions on {DEVICE}\n')
VALGRIND = os.environ.get("VALGRIND") == "1"
# change this to make inference tests longer
MAX_TRANSACTIONS=100
def get_connection(env, routing_hint):
return env.getConnectionByKey(routing_hint, 'SET')
# returns the test name and line number from which a helper function within this file was called.
# For example, if an assertion fails in check_error_message function, and the caller function to check_error_message
# is in tests_onnx.py line 25, this should return: "tests_onnx:py:25"
def get_caller_pos():
return f'{sys._getframe(2).f_code.co_filename.split("/")[-1]}:{sys._getframe(2).f_lineno}'
def ensureSlaveSynced(con, env, timeout_ms=0):
if env.useSlaves:
# When WAIT returns, all the previous write commands
# sent in the context of the current connection are
# guaranteed to be received by the number of replicas returned by WAIT.
wait_reply = con.execute_command('WAIT', '1', timeout_ms)
try:
number_replicas = int(wait_reply)
except Exception as ex:
# Error in converting to int
env.debugPring(str(ex), force=True)
env.assertFalse(True, message=get_caller_pos())
return
env.assertEqual(number_replicas, 1)
# Ensures command is sent and forced disconnect
# after without waiting for the reply to be parsed
# Usefull for checking behaviour of commands
# that are run with background threads
def send_and_disconnect(cmd, red):
pool = red.connection_pool
con = pool.get_connection(cmd[0])
ret = con.send_command(*cmd)
con.disconnect()
# For making sure that Redis will have the time to exit cleanly.
time.sleep(1)
return ret
def check_cuda():
return os.system('which nvcc')
def info_to_dict(info):
info = [el.decode('utf-8') if type(el) is bytes else el for el in info]
return dict(zip(info[::2], info[1::2]))
def load_resnet_test_data():
test_data_path = os.path.join(os.path.dirname(__file__), 'test_data/imagenet')
labels_filename = os.path.join(test_data_path, 'imagenet_class_index.json')
image_filename = os.path.join(test_data_path, 'dog.jpg')
model_filename = os.path.join(test_data_path, 'resnet50.pb')
script_filename = os.path.join(test_data_path, 'data_processing_script.txt')
with open(script_filename, 'rb') as f:
script = f.read()
with open(model_filename, 'rb') as f:
model_pb = f.read()
with open(labels_filename, 'r') as f:
labels = json.load(f)
img_height, img_width = 224, 224
img = imread(image_filename)
img = resize(img, (img_height, img_width), mode='constant', anti_aliasing=True)
img = img.astype(np.uint8)
return model_pb, script, labels, img
def load_resnet_test_data_old():
test_data_path = os.path.join(os.path.dirname(__file__), 'test_data/imagenet')
labels_filename = os.path.join(test_data_path, 'imagenet_class_index.json')
image_filename = os.path.join(test_data_path, 'dog.jpg')
model_filename = os.path.join(test_data_path, 'resnet50.pb')
script_filename = os.path.join(test_data_path, 'data_processing_script_old.txt')
with open(script_filename, 'rb') as f:
script = f.read()
with open(model_filename, 'rb') as f:
model_pb = f.read()
with open(labels_filename, 'r') as f:
labels = json.load(f)
img_height, img_width = 224, 224
img = imread(image_filename)
img = resize(img, (img_height, img_width), mode='constant', anti_aliasing=True)
img = img.astype(np.uint8)
return model_pb, script, labels, img
def load_mobilenet_v1_test_data():
test_data_path = os.path.join(os.path.dirname(__file__), 'test_data')
labels_filename = os.path.join(test_data_path, 'imagenet_class_index.json')
image_filename = os.path.join(test_data_path, 'panda.jpg')
model_filename = os.path.join(test_data_path, 'mobilenet/mobilenet_v1_100_224_cpu_NxHxWxC.pb')
input_var = 'input'
output_var = 'MobilenetV1/Predictions/Reshape_1'
with open(model_filename, 'rb') as f:
model_pb = f.read()
with open(labels_filename, 'r') as f:
labels = json.load(f)
img_height, img_width = 224, 224
img = imread(image_filename)
img = resize(img, (img_height, img_width), mode='constant', anti_aliasing=True)
img = img.astype(np.float32)
return model_pb, input_var, output_var, labels, img
def load_mobilenet_v2_test_data():
test_data_path = os.path.join(os.path.dirname(__file__), 'test_data')
labels_filename = os.path.join(test_data_path, 'imagenet_class_index.json')
image_filename = os.path.join(test_data_path, 'panda.jpg')
model_filename = os.path.join(test_data_path, 'mobilenet/mobilenet_v2_1.4_224_frozen.pb')
input_var = 'input'
output_var = 'MobilenetV2/Predictions/Reshape_1'
with open(model_filename, 'rb') as f:
model_pb = f.read()
with open(labels_filename, 'r') as f:
labels = json.load(f)
img_height, img_width = 224, 224
img = imread(image_filename)
img = resize(img, (img_height, img_width), mode='constant', anti_aliasing=True)
img = img.astype(np.float32)
return model_pb, input_var, output_var, labels, img
def load_creditcardfraud_data(env,max_tensors=10000):
test_data_path = os.path.join(os.path.dirname(__file__), 'test_data')
model_filename = os.path.join(test_data_path, 'creditcardfraud.pb')
creditcard_transaction_filename = os.path.join(test_data_path, 'creditcard_10K.csv')
rg = default_rng()
creditcard_transactions = np.genfromtxt(creditcard_transaction_filename, delimiter=',', dtype='float32', skip_header=1, usecols=range(0,30))
creditcard_referencedata = []
for tr in range(0,max_tensors):
creditcard_referencedata.append(rg.random((1,256), dtype='float32'))
with open(model_filename, 'rb') as f:
model_pb = f.read()
return model_pb, creditcard_transactions, creditcard_referencedata
def run_mobilenet(con, i, img, input_var, output_var):
time.sleep(0.5 * random.randint(0, 10))
con.execute_command('AI.TENSORSET', 'input{1}',
'FLOAT', 1, img.shape[1], img.shape[0], img.shape[2],
'BLOB', img.tobytes())
con.execute_command('AI.MODELEXECUTE', 'mobilenet{1}',
'INPUTS', 1, 'input{1}', 'OUTPUTS', 1, 'output{1}')
def run_test_multiproc(env, routing_hint, n_procs, fn, args=tuple()):
procs = []
def tmpfn(i):
con = get_connection(env, routing_hint)
fn(con, i, *args)
return 1
for i in range(n_procs):
p = Process(target=tmpfn, args=(i, ))
p.start()
procs.append(p)
[p.join() for p in procs]
def get_parent_children_pipes(num_children):
parent_end_pipes = []
children_end_pipes = []
# Create a pipe for every child process, so it can report number of successful runs.
for i in range(num_children):
parent_pipe, child_pipe = Pipe()
parent_end_pipes.append(parent_pipe)
children_end_pipes.append(child_pipe)
return parent_end_pipes, children_end_pipes
# Load a model/script from a file located in test_data dir.
def load_file_content(file_name):
test_data_path = os.path.join(os.path.dirname(__file__), 'test_data')
filename = os.path.join(test_data_path, file_name)
with open(filename, 'rb') as f:
return f.read()
def check_error_message(env, con, error_msg, *command, error_msg_is_substr=False, error_type=redis.exceptions.ResponseError):
try:
con.execute_command(*command)
env.assertFalse(True, message=get_caller_pos())
except Exception as exception:
env.assertEqual(type(exception), error_type, message=get_caller_pos())
if error_msg_is_substr:
# We only verify that the given error_msg is a substring of the entire error message.
env.assertTrue(str(exception).find(error_msg) >= 0, message=get_caller_pos())
else:
env.assertEqual(error_msg, str(exception), message=get_caller_pos())
def check_error(env, con, *command, error_type=redis.exceptions.ResponseError):
try:
con.execute_command(*command)
env.assertFalse(True, message=get_caller_pos())
except Exception as e:
exception = e
env.assertTrue(issubclass(type(exception), error_type), message=get_caller_pos())
# Returns a dict with all the fields of a certain section from INFO MODULES command
def get_info_section(con, section):
sections = ['ai_versions', 'ai_git', 'ai_load_time_configs', 'ai_backends_info', 'ai_cpu']
section_ind = [i for i in range(len(sections)) if sections[i] == 'ai_'+section][0]
return {k.split(":")[0]: k.split(":")[1]
for k in con.execute_command("INFO MODULES").decode().split("#")[section_ind+2].split()[1:]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.