This commit is contained in:
aozhiwei 2020-03-16 11:09:26 +08:00
parent 3d917552f8
commit 9a388bb8cd
13 changed files with 5 additions and 349 deletions

6
.gitmodules vendored
View File

@ -1,9 +1,9 @@
[submodule "third_party/phpcommon"]
path = third_party/phpcommon
url = git@git.kingsome.cn:server_common/phpcommon.git
[submodule "third_party/f7"]
path = third_party/f7
url = git@git.kingsome.cn:server_common/f7.git
[submodule "third_party/q7"]
path = third_party/q7
url = git@git.kingsome.cn:server_common/q7.git
[submodule "third_party/f7"]
path = third_party/f7
url = git@git.kingsome.cn:server_common/f7.git

1
third_party/f7 vendored Submodule

@ -0,0 +1 @@
Subproject commit 1d7840b984d20261df241e39db0d8089a831f5b3

View File

@ -1 +0,0 @@
*.pyc

View File

@ -1,3 +0,0 @@
[submodule "third_party/q7"]
path = third_party/q7
url = git@git.kingsome.cn:server_common/q7.git

View File

@ -1,34 +0,0 @@
# -*- coding: utf-8 -*-
#!/usr/bin/python
import os
from .app import instance as i_app
from .timer import instance as i_timer
from .udplog import instance as i_udplog
app = i_app()
udplog = i_udplog()
timer = i_timer()
def isOnlineEnv():
return not os.getenv("SERVER_ENV");
def scanRedisKey(conn, pattern):
result = {}
cursor, keys = conn.scan(0, pattern, 1000)
while cursor != 0 or len(keys) > 0:
for key in keys:
if key in result:
result[key] += result[key]
else:
result[key] = 0
keys = []
if cursor != 0:
cursor, keys = conn.scan(cursor, pattern, 1000)
return result
def getChannelByAccountId(account_id):
tmp_strings = account_id.split('_')
if len(tmp_strings) < 3:
return 0
return tmp_strings[0]

View File

@ -1,130 +0,0 @@
# -*- coding: utf-8 -*-
#!/usr/bin/python
import f7
import json
import threading
import traceback
import tornado.web
import tornado.ioloop
class _mainHandler(tornado.web.RequestHandler):
def get(self):
instance()._dispatchRequest(self)
_IM_DoneCallback = 100
class _App:
_instance = None
@classmethod
def instance(cls):
if not cls._instance:
cls._instance = _App()
return cls._instance
def __init__(self):
self._listened = False
self._requestHandler = {}
self._app = tornado.web.Application([
(r"/webapp/index[\.]php", _mainHandler),
])
self.registerHandler('Ops', 'selfChecking', self.__selfChecking)
self._immsgLock = threading.Lock()
self._immsgList = []
tornado.ioloop.PeriodicCallback(self._processIMMsg, 100).start()
def init(self, log_dir):
f7.udplog.init()
f7.udplog.setLogDirAndCreate(log_dir)
def start(self):
if self._listened:
tornado.ioloop.IOLoop.current().start()
f7.timer.unInit()
f7.udplog.unInit()
def listen(self, port):
self._app.listen(port)
self._listened = True
def callAt(self, when, callback):
tornado.ioloop.IOLoop.current().call_at(when, callback)
def callLater(self, when, callback):
tornado.ioloop.IOLoop.current().call_later(when, callback)
def registerHandler(self, c, a, callback):
self._requestHandler[c + '$' + a] = callback
def _dispatchRequest(self, request):
c = request.get_argument('c', '')
a = request.get_argument('a', '')
handler = self._requestHandler.get(c + '$' + a, None)
if not handler:
request.write('')
return
try:
response = handler(lambda param, def_val = '': request.get_argument(param, def_val))
request.write(response)
except Exception as e:
f7.udplog.error('dispatch request ' + str(e))
request.write(json.dumps({
'errcode': 200,
'errmsg': '服务内部错误',
}))
def __selfChecking(self, request):
return json.dumps({
'errcode': 0,
'errmsg': '',
'healthy': 1,
'max_rundelay': 10
})
def _processIMMsg(self):
self._immsgLock.acquire()
try:
if len(self._immsgList) > 0:
for node in self._immsgList:
self._dispatchIMMsg(node[0], node[1])
finally:
self._immsgList = []
self._immsgLock.release()
def _dispatchIMMsg(self, msgid, callback):
try:
if msgid == _IM_DoneCallback:
self._IMDoneCallback(callback)
except Exception as e:
f7.udplog.error('_dispatchIMMsg %d %s' % (msgid, str(e)))
def _addIMMsg(self, msgid, callback):
self._immsgLock.acquire()
try:
self._immsgList.append((msgid, callback))
finally:
self._immsgLock.release()
def _IMDoneCallback(self, callback):
callback()
def createAsyncTask(self, done_callback, func, *args):
assert self._listened
def thread_func(args):
try:
if len(args) > 0:
func(args)
else:
func()
except Exception as e:
f7.udplog.error('_dispatchIMMsg ' + str(e))
if done_callback:
self._addIMMsg(_IM_DoneCallback, done_callback)
thread = threading.Thread(target = thread_func, args = args)
thread.start()
def instance():
return _App.instance()

View File

@ -1,28 +0,0 @@
# -*- coding: utf-8 -*-
#!/usr/bin/python
import f7
class _Timer:
_instance = None
@classmethod
def instance(cls):
if not cls._instance:
cls._instance = _Timer()
return cls._instance
def __init__(self):
pass
def unInit(self):
pass
def callAt(self, when, callback):
f7.app.callAt(when, callback)
def callLater(self, when, callback):
f7.app.callLater(when, callback)
def instance():
return _Timer.instance()

View File

@ -1,110 +0,0 @@
# -*- coding: utf-8 -*-
import os
import time
import datetime
import traceback
import threading
import q7
class _LocalLogNode:
def __init__(self, msg):
self.msg = msg
self.nextNode = None
class _UdpLog:
_instance = None
@classmethod
def instance(cls):
if not cls._instance:
cls._instance = _UdpLog()
return cls._instance
def __init__(self):
self._logDir = ''
self._topNode = None
self._botNode = None
self._workNode = None
self._terminated = False
self._cond = threading.Condition()
self._msgLock = threading.Lock()
self._workerThread = threading.Thread(target = self._saveToFile, args = ())
def init(self):
self._workerThread.start()
def unInit(self):
self._terminated = True
self._cond.acquire()
self._cond.notifyAll()
self._cond.release()
self._workerThread.join()
def setLogDirAndCreate(self, logdir):
if not os.path.exists(logdir):
os.makedirs(logdir)
self._logDir = logdir
def info(self, msg):
self._addLog(str(datetime.datetime.now()) + '[INFO]' + str(msg))
def debug(self, msg):
self._addLog(str(datetime.datetime.now()) + '[DEBUG]' + str(msg))
def warning(self, msg):
self._addLog(str(datetime.datetime.now()) + '[WARNING]' + str(msg))
def error(self, msg):
self._addLog(str(datetime.datetime.now()) + '[ERROR]' + str(msg))
def _addLog(self, msg):
node = _LocalLogNode(msg)
self._msgLock.acquire()
try:
if self._botNode == None:
self._topNode = node
self._botNode = node
else:
self._botNode.nextNode = node
self._botNode = node
except:
traceback.print_exc()
finally:
self._msgLock.release()
def _saveToFile(self):
try:
while not self._terminated:
self._internalSave()
self._cond.acquire()
self._cond.wait(10)
self._cond.release()
self._internalSave()
except:
traceback.print_exec()
def _internalSave(self):
if not self._workNode and self._topNode:
self._msgLock.acquire()
try:
self._workNode = self._topNode
self._topNode = None
self._botNode = None
finally:
self._msgLock.release()
if self._workNode:
filename = datetime.datetime.now().strftime('log_' + str(os.getpid()) + '_%Y%m%d.log')
try:
with open(os.path.join(self._logDir, filename), 'a') as f:
while self._workNode:
nextNode = self._workNode.nextNode
f.write(self._workNode.msg + '\r\n')
self._workNode = nextNode
except Exception as e:
print(str(e), flush=True)
def instance():
return _UdpLog.instance()

View File

@ -1,13 +0,0 @@
# -*- coding: utf-8 -*-
import sys
import time
sys.path.append('..')
import f7.udplog
f7.udplog.instance().init()
f7.udplog.instance().setLogDirAndCreate('/data/logs/f7test/logs')
f7.udplog.instance().info('start')
time.sleep(15)

1
third_party/q7 vendored Submodule

@ -0,0 +1 @@
Subproject commit 4af43d56490d566c38021d9687975dae17d9e7ad

View File

@ -1 +0,0 @@
*.pyc

View File

@ -1,4 +0,0 @@
# -*- coding: utf-8 -*-
#!/usr/bin/python
from .sysutils import *

View File

@ -1,22 +0,0 @@
# -*- coding: utf-8 -*-
#!/usr/bin/python
import binascii
def xPrint(text):
print(text, flush=True)
def getDaySeconds(time_val, incdays):
time_zone = 8
return int((time_val + time_zone * 3600)/3600/24 + incdays) * 3600 * 24 - 3600 * time_zone;
def crc32(data):
hash_code = binascii.crc32(data)
assert hash_code >= 0
return hash_code
def safeDiv(a, b):
if b == 0:
return 0
else:
return a / b