utils.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. import os
  2. import json
  3. from aliyunsdkcore.client import AcsClient
  4. from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
  5. from model import InstanceList,IntfaceList
  6. # from DBSession import session_maker
  7. from model_longvideo import produce_video_task
  8. from DBSession_longvideo import session_maker_longvideo
  9. from aliyun.log.logclient import LogClient
  10. from aliyun.log.getlogsrequest import GetLogsRequest
  11. import requests
  12. import time
  13. import datetime
  14. import pymysql
  15. from sqlalchemy.sql import func
  16. from model_longvideo import produce_video_project
  17. from datetime import date, timedelta
  18. from DBSession import session_maker
  19. import logging
  20. from flask import current_app
  21. client = AcsClient('LTAI4GBWbFvvXoXsSVBe1o9f', 'kRAikWitb4kDxaAyBqNrmLmllMEDO3', 'cn-hangzhou')
  22. from prometheus_client import Gauge,Counter, generate_latest
  23. def intances_list_update():
  24. request = DescribeInstancesRequest()
  25. request.set_accept_format('json')
  26. request.set_PageSize(100)
  27. request.set_InstanceNetworkType("vpc")
  28. request.set_Tags([
  29. {
  30. "Key": "ecs"
  31. }
  32. ])
  33. response = client.do_action_with_exception(request)
  34. instance_info = json.loads(response)
  35. intances_list_del()
  36. print(len(instance_info["Instances"]["Instance"]))
  37. for i in range(len(instance_info["Instances"]["Instance"])):
  38. instance_id = instance_info["Instances"]["Instance"][i]["InstanceId"]
  39. ipaddr = instance_info["Instances"]["Instance"][i]["VpcAttributes"]["PrivateIpAddress"]["IpAddress"][0]
  40. server_name = instance_info["Instances"]["Instance"][i]["Tags"]["Tag"][0]["TagValue"]
  41. status = instance_info["Instances"]["Instance"][i]["Status"]
  42. instance_name = instance_info["Instances"]["Instance"][i]["HostName"]
  43. if status == "Running":
  44. status = 1
  45. instance_insert(instance_id, ipaddr, instance_name, server_name, status)
  46. return "OK"
  47. def intances_list_del():
  48. with session_maker() as session:
  49. session.query(InstanceList).delete()
  50. def instance_insert(instance_id, ipadd, instance_name, server_name, status):
  51. InstanceInfo = None
  52. InstanceInfo = InstanceList()
  53. with session_maker() as session:
  54. InstanceInfo.instance_id = instance_id
  55. InstanceInfo.ipadd = ipadd
  56. InstanceInfo.instance_name = instance_name
  57. InstanceInfo.server_name = server_name
  58. InstanceInfo.status = status
  59. session.add(InstanceInfo)
  60. def healthcheck(ipaddr,server_name):
  61. """返回容器upload时间,容器运行状态,健康坚持接口返回值,"""
  62. svc_name = server_name
  63. if svc_name == "longvideoapi.prod" :
  64. url = "http://{}:8080/longvideoapi/test".format(ipaddr)
  65. res = requests.post(url, timeout=5)
  66. print(res.status_code)
  67. return res.status_code
  68. elif svc_name == "commonapi.prod":
  69. url = "http://{}:8080/commonapi/test".format(ipaddr)
  70. res = requests.post(url, timeout=5)
  71. return res.status_code
  72. elif svc_name == "speed.prod":
  73. url = "http://{}:8080/longvideoapi/test".format(ipaddr)
  74. res = requests.post(url, timeout=5)
  75. return res.status_code
  76. elif svc_name == "clipapi.prod":
  77. url = "http://{}:8080/longvideoapi/test".format(ipaddr)
  78. res = requests.post(url, timeout=5)
  79. return res.status_code
  80. elif svc_name == "distribution.prod":
  81. url = "http://{}:8080/healthcheck".format(ipaddr)
  82. res = requests.post(url, timeout=5)
  83. return res.status_code
  84. elif svc_name == "manager.prod":
  85. url = "http://{}:8080/manager/healthcheck".format(ipaddr)
  86. res = requests.post(url, timeout=5)
  87. return res.status_code
  88. elif svc_name == "recommend-queue.prod":
  89. url = "http://{}:8080/video-recommend-queue/healthcheck".format(ipaddr)
  90. res = requests.post(url, timeout=5)
  91. return res.status_code
  92. elif svc_name == "recommend-rov.prod":
  93. url = "http://{}:8080/healthcheck".format(ipaddr)
  94. res = requests.post(url, timeout=5)
  95. return res.status_code
  96. elif svc_name == "measure-queue.prod":
  97. url = "http://{}:8080/video-measure-queue/healthcheck".format(ipaddr)
  98. res = requests.post(url, timeout=5)
  99. return res.status_code
  100. elif svc_name == "message-queue.prod":
  101. url = "http://{}:8080/video-message-queue/healthcheck".format(ipaddr)
  102. res = requests.post(url, timeout=5)
  103. return res.status_code
  104. elif svc_name == "search-material.prod":
  105. url = "http://{}:8089/v1/search/test".format(ipaddr)
  106. res = requests.post(url, timeout=5)
  107. return res.status_code
  108. elif svc_name == "spider.prod":
  109. url = "http://{}:9990/test/version".format(ipaddr)
  110. try:
  111. res = requests.post(url, timeout=5)
  112. except Exception as e:
  113. return -1
  114. return res.status_code
  115. elif svc_name == "video-job.prod":
  116. url = "http://{}:8080/video-job/healthcheck".format(ipaddr)
  117. res = requests.post(url, timeout=5)
  118. return res.status_code
  119. elif svc_name == "combine-job.prod":
  120. url = "http://{}:8080/video-combine-job/healthcheck".format(ipaddr)
  121. res = requests.post(url, timeout=5)
  122. return res.status_code
  123. elif svc_name == "recommend-server.prod":
  124. url = "http://{}:8080/healthcheck".format(ipaddr)
  125. # res = requests.post(url, timeout=5)
  126. return 200
  127. else:
  128. return 200
  129. # def healthcheck_metirc(instance_id,ipaddr,server_name,http_code):
  130. # healthcheck_status = Gauge("healthcheck_status", "http_code", ['instance_id', 'server_name', 'ipaddress'],
  131. # registry=registry)
  132. #
  133. # healthcheck_status.labels(instance_id, server_name, ipaddr).set(http_code)
  134. #
  135. # return Response(generate_latest(registry),mimetype="text/plain")
  136. def count_qps(appType, url):
  137. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  138. accessKeyId = 'LTAIWYUujJAm7CbH'
  139. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  140. logstore = 'request-log'
  141. client = LogClient(endpoint, accessKeyId, accessKey)
  142. project = 'wqsd-longvideoapi'
  143. topic = ""
  144. start_time = int(time.time())
  145. end_time = start_time - 60
  146. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  147. "params.appType={} and requestUri= {} |select requestUri,count(1) as cnt, date_format(logTimestamp/1000,'%Y-%m-%d %H:%i:%S') as date group by requestUri, date order by cnt desc limit 1".format(appType, url)
  148. , 30, 0, False)
  149. try:
  150. res = client.get_logs(req)
  151. except :
  152. qps = 0
  153. else:
  154. if res.body:
  155. qps = res.body[0]["cnt"]
  156. else:
  157. qps = 0
  158. print(int(time.time())-start_time)
  159. current_app.logger.info(qps)
  160. return qps
  161. def count_avg_time(appType ,url):
  162. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  163. accessKeyId = 'LTAIWYUujJAm7CbH'
  164. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  165. logstore = 'request-log'
  166. client = LogClient(endpoint, accessKeyId, accessKey)
  167. project = 'wqsd-longvideoapi'
  168. topic = ""
  169. start_time = int(time.time())
  170. end_time = start_time - 60
  171. # url = '/longvideoapi/user/idolsUpdated'
  172. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  173. "params.appType=%s and requestUri=%s |select requestUri,round(avg(expendTime)) as avgs,count(1) as cnt group by requestUri " %(appType, url), 30, 0, False)
  174. try:
  175. res = client.get_logs(req)
  176. except Exception as e:
  177. avgs = 0
  178. else:
  179. if res.body:
  180. avgs = res.body[0]["avgs"]
  181. else:
  182. avgs = 0
  183. return avgs
  184. def slb_status_code_count(server_name):
  185. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  186. accessKeyId = 'LTAIWYUujJAm7CbH'
  187. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  188. client = LogClient(endpoint, accessKeyId, accessKey)
  189. if server_name == "longvideoapi":
  190. project = 'longvideoapi-slb-log'
  191. logstore = 'slb-access-log'
  192. if server_name == "speed":
  193. project = 'speed-slb-log'
  194. logstore = 'access-log'
  195. if server_name == "clip":
  196. project = 'clips-slb-log'
  197. logstore = 'access-log'
  198. if server_name == "commonapi":
  199. project = 'commonapi-slb-log'
  200. logstore = 'slb-access-log'
  201. topic = ""
  202. end_time = int(time.time())
  203. start_time = end_time - (end_time - time.timezone)%86400
  204. # url = '/longvideoapi/user/idolsUpdated'
  205. req = GetLogsRequest(project, logstore, start_time, end_time, topic,
  206. "* |SELECT status ,COUNT(*) as cnt group by status" , 30, 0, False)
  207. try:
  208. res = client.get_logs(req)
  209. except Exception as e:
  210. avgs = 0
  211. else:
  212. if res.body:
  213. return res.body
  214. def produce_video_task_status_count():
  215. with session_maker_longvideo() as session:
  216. video_progress_count = session.query(produce_video_task).filter(produce_video_task.task_status == 1).count()
  217. video_success_count = session.query(produce_video_task).filter(produce_video_task.task_status == 2).count()
  218. video_fail_count = session.query(produce_video_task).filter(produce_video_task.task_status == 3).count()
  219. end_time = int(time.time())
  220. start_time = end_time - (end_time - time.timezone) % 86400
  221. res = session.query(produce_video_task).filter(produce_video_task.task_status==2).order_by(produce_video_task.id.desc()).first()
  222. duration = res.duration
  223. submit_timestamp = res.submit_timestamp
  224. complete_timestamp = res.complete_timestamp
  225. print(res.id,duration,submit_timestamp,complete_timestamp)
  226. rate = (duration / (complete_timestamp - submit_timestamp) / 1000)
  227. def logs_tts_count(tts_channel, tts_status):
  228. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  229. accessKeyId = 'LTAIWYUujJAm7CbH'
  230. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  231. client = LogClient(endpoint, accessKeyId, accessKey)
  232. project = 'wqsd-monitor'
  233. logstore = 'monitor-log'
  234. topic = ""
  235. end_time = int(time.time())
  236. start_time = end_time - (end_time - time.timezone)%86400
  237. req = GetLogsRequest(project, logstore, start_time, end_time, topic,
  238. "* and __topic__: producetts and channel:{} and produceStatus:{}| select channel,produceStatus,count(*) as count group by channel,produceStatus".format(tts_channel, tts_status) , 30, 0, False)
  239. try:
  240. res = client.get_logs(req)
  241. except Exception as e:
  242. avgs = 0
  243. else:
  244. if res.body:
  245. return res.body
  246. def logs_tts_ratio(tts_channel, tts_status):
  247. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  248. accessKeyId = 'LTAIWYUujJAm7CbH'
  249. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  250. client = LogClient(endpoint, accessKeyId, accessKey)
  251. project = 'wqsd-monitor'
  252. logstore = 'monitor-log'
  253. topic = ""
  254. end_time = int(time.time())
  255. start_time = end_time - 300
  256. print(start_time, end_time)
  257. req = GetLogsRequest(project, logstore, start_time, end_time, topic,
  258. "* and __topic__: producetts and channel:{} and produceStatus:{}| select channel,produceStatus,count(*) as count group by channel,produceStatus".format(tts_channel, tts_status) , 30, 0, False)
  259. try:
  260. res = client.get_logs(req)
  261. except Exception as e:
  262. avgs = 0
  263. else:
  264. if res.body:
  265. return res.body
  266. def count_recommend_null():
  267. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  268. accessKeyId = 'LTAIWYUujJAm7CbH'
  269. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  270. logstore = 'app-recommend-log'
  271. client = LogClient(endpoint, accessKeyId, accessKey)
  272. project = 'wqsd-longvideoapi'
  273. topic = ""
  274. start_time = int(time.time())
  275. #监控获取时间间隔300s
  276. end_time = start_time - 300
  277. query_sql = "* and requestUri:'/longvideoapi/video/distribute/category/videoList/v2' | select count(DISTINCT json_extract(params, '$.machineCode')) as cnt where json_array_length(json_extract(result, '$.data')) = 0"
  278. req = GetLogsRequest(project, logstore, end_time, start_time, topic, query_sql, 30, 0, False)
  279. try:
  280. res = client.get_logs(req)
  281. except Exception as e:
  282. print(e)
  283. avgs = 0
  284. else:
  285. if res.body:
  286. cnt_300 = res.body[0]["cnt"]
  287. else:
  288. cnt_300 = 0
  289. return cnt_300
  290. def db_query(sql):
  291. HOST = 'rr-bp1x9785e8h5452bi157.mysql.rds.aliyuncs.com'
  292. PORT = '3306'
  293. DATABASE = 'longvideo'
  294. USERNAME = 'devops'
  295. PASSWORD = 'devops@123456'
  296. conn = pymysql.connect(host=HOST, user=USERNAME, password=PASSWORD, database=DATABASE, charset="utf8")
  297. cursor = conn.cursor()
  298. cursor.execute(sql)
  299. res = cursor.fetchone()
  300. return res
  301. def db_query_devlop(sql):
  302. HOST = 'rm-bp1k5853td1r25g3n690.mysql.rds.aliyuncs.com'
  303. PORT = '3306'
  304. DATABASE = 'devops'
  305. USERNAME = 'devops'
  306. PASSWORD = 'devops@123456'
  307. conn = pymysql.connect(host=HOST, user=USERNAME, password=PASSWORD, database=DATABASE, charset="utf8")
  308. cursor = conn.cursor()
  309. cursor.execute(sql)
  310. res = cursor.fetchall()
  311. return res
  312. def db_query_prod(sql):
  313. HOST = 'rr-bp1x9785e8h5452bi157.mysql.rds.aliyuncs.com'
  314. PORT = '3306'
  315. DATABASE = 'longvideo'
  316. USERNAME = 'devops'
  317. PASSWORD = 'devops@123456'
  318. conn = pymysql.connect(host=HOST, user=USERNAME, password=PASSWORD, database=DATABASE, charset="utf8")
  319. cursor = conn.cursor()
  320. cursor.execute(sql)
  321. res = cursor.fetchone()
  322. return res
  323. def count_qps_avgtime(appType):
  324. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  325. accessKeyId = 'LTAIWYUujJAm7CbH'
  326. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  327. logstore = 'request-log'
  328. client = LogClient(endpoint, accessKeyId, accessKey)
  329. project = 'wqsd-longvideoapi'
  330. topic = ""
  331. start_time = int(time.time())
  332. end_time = start_time - 60
  333. # url = '/longvideoapi/user/idolsUpdated'
  334. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  335. "params.appType=%s | select requestUri,count(1) as cnt , avg(expendTime) as avg_time group by requestUri order by requestUri,cnt desc limit 1000" %(appType), 30, 0, False)
  336. try:
  337. res = client.get_logs(req)
  338. except Exception as e:
  339. avgs = 0
  340. return res
  341. def count_avg_max(appType):
  342. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  343. accessKeyId = 'LTAIWYUujJAm7CbH'
  344. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  345. logstore = 'request-log'
  346. client = LogClient(endpoint, accessKeyId, accessKey)
  347. project = 'wqsd-longvideoapi'
  348. topic = ""
  349. start_time = int(time.time())
  350. end_time = start_time - (60*15)
  351. # url = '/longvideoapi/user/idolsUpdated'
  352. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  353. "params.appType=%s | select requestUri,count(1) as cnt , max(expendTime) as max_time ,round(avg(expendTime),2) as avg_time group by requestUri order by requestUri,cnt desc limit 1000" %(appType), 30, 0, False)
  354. try:
  355. res = client.get_logs(req)
  356. except Exception as e:
  357. avgs = 0
  358. return res
  359. def count_rt_less_time_count(appType, than, less):
  360. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  361. accessKeyId = 'LTAIWYUujJAm7CbH'
  362. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  363. logstore = 'request-log'
  364. client = LogClient(endpoint, accessKeyId, accessKey)
  365. project = 'wqsd-longvideoapi'
  366. topic = ""
  367. start_time = int(time.time())
  368. end_time = start_time - 60
  369. # url = '/longvideoapi/user/idolsUpdated'
  370. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  371. "params.appType=%s and expendtime >%s and expendtime <%s| select requestUri,count(1) as cnt group by requestUri order by requestUri,cnt desc limit 1000" %(appType,than,less), 30, 0, False)
  372. try:
  373. res = client.get_logs(req)
  374. except Exception as e:
  375. print(e)
  376. return res
  377. def error_cnt(appType):
  378. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  379. accessKeyId = 'LTAIWYUujJAm7CbH'
  380. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  381. logstore = 'request-log'
  382. client = LogClient(endpoint, accessKeyId, accessKey)
  383. project = 'wqsd-longvideoapi'
  384. topic = ""
  385. start_time = int(time.time())
  386. end_time = start_time - 60
  387. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  388. "params.appType=%s and (resultCode:-111 or resultCode:-990 or resultCode:-994 or resultCode:-666 or resultCode:-222)| SELECT COUNT(*) as cnt, resultCode group by resultCode" %(appType), 30, 0, False)
  389. try:
  390. res = client.get_logs(req)
  391. except Exception as e:
  392. print(e)
  393. return res
  394. def app_openapi_qps_avgtime_count():
  395. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  396. accessKeyId = 'LTAIWYUujJAm7CbH'
  397. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  398. logstore = 'request-log'
  399. client = LogClient(endpoint, accessKeyId, accessKey)
  400. project = 'wqsd-longvideoapi'
  401. topic = ""
  402. start_time = int(time.time())
  403. end_time = start_time - 60
  404. url = '/longvideoapi/openapi/video/distribute/category/videoList/v2'
  405. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  406. "requestUri=%s| select requestUri,count(1) as cnt , avg(expendTime) as avg_time group by requestUri order by requestUri,cnt desc limit 1000"%(url) , 30, 0, False)
  407. try:
  408. res = client.get_logs(req)
  409. except Exception as e:
  410. avgs = 0
  411. return res,url
  412. def produce_video_data():
  413. start_time = (int(time.strftime("%Y%m%d", time.localtime()))) * 1000000000000000
  414. end_time = (int(time.strftime("%Y%m%d", time.localtime())) + 1) * 1000000000000000
  415. # start_time = (int(datetime.strftime("%Y%m%d",datetime.date.today()))
  416. print(start_time, end_time)
  417. sum_sql = ("select count(*) as totalCount "
  418. "from produce_video_project t1 "
  419. " where t1.project_id > %s and t1.project_id < %s and t1.app_type not in (1,13,15) "% (start_time,end_time)
  420. )
  421. res = db_query(sum_sql)
  422. return
  423. def update_request_url_list():
  424. HOST = 'rm-bp1k5853td1r25g3n690.mysql.rds.aliyuncs.com'
  425. PORT = '3306'
  426. DATABASE = 'devops'
  427. USERNAME = 'devops'
  428. PASSWORD = 'devops@123456'
  429. conn = pymysql.connect(host=HOST, user=USERNAME, password=PASSWORD, database=DATABASE, charset="utf8")
  430. cursor = conn.cursor()
  431. current_app.logger.info("定时任务开始5m")
  432. appType = ['0', '4', '5', '6', '12', '15']
  433. for index in range(len(appType)):
  434. type = appType[index]
  435. res = count_avg_max(type)
  436. for i in range(len(res.body)):
  437. url = res.body[i]["requestUri"]
  438. cnt = res.body[i]["cnt"]
  439. max_time = res.body[i]["max_time"]
  440. avg_time = res.body[i]["avg_time"]
  441. sql = "UPDATE `reuqest_url_list` set `qps`=%s, `max_time`=%s, `avg_time`=%s WHERE `request_url` ='%s' and `apptype`=%s" % (
  442. cnt, max_time, avg_time, url, type)
  443. cursor.execute(sql)
  444. conn.commit()
  445. for i in range(len(res.body)):
  446. url = res.body[i]["requestUri"]
  447. cnt = res.body[i]["cnt"]
  448. sql = "UPDATE `reuqest_url_list` set `rt_1`=%s WHERE `request_url` ='%s' and `apptype`=%s" % (
  449. cnt, url, type)
  450. cursor.execute(sql)
  451. conn.commit()
  452. res = count_rt_less_time_count(type, 200, 500)
  453. for i in range(len(res.body)):
  454. url = res.body[i]["requestUri"]
  455. cnt = res.body[i]["cnt"]
  456. sql = "UPDATE `reuqest_url_list` set `rt_2`=%s WHERE `request_url` ='%s' and `apptype`=%s" % (
  457. cnt, url, type)
  458. cursor.execute(sql)
  459. conn.commit()
  460. res = count_rt_less_time_count(type, 500, 1000)
  461. for i in range(len(res.body)):
  462. url = res.body[i]["requestUri"]
  463. cnt = res.body[i]["cnt"]
  464. sql = "UPDATE `reuqest_url_list` set `rt_3`=%s WHERE `request_url` ='%s' and `apptype`=%s" % (
  465. cnt, url, type)
  466. cursor.execute(sql)
  467. conn.commit()
  468. res = count_rt_less_time_count(type, 1000, 10000)
  469. for i in range(len(res.body)):
  470. url = res.body[i]["requestUri"]
  471. cnt = res.body[i]["cnt"]
  472. sql = "UPDATE `reuqest_url_list` set `rt_4`=%s WHERE `request_url` ='%s' and `apptype`=%s" % (
  473. cnt, url, type)
  474. cursor.execute(sql)
  475. conn.commit()
  476. def produce_video_task_cnt():
  477. start_time = int(time.strftime("%Y%m%d", time.localtime())) * 1000000000000000
  478. end_time = int(time.strftime("%Y%m%d%H%M", time.localtime())) * 100000000000
  479. query_sql = ("select count(*) as totalCount,"
  480. "sum(case when produce_status in (5,6,7,8) then 1 else 0 end) as successCount,"
  481. "sum(case when produce_status = 99 then 1 else 0 end) as failCount , "
  482. "sum(case when produce_status in(0,1,2,3,4) then 1 else 0 end) as processingCount,"
  483. "sum(case when produce_status in(5,6,7,8) and (rate < 0.5 or rate is null) then 1 else 0 end) processingCount1,"
  484. "sum(case when produce_status in(5,6,7,8) and rate >= 0.5 and rate < 0.7 then 1 else 0 end) processingCount2 ,"
  485. "sum(case when produce_status in(5,6,7,8) and rate >= 0.7 and rate < 1 then 1 else 0 end) processingCount3 ,"
  486. "sum(case when produce_status in(5,6,7,8) and rate >= 1 and rate < 1.5 then 1 else 0 end) processingCount4 ,"
  487. "sum(case when produce_status in(5,6,7,8) and rate >= 1.5 and rate < 2 then 2 else 0 end) processingCount5 ,"
  488. "sum(case when produce_status in(5,6,7,8) and rate >2 then 1 else 0 end) processingCount6 from "
  489. "(select t1.project_id, t1.produce_status, round((t2.last_connect_timestamp - t1.submit_timestamp) / (t1.video_duration/1000), 1) as rate from produce_video_project t1 "
  490. "left join produce_video_project_connect_time t2 on t1.project_id = t2.project_id "
  491. "where t1.project_id > %s and t1.project_id < %s and t1.app_type not in (1,13,15)) s1 " %(start_time ,end_time)
  492. )
  493. res = db_query(query_sql)
  494. return res
  495. def produce_video_ratio_cnt():
  496. HOST = 'rm-bp1k5853td1r25g3n690.mysql.rds.aliyuncs.com'
  497. PORT = '3306'
  498. DATABASE = 'devops'
  499. USERNAME = 'devops'
  500. PASSWORD = 'devops@123456'
  501. conn = pymysql.connect(host=HOST, user=USERNAME, password=PASSWORD, database=DATABASE, charset="utf8")
  502. cursor = conn.cursor()
  503. start_time = int((date.today() + timedelta(days=-1)).strftime("%Y%m%d")) * 1000000000000000
  504. # end_time = int(date.today().strftime("%Y%m%d")) * 1000000000000000
  505. end_time = int((date.today() + timedelta(days=0)).strftime("%Y%m%d")) * 1000000000000000
  506. sql = ("select count(*) as totalCount, "
  507. "sum(case when rate < 0.5 then 1 else 0 end) as r1,"
  508. "sum(case when (rate >= 0.5 and rate < 0.7) then 1 else 0 end) as r2,"
  509. "sum(case when (rate >= 0.7 and rate < 1) then 1 else 0 end) as r3,"
  510. "sum(case when (rate >= 1 and rate < 1.5) then 1 else 0 end) as r4,"
  511. "sum(case when (rate >= 1.5 and rate < 2) then 1 else 0 end) as r5,"
  512. "sum(case when rate >= 2 then 1 else 0 end) as r6 from "
  513. "(select project_id, round( (produce_done_timestamp - submit_timestamp) / (video_duration/1000),1) as rate from "
  514. "(select project_id, draftbox_id,video_duration,submit_timestamp,produce_done_timestamp from "
  515. "(select project_id, draftbox_id,video_duration,submit_timestamp,produce_done_timestamp from "
  516. "produce_video_project where project_id > %s and project_id < %s and app_type not in (1,13,15) and produce_status in (5,6,7,8) order by video_duration desc limit 100000) t1 group by draftbox_id) t2) t3"%(start_time, end_time)
  517. )
  518. y_date = (date.today() + timedelta(days=-1)).strftime("%Y%m%d")
  519. res = db_query(sql)
  520. if res[0]:
  521. cnt = res[0]
  522. else:
  523. cnt = 0
  524. if res[1]:
  525. r1 = res[1]
  526. else:
  527. r1 = 0
  528. if res[2]:
  529. r2 = res[2]
  530. else:
  531. r2 = 0
  532. if res[3]:
  533. r3 = res[3]
  534. else:
  535. r3 = 0
  536. if res[4]:
  537. r4 = res[4]
  538. else:
  539. r4 = 0
  540. if res[5]:
  541. r5 = res[5]
  542. else:
  543. r5 = 0
  544. if res[6]:
  545. r6 = res[6]
  546. else:
  547. r6 = 0
  548. sql = ("insert into produce_video_ratio (`cnt`,`r1`,`r2`,`r3`,`r4`,`r5`,`r6`,`date`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"%(cnt, r1, r2, r3, r4, r5, r6, y_date)
  549. )
  550. cursor.execute(sql)
  551. conn.commit()
  552. return res
  553. def create_log():
  554. LOG_PATH = os.path.abspath(os.path.join(os.path.join(basedir, os.path.pardir), 'logs'))
  555. # 创建handler
  556. handler = RotatingFileHandler(os.path.join(LOG_PATH, 'flask_demo.log'), maxBytes=100 * 1024 * 1024, backupCount=10,
  557. encoding="utf-8")
  558. # 设置handler日志级别
  559. handler.setLevel(logging.INFO)
  560. # 设置handler打印格式
  561. fmt_str = logging.Formatter(
  562. '时间:%(asctime)-15s 日志级别:%(levelname)s 文件名:%(filename)s 行数:%(lineno)d 进程号:%(process)d 当前线程号:%(thread)s 日志信息:%(message)s')
  563. handler.setFormatter(fmt_str)
  564. # if __name__ == '__main__':
  565. # res = logs_tts_ratio("aliyun",1)
  566. # print(res)