import threading
import time
import inspect
import ctypes
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
def synchronized(func):
func.__lock__ = threading.Lock()
def synced_func(*args, **kws):
with func.__lock__:
return func(*args, **kws)
return synced_func
def Singleton(cls):
_instance = {}
@synchronized
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@Singleton
class MyThread(threading.Thread):
def run(self):
for i in range(1):
time.sleep(1)
msg = "I'm " + self.name + ' @ ' + str(i) # name属性中保存的是当前线程的名字
print(msg)
try:
if self._target:
self._target(*self._args, **self._kwargs)
finally:
# Avoid a refcycle if the thread is running a function with
# an argument that has a member that points to the thread.
del self._target, self._args, self._kwargs
def Bar(a):
print("Bar...")
time.sleep(3)
print(a)
for i in range(5):
t1 = MyThread(target=Bar, args=(23,))
print(t1.isAlive)
if t1.is_alive():
print('stop')
stop_thread(t1)
else:
try:
t1.start()
except Exception:
print('pass')
print(t1.is_alive(),'---------')
pass
print(t1.isAlive)
print(t1.is_alive(), 't1')
print(id(t1),'t1')
t1 = MyThread(target=Bar, args=(4,))
if t1.is_alive():
print('stop')
stop_thread(t1)
print(t1.is_alive(), 't2')
print(id(t1),'t2')
length = len(threading.enumerate())
print('当前运行的线程数为:%d' % length)
time.sleep(2)
import threading
import time
import multiprocessing
import inspect
import ctypes
import json
from queue import Queue
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
# -*- coding:utf-8 -*-
# from __future__ import unicode_literals
import threading
def Singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
def web_socket1():
for i in range(5):
print(i)
time.sleep(6)
@Singleton
class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg = "I'm " + self.name + ' @ ' + str(i) # name属性中保存的是当前线程的名字
print(msg)
def web_socket():
t1 = MyThread(target=web_socket1)
for message in range(5):
print('index', message)
if message:
if message % 2 == 0:
msg = {'itsm_id': '123', 'status': 'success'}
else:
msg = {}
if msg.get('itsm_id'):
if msg.get('msg') == 'pitpat':
pass
if msg.get('_id'):
pass
else:
pass
if msg.get('status') == 'success':
state = None
if state:
pass
else:
if t1.is_alive():
print('55 line stop')
stop_thread(t1)
t1 = MyThread(target=web_socket1)
t1.start()
# time.sleep(15)
# continue
elif msg.get('status') == 'failing':
pass
elif msg.get('msg') == 'pitpat':
continue
elif msg.get('msg') == 'connection over':
if t1.is_alive():
print('stop')
stop_thread(t1)
else:
if t1.is_alive():
print('stop')
stop_thread(t1)
continue
length = len(threading.enumerate())
print('当前运行的线程数为:%d' % length)
time.sleep(2)
web_socket()
print('end')
@accept_websocket
def web_socket(request):
if not request.is_websocket(): # 判断是不是websocket连接
return Response({
'status': 'failing',
'message': str(),
'data': {},
}, http_status.HTTP_500_INTERNAL_SERVER_ERROR)
else:
data = {}
for message in request.websocket:
logger.info('websocket params %s' % message)
# print('*' * 30)
# print(message)
try:
if message:
msg = json.loads(message.decode())
if msg.get('itsm_id'):
logger.info('websocket params %s' % msg)
# print('*' * 30)
while True:
if msg.get('msg') == 'pitpat':
request.websocket.send(json.dumps({"msg": "pitpat"}).encode())
break
if msg.get('_id'):
service_obj = ServiceInstance.objects.get(itsm_id=msg['itsm_id'])
opr = ''
if service_obj.status == '2':
opr = 'execute'
elif service_obj.status == '3':
opr = 'rollback'
else:
break
data_log = copy.deepcopy(data)
if msg.get('task'):
plan_type = msg.get('task')
else:
plan = requests.get(
settings.APP_BACKEND['change_record'] + 'plan?itsm_change_id=%s' % msg[
'itsm_id']).json()
plan_type = plan['data']['plans'][0]['type']
ret = detail_data_log(data_log, opr, plan_type, msg['group_key'], msg['task_key'],
msg['_id'])
data = ret['data']
request.websocket.send(json.dumps(data).encode())
else:
ret = requests.get(
settings.APP_BACKEND['dorado_service'] + 'flow_detail?itsm_id=' + msg[
'itsm_id']).json()
data = ret['data']
if ret.get('status') == 'success':
state = None
for k, v in data.items():
if data[k]['flow_state'] == 'SUCCESS' or data[k]['flow_state'] == 'ERROR':
logger.info('flow_done')
state = True
break
if state:
request.websocket.send(json.dumps(data).encode())
break
else:
logger.info(data)
request.websocket.send(json.dumps(data).encode())
time.sleep(15)
continue
# break
elif ret.get('status') == 'failing':
request.websocket.send(json.dumps(ret).encode())
break
elif msg.get('msg') == 'pitpat':
request.websocket.send(json.dumps({"msg": "pitpat"}).encode())
continue
elif msg.get('msg') == 'connection over':
request.websocket.send(json.dumps({"msg": "close"}).encode())
else:
continue
else:
logger.info('websocke connection succeeded')
request.websocket.send(json.dumps({"msg": "success"}).encode())
except Exception as e:
logger.exception('dorado_service exec error' + ERROR_MSG_DELIMITER +
str(e))
request.websocket.send(json.dumps({"msg": "error"}).encode())
def detail_while(request, msg, data):
while True:
if msg.get('msg') == 'pitpat':
request.websocket.send(json.dumps({"msg": "pitpat"}).encode())
break
if msg.get('_id'):
service_obj = ServiceInstance.objects.get(itsm_id=msg['itsm_id'])
opr = ''
if service_obj.status == '2':
opr = 'execute'
elif service_obj.status == '3':
opr = 'rollback'
else:
break
data_log = copy.deepcopy(data)
plan = requests.get(
settings.APP_BACKEND['change_record'] + 'plan?itsm_change_id=%s' % msg[
'itsm_id']).json()
type = plan['data']['plans'][0]['type']
plan_type = msg.get('task', type)
ret = detail_data_log(data_log, opr, plan_type, msg['group_key'], msg['task_key'],
msg['_id'])
data_log = ret['data']
request.websocket.send(json.dumps(data_log).encode())
else:
ret = requests.get(
settings.APP_BACKEND['dorado_service'] + 'flow_detail?itsm_id=' + msg[
'itsm_id']).json()
data = ret['data']
if ret.get('status') == 'success':
state = None
for k, v in data.items():
if data[k]['flow_state'] == 'SUCCESS' or data[k]['flow_state'] == 'ERROR':
logger.info('flow_done')
state = True
break
if state:
request.websocket.send(json.dumps(data).encode())
break
else:
logger.info(data)
request.websocket.send(json.dumps(data).encode())
# time.sleep(15)
# continue
break
elif ret.get('status') == 'failing':
request.websocket.send(json.dumps(ret).encode())
break