You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tasks_loop.py 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import asyncio
  2. import time
  3. import redis
  4. import os
  5. import copy
  6. import json
  7. import traceback
  8. import inspect
  9. import atexit
  10. from asgiref.sync import async_to_sync,sync_to_async
  11. '''
  12. umod
  13. # '''
  14. p=print
  15. async def anop(*a,**kw):pass
  16. def nop(*a,**kw):pass
  17. class Edict(dict):pass
  18. class Eobj():pass
  19. def connect_redis():
  20. return redis.Redis(host='localhost', port=6379, db=0,charset="utf-8", decode_responses=True, encoding_errors="backslashreplace")
  21. def eclass_factory(n):
  22. ret = []
  23. for k in range(n):
  24. class nx:pass
  25. # _rcls_name
  26. ret.append(nx)
  27. return ret
  28. '''
  29. # '''
  30. def callable_helper(fn):
  31. ret = {
  32. "is_callable":0,
  33. "is_coroutine":0,
  34. }
  35. ret["is_callable"]= callable(fn)
  36. ret["is_coroutine"]= inspect.iscoroutinefunction(fn)
  37. # if (ca)
  38. return ret
  39. verbose = print
  40. class DbgMixin:
  41. async def ws_rec(self,text_data,*a,**kw):
  42. # if "dbg" in
  43. text_data_json = json.loads(text_data)
  44. if not 'dbg' in text_data_json:
  45. return
  46. p("DBG!")
  47. exec(text_data_json["dbg"])
  48. class AconMixin(DbgMixin):
  49. # class AconMixin:
  50. async def connect(self):
  51. # print("-----------CONNECTING async def connect")
  52. p("ACON!!!!!!!!!!!!!!!!!!!!!!!!!!!")
  53. p(flush=True)
  54. await self.accept()
  55. verbose("<MRO")
  56. verbose(type(self))
  57. await self.call_all_mro("ws_conn0")
  58. await self.call_all_mro("ws_conn")
  59. await self.call_all_mro("ws_conn2")
  60. verbose("/MRO>")
  61. # await self.ws_conn_once(event)
  62. await self.ws_conn_once()
  63. async def ws_conn_once(self, *a,**kw):pass
  64. async def ws_disconn_once(self, *a,**kw):pass
  65. async def ws_rec_once(self, *a,**kw):pass
  66. async def receive(self, *a,**kw):
  67. print("REC")
  68. print("",end="",flush=True)
  69. # print("-----------REC")
  70. await self.call_all_mro("ws_rec",*a,**kw)
  71. await self.ws_rec_once(*a,**kw)
  72. async def call_all_mro(self,mthd_name,*args,**kwargs):
  73. called = set([None])
  74. for cls_obj in self.__class__.__mro__:
  75. mthd = getattr(cls_obj,mthd_name,None)
  76. # print("~",cls_obj,mthd)
  77. if not mthd in called:
  78. # print(cls_obj,mthd)
  79. called.add(mthd)
  80. await mthd(self,*args,**kwargs)
  81. async def disconnect(self, close_code):
  82. await self.call_all_mro("ws_disconn",close_code)
  83. await self.ws_disconn_once(close_code)
  84. async def websocket_connect_x(self, event):
  85. await super().websocket_connect(event)
  86. print("<MRO")
  87. print(type(self))
  88. await self.call_all_mro("ws_conn",event)
  89. await self.call_all_mro("ws_conn2",event)
  90. print("/MRO>")
  91. await self.ws_conn_once(event)
  92. class AclTaskMixin:
  93. async def ws_disconn(self,*a,**kw):
  94. # for group in self.groups_set:
  95. pass
  96. async def ws_conn0(self):
  97. self.groups_set = set()
  98. if glob_cl.has_cl:
  99. return
  100. glob_cl.has_cl = True
  101. print("AclTaskMixin:ws_conn0")
  102. glob_cl.run_persistent_loop(self)
  103. glob_cl.acl = self.channel_layer
  104. # print("++++++++++++++++++++++++++")
  105. async def ws_conn_once(self,*a,**kw):
  106. print("\t\tws_conn_once:","AclTaskMixin")
  107. class DevMixin(*eclass_factory(10)):pass
  108. class DevMroMixin(*eclass_factory(10)):pass
  109. class WSStoMixin(*eclass_factory(10)):pass
  110. class GCLMixin(*eclass_factory(10)):pass
  111. class RldManMixin(*eclass_factory(10)):pass
  112. class LoneMixinA():pass
  113. class LoneMixinB():pass
  114. Mixins = Eobj()
  115. Mixins.DevMixin = DevMixin
  116. Mixins.DevMroMixin = DevMroMixin
  117. Mixins.WSStoMixin = WSStoMixin
  118. Mixins.GCLMixin = GCLMixin
  119. Mixins.RldManMixin = RldManMixin
  120. Mixins.LoneMixinA = LoneMixinA
  121. Mixins.LoneMixinB = LoneMixinB
  122. Mixins.DbgMixin = DbgMixin
  123. Mixins.AconMixin = AconMixin
  124. Mixins.AclTaskMixin = AclTaskMixin
  125. # GCLMixin
  126. class globCL(GCLMixin):
  127. def __init__(self,*a,**kw):
  128. # for now we are not going to do any weird class stuff
  129. self.acl = None
  130. self.has_cl = False
  131. self.rconn = connect_redis()
  132. self.rman = RldMan()
  133. self.cbs_once = []
  134. self.cbs_once_set = set()
  135. self.cbs = {"fn1":fn1,"fn2x":nop}
  136. self.timeout = 1
  137. pass
  138. async def persistent_loop(self,*a,**kw):
  139. while 1:
  140. # p("PL:",time.time(),flush=1)
  141. # await asyncio.sleep(5)
  142. # for k,v in cls.cbs.items():
  143. for k,v in [*self.cbs.items()]:
  144. try:
  145. call_info = callable_helper(v)
  146. if (call_info["is_callable"]):
  147. if call_info["is_coroutine"]:
  148. pass
  149. await v({k,self})
  150. else:
  151. v({k,self})
  152. else:
  153. pass
  154. # p(k,v)
  155. pass
  156. except Exception as e:
  157. p("persistent_loop Exception",e)
  158. p(flush=True)
  159. # raise
  160. else:
  161. pass
  162. finally:
  163. pass
  164. # cbs_once
  165. cbs_once = [*self.cbs_once,*self.cbs_once_set]
  166. self.cbs_once = []
  167. self.cbs_once_set = set()
  168. k=0
  169. for v in cbs_once:
  170. try:
  171. call_info = callable_helper(v)
  172. if (call_info["is_callable"]):
  173. if call_info["is_coroutine"]:
  174. pass
  175. await v({k,self})
  176. else:
  177. v({k,self})
  178. else:
  179. pass
  180. # p(k,v)
  181. pass
  182. except Exception as e:
  183. p("persistent_loop Exception cbs_once:",e)
  184. p(flush=True)
  185. # raise
  186. else:
  187. pass
  188. finally:
  189. pass
  190. k += 1
  191. await asyncio.sleep(self.timeout)
  192. def _run_persistent_loop(self,*a,**kw):
  193. p("_run_persistent_loop:")
  194. loop = asyncio.get_event_loop()
  195. self.run_persistent_loop = nop
  196. self.rman.persistent_loop_cb()
  197. loop.create_task(self.persistent_loop())
  198. self.loop = loop
  199. run_persistent_loop = _run_persistent_loop
  200. def sync_dev_group_add(self,*a,**kw):
  201. glob_cl.cbs_once.append(group_add(*a,**kw))
  202. async def dev_group_add(self,group_name,consumer):
  203. channel_layer = glob_cl.acl
  204. # if not consumer.channel_name in consumer.groups_set:
  205. # consumer.groups_set.add(groups)
  206. if not consumer.channel_name in consumer.groups:
  207. consumer.groups.append(group_name)
  208. await channel_layer.group_add(group_name,consumer.channel_name)
  209. # RldManMixin
  210. class RldMan(RldManMixin):
  211. def __init__(self,*a,**kw):
  212. self.files = {}
  213. z="ABC"
  214. self.scopes = {
  215. "dflt_scope":{"globals":globals(),"locals":locals()},
  216. "dflt_scope_zloc":{"globals":globals(),"locals":{}},
  217. "dflt_scope_gscope":{"globals":globals(),"locals":{}},
  218. "dflt_scope_copy": {"globals":copy.copy(globals()),"locals":copy.copy(locals())},
  219. # "dflt_scope":{"globals":globals(),"locals":{}}
  220. }
  221. self.scopes['current_scope'] = self.scopes['dflt_scope_zloc']
  222. # self.scope_opt = "locals"
  223. self.scope_opt = "globals"
  224. self.print_tb = 0
  225. base_path = "/usr/games/repos/ign4/py_rld/djc/rdir1/"
  226. file_list = [
  227. base_path+"i0.py",
  228. base_path+"i1.py",
  229. base_path+"i2.py",
  230. base_path+"i3.py",
  231. base_path+"i4.py",
  232. base_path+"i5.py",
  233. ]
  234. self.add_files(file_list)
  235. # self.add_files(file_list,{"run"})
  236. def persistent_loop_cb(self,*a,**kw):
  237. base_path = "/usr/games/repos/ign4/py_rld/djc/rdir1/"
  238. file_list = [
  239. base_path+"r0.py",
  240. base_path+"r1.py",
  241. base_path+"r2.py",
  242. base_path+"r3.py",
  243. base_path+"r4.py",
  244. base_path+"r5.py",
  245. ]
  246. self.add_files(file_list)
  247. def add_files(self,files):
  248. for file in files:
  249. if type(file)==str:
  250. self.add_file(file)
  251. elif type(file)==list:
  252. self.add_file(*file)
  253. else:
  254. p("add files???",file)
  255. def add_file(self,file_name,fnx={}):
  256. self.files[file_name] = {"ftxt":"",**fnx}
  257. def get_scope(self,rfile_obj,file_name):
  258. return self.scopes["current_scope"]
  259. return {
  260. "scope":self.scopes["current_scope"],
  261. }
  262. # rfile_obj.get("scope")
  263. # if
  264. def rld_file(self,file_name,ret= {"errs":{},"all":{},"alle":{},},**kw):
  265. if file_name in self.files:
  266. rfile_obj = self.files[file_name]
  267. st = os.stat(file_name)
  268. st_tuple = (st.st_mtime,st.st_size)
  269. # if rfile_obj["ftxt"] == "":
  270. eflag ="nd"
  271. # rfile_obj["ftxt"] = st_tuple
  272. if rfile_obj["ftxt"] != st_tuple:
  273. # p(rfile_obj["ftxt"])
  274. rfile_obj["ftxt"] = st_tuple
  275. try:
  276. f = open(file_name,"r")
  277. ftxt = f.read()
  278. # scope_key = rfile_obj.get("scope")
  279. # p(scope_key,rfile_obj)
  280. f.close()
  281. scope_obj = self.get_scope(file_name,rfile_obj)
  282. if self.scope_opt == "locals":
  283. eflag ="locals"
  284. exec(ftxt,scope_obj["globals"],scope_obj["locals"])
  285. elif self.scope_opt == "globals":
  286. eflag ="globals"
  287. exec(ftxt,scope_obj["globals"])
  288. else:
  289. eflag ="[]"
  290. exec(ftxt)
  291. except Exception as e:
  292. p()
  293. print("file:",file_name)
  294. print("EXCEPT",eflag,e)
  295. if self.print_tb:
  296. traceback.print_tb(e.__traceback__,file=sys.stdout)
  297. else:
  298. pass
  299. # print("ELSE")
  300. finally:
  301. # print("FINALLY")
  302. pass
  303. print(end="",flush=True)
  304. return ret
  305. def rld_files(self):
  306. # p()
  307. ret = {
  308. "errs":{},
  309. "all":{},
  310. "alle":{},
  311. }
  312. # for k in self.files:
  313. for k in [*self.files]:
  314. self.rld_file(k,ret)
  315. # p("rld_files!")
  316. p("",end="",flush=True)
  317. return ret
  318. def fn1(*a,**kw):
  319. # rld_files
  320. glob_cl.rman.rld_files()
  321. glob_cl = globCL()
  322. glob_cl.rman.rld_files()
  323. # print("..",end="\n",flush=True)
  324. r"""
  325. def atexit_fn():
  326. pass
  327. # rconn.flushall()
  328. print("ATEXIT FN")
  329. rinfo_len()
  330. keys = rconn.keys()
  331. print(keys)
  332. print(len(keys))
  333. print("t 000")
  334. # time.sleep(10)
  335. print("t 010")
  336. # time.sleep(20)
  337. print("t 020")
  338. print("ATEXIT FN...")
  339. rconn.flushall()
  340. atexit.register(atexit_fn)
  341. # """
  342. def atexit_fn():
  343. print("atexit_fn!\n\n")
  344. print("",end="",flush=True)
  345. atexit.register(atexit_fn)