utils.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. client = AcsClient('LTAI4GBWbFvvXoXsSVBe1o9f', 'kRAikWitb4kDxaAyBqNrmLmllMEDO3', 'cn-hangzhou')
  19. def intances_list_update():
  20. request = DescribeInstancesRequest()
  21. request.set_accept_format('json')
  22. request.set_PageSize(100)
  23. request.set_InstanceNetworkType("vpc")
  24. request.set_Tags([
  25. {
  26. "Key": "ecs"
  27. }
  28. ])
  29. response = client.do_action_with_exception(request)
  30. instance_info = json.loads(response)
  31. intances_list_del()
  32. print(len(instance_info["Instances"]["Instance"]))
  33. for i in range(len(instance_info["Instances"]["Instance"])):
  34. instance_id = instance_info["Instances"]["Instance"][i]["InstanceId"]
  35. ipaddr = instance_info["Instances"]["Instance"][i]["VpcAttributes"]["PrivateIpAddress"]["IpAddress"][0]
  36. server_name = instance_info["Instances"]["Instance"][i]["Tags"]["Tag"][0]["TagValue"]
  37. status = instance_info["Instances"]["Instance"][i]["Status"]
  38. instance_name = instance_info["Instances"]["Instance"][i]["HostName"]
  39. if status == "running":
  40. status = 1
  41. instance_insert(instance_id, ipaddr, instance_name, server_name, status)
  42. return "OK"
  43. def intances_list_del():
  44. with session_maker() as session:
  45. session.query(InstanceList).delete()
  46. def instance_insert(instance_id, ipadd, instance_name, server_name, status):
  47. InstanceInfo = None
  48. InstanceInfo = InstanceList()
  49. with session_maker() as session:
  50. InstanceInfo.instance_id = instance_id
  51. InstanceInfo.ipadd = ipadd
  52. InstanceInfo.instance_name = instance_name
  53. InstanceInfo.server_name = server_name
  54. InstanceInfo.status = status
  55. session.add(InstanceInfo)
  56. def healthcheck(ipaddr,server_name):
  57. """返回容器upload时间,容器运行状态,健康坚持接口返回值,"""
  58. svc_name = server_name
  59. print(server_name)
  60. if svc_name == "longvideoapi.prod" :
  61. url = "http://{}:8080/longvideoapi/test".format(ipaddr)
  62. res = requests.post(url, timeout=5)
  63. print(res.status_code)
  64. return res.status_code
  65. if svc_name == "commonapi.prod":
  66. url = "http://{}:8080/commonapi/test".format(ipaddr)
  67. res = requests.post(url, timeout=5)
  68. return res.status_code
  69. if svc_name == "speed.prod":
  70. url = "http://{}:8080/longvideoapi/test".format(ipaddr)
  71. res = requests.post(url, timeout=5)
  72. return res.status_code
  73. if svc_name == "clipapi.prod":
  74. url = "http://{}:8080/longvideoapi/test".format(ipaddr)
  75. res = requests.post(url, timeout=5)
  76. return res.status_code
  77. if svc_name == "distribution.prod":
  78. url = "http://{}:8080/healthcheck".format(ipaddr)
  79. res = requests.post(url, timeout=5)
  80. return res.status_code
  81. if svc_name == "manager.prod":
  82. url = "http://{}:8971/dev/test/healthcheck".format(ipaddr)
  83. res = requests.post(url, timeout=5)
  84. return res.status_code
  85. if svc_name == "recommend-queue.prod":
  86. url = "http://{}:8080/healthcheck".format(ipaddr)
  87. res = requests.post(url, timeout=5)
  88. return res.status_code
  89. # def healthcheck_metirc(instance_id,ipaddr,server_name,http_code):
  90. # healthcheck_status = Gauge("healthcheck_status", "http_code", ['instance_id', 'server_name', 'ipaddress'],
  91. # registry=registry)
  92. #
  93. # healthcheck_status.labels(instance_id, server_name, ipaddr).set(http_code)
  94. #
  95. # return Response(generate_latest(registry),mimetype="text/plain")
  96. def count_qps(appType, url):
  97. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  98. accessKeyId = 'LTAIWYUujJAm7CbH'
  99. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  100. logstore = 'request-log'
  101. client = LogClient(endpoint, accessKeyId, accessKey)
  102. project = 'wqsd-longvideoapi'
  103. topic = ""
  104. start_time = int(time.time())
  105. end_time = start_time - 60
  106. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  107. "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)
  108. , 30, 0, False)
  109. try:
  110. res = client.get_logs(req)
  111. except :
  112. qps = 0
  113. else:
  114. if res.body:
  115. qps = res.body[0]["cnt"]
  116. else:
  117. qps = 0
  118. print(int(time.time())-start_time)
  119. return qps
  120. def count_avg_time(appType ,url):
  121. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  122. accessKeyId = 'LTAIWYUujJAm7CbH'
  123. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  124. logstore = 'request-log'
  125. client = LogClient(endpoint, accessKeyId, accessKey)
  126. project = 'wqsd-longvideoapi'
  127. topic = ""
  128. start_time = int(time.time())
  129. end_time = start_time - 60
  130. # url = '/longvideoapi/user/idolsUpdated'
  131. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  132. "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)
  133. try:
  134. res = client.get_logs(req)
  135. except Exception as e:
  136. avgs = 0
  137. else:
  138. if res.body:
  139. avgs = res.body[0]["avgs"]
  140. else:
  141. avgs = 0
  142. return avgs
  143. def slb_status_code_count(server_name):
  144. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  145. accessKeyId = 'LTAIWYUujJAm7CbH'
  146. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  147. client = LogClient(endpoint, accessKeyId, accessKey)
  148. if server_name == "longvideoapi":
  149. project = 'longvideoapi-slb-log'
  150. logstore = 'slb-access-log'
  151. if server_name == "speed":
  152. project = 'speed-slb-log'
  153. logstore = 'access-log'
  154. if server_name == "clip":
  155. project = 'clips-slb-log'
  156. logstore = 'access-log'
  157. if server_name == "commonapi":
  158. project = 'commonapi-slb-log'
  159. logstore = 'slb-access-log'
  160. topic = ""
  161. end_time = int(time.time())
  162. start_time = end_time - (end_time - time.timezone)%86400
  163. # url = '/longvideoapi/user/idolsUpdated'
  164. req = GetLogsRequest(project, logstore, start_time, end_time, topic,
  165. "* |SELECT status ,COUNT(*) as cnt group by status" , 30, 0, False)
  166. try:
  167. res = client.get_logs(req)
  168. except Exception as e:
  169. avgs = 0
  170. else:
  171. if res.body:
  172. return res.body
  173. def produce_video_task_status_count():
  174. with session_maker_longvideo() as session:
  175. video_progress_count = session.query(produce_video_task).filter(produce_video_task.task_status == 1).count()
  176. video_success_count = session.query(produce_video_task).filter(produce_video_task.task_status == 2).count()
  177. video_fail_count = session.query(produce_video_task).filter(produce_video_task.task_status == 3).count()
  178. end_time = int(time.time())
  179. start_time = end_time - (end_time - time.timezone) % 86400
  180. res = session.query(produce_video_task).filter(produce_video_task.task_status==2).order_by(produce_video_task.id.desc()).first()
  181. duration = res.duration
  182. submit_timestamp = res.submit_timestamp
  183. complete_timestamp = res.complete_timestamp
  184. print(res.id,duration,submit_timestamp,complete_timestamp)
  185. rate = (duration / (complete_timestamp - submit_timestamp) / 1000)
  186. def logs_tts_count(tts_channel, tts_status):
  187. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  188. accessKeyId = 'LTAIWYUujJAm7CbH'
  189. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  190. client = LogClient(endpoint, accessKeyId, accessKey)
  191. project = 'wqsd-monitor'
  192. logstore = 'monitor-log'
  193. topic = ""
  194. end_time = int(time.time())
  195. start_time = end_time - (end_time - time.timezone)%86400
  196. req = GetLogsRequest(project, logstore, start_time, end_time, topic,
  197. "* 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)
  198. try:
  199. res = client.get_logs(req)
  200. except Exception as e:
  201. avgs = 0
  202. else:
  203. if res.body:
  204. return res.body
  205. def count_recommend_null():
  206. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  207. accessKeyId = 'LTAIWYUujJAm7CbH'
  208. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  209. logstore = 'app-recommend-log'
  210. client = LogClient(endpoint, accessKeyId, accessKey)
  211. project = 'wqsd-longvideoapi'
  212. topic = ""
  213. start_time = int(time.time())
  214. #监控获取时间间隔300s
  215. end_time = start_time - 300
  216. 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"
  217. req = GetLogsRequest(project, logstore, end_time, start_time, topic, query_sql, 30, 0, False)
  218. try:
  219. res = client.get_logs(req)
  220. except Exception as e:
  221. print(e)
  222. avgs = 0
  223. else:
  224. if res.body:
  225. cnt_300 = res.body[0]["cnt"]
  226. else:
  227. cnt_300 = 0
  228. return cnt_300
  229. def db_query(sql):
  230. HOST = 'rr-bp1x9785e8h5452bi157.mysql.rds.aliyuncs.com'
  231. PORT = '3306'
  232. DATABASE = 'longvideo'
  233. USERNAME = 'devops'
  234. PASSWORD = 'devops@123456'
  235. conn = pymysql.connect(host=HOST, user=USERNAME, password=PASSWORD, database=DATABASE, charset="utf8")
  236. cursor = conn.cursor()
  237. cursor.execute(sql)
  238. res = cursor.fetchone()
  239. return res
  240. def db_query_prod(sql):
  241. HOST = 'rr-bp1x9785e8h5452bi157.mysql.rds.aliyuncs.com'
  242. PORT = '3306'
  243. DATABASE = 'longvideo'
  244. USERNAME = 'devops'
  245. PASSWORD = 'devops@123456'
  246. conn = pymysql.connect(host=HOST, user=USERNAME, password=PASSWORD, database=DATABASE, charset="utf8")
  247. cursor = conn.cursor()
  248. cursor.execute(sql)
  249. res = cursor.fetchone()
  250. return res
  251. def count_qps_avgtime(appType):
  252. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  253. accessKeyId = 'LTAIWYUujJAm7CbH'
  254. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  255. logstore = 'request-log'
  256. client = LogClient(endpoint, accessKeyId, accessKey)
  257. project = 'wqsd-longvideoapi'
  258. topic = ""
  259. start_time = int(time.time())
  260. end_time = start_time - 60
  261. # url = '/longvideoapi/user/idolsUpdated'
  262. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  263. "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)
  264. try:
  265. res = client.get_logs(req)
  266. except Exception as e:
  267. avgs = 0
  268. return res
  269. def count_avg_max(appType):
  270. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  271. accessKeyId = 'LTAIWYUujJAm7CbH'
  272. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  273. logstore = 'request-log'
  274. client = LogClient(endpoint, accessKeyId, accessKey)
  275. project = 'wqsd-longvideoapi'
  276. topic = ""
  277. start_time = int(time.time())
  278. end_time = start_time - (60*15)
  279. # url = '/longvideoapi/user/idolsUpdated'
  280. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  281. "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)
  282. try:
  283. res = client.get_logs(req)
  284. except Exception as e:
  285. avgs = 0
  286. return res
  287. def count_rt_less_time_count(appType, than, less):
  288. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  289. accessKeyId = 'LTAIWYUujJAm7CbH'
  290. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  291. logstore = 'request-log'
  292. client = LogClient(endpoint, accessKeyId, accessKey)
  293. project = 'wqsd-longvideoapi'
  294. topic = ""
  295. start_time = int(time.time())
  296. end_time = start_time - 60
  297. # url = '/longvideoapi/user/idolsUpdated'
  298. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  299. "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)
  300. try:
  301. res = client.get_logs(req)
  302. except Exception as e:
  303. print(e)
  304. return res
  305. def error_cnt(appType):
  306. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  307. accessKeyId = 'LTAIWYUujJAm7CbH'
  308. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  309. logstore = 'request-log'
  310. client = LogClient(endpoint, accessKeyId, accessKey)
  311. project = 'wqsd-longvideoapi'
  312. topic = ""
  313. start_time = int(time.time())
  314. end_time = start_time - 60
  315. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  316. "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)
  317. try:
  318. res = client.get_logs(req)
  319. except Exception as e:
  320. print(e)
  321. return res
  322. def app_openapi_qps_avgtime_count():
  323. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  324. accessKeyId = 'LTAIWYUujJAm7CbH'
  325. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  326. logstore = 'request-log'
  327. client = LogClient(endpoint, accessKeyId, accessKey)
  328. project = 'wqsd-longvideoapi'
  329. topic = ""
  330. start_time = int(time.time())
  331. end_time = start_time - 60
  332. url = '/longvideoapi/openapi/video/distribute/category/videoList/v2'
  333. req = GetLogsRequest(project, logstore, end_time, start_time, topic,
  334. "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)
  335. try:
  336. res = client.get_logs(req)
  337. except Exception as e:
  338. avgs = 0
  339. return res,url
  340. def produce_video_data():
  341. start_time = (int(time.strftime("%Y%m%d", time.localtime()))) * 1000000000000000
  342. end_time = (int(time.strftime("%Y%m%d", time.localtime())) + 1) * 1000000000000000
  343. # start_time = (int(datetime.strftime("%Y%m%d",datetime.date.today()))
  344. print(start_time, end_time)
  345. sum_sql = ("select count(*) as totalCount "
  346. "from produce_video_project t1 "
  347. " where t1.project_id > %s and t1.project_id < %s and t1.app_type not in (1,13,15) "% (start_time,end_time)
  348. )
  349. res = db_query(sum_sql)
  350. return
  351. def update_request_url_list():
  352. HOST = 'rm-bp1k5853td1r25g3n690.mysql.rds.aliyuncs.com'
  353. PORT = '3306'
  354. DATABASE = 'devops'
  355. USERNAME = 'devops'
  356. PASSWORD = 'devops@123456'
  357. conn = pymysql.connect(host=HOST, user=USERNAME, password=PASSWORD, database=DATABASE, charset="utf8")
  358. cursor = conn.cursor()
  359. print("5m定时任务开始")
  360. appType = ['0', '4', '5', '6', '12', '15']
  361. for index in range(len(appType)):
  362. type = appType[index]
  363. res = count_avg_max(type)
  364. for i in range(len(res.body)):
  365. url = res.body[i]["requestUri"]
  366. cnt = res.body[i]["cnt"]
  367. max_time = res.body[i]["max_time"]
  368. avg_time = res.body[i]["avg_time"]
  369. sql = "UPDATE `reuqest_url_list` set `qps`=%s, `max_time`=%s, `avg_time`=%s WHERE `request_url` ='%s' and `apptype`=%s" % (
  370. cnt, max_time, avg_time, url, type)
  371. cursor.execute(sql)
  372. conn.commit()
  373. for i in range(len(res.body)):
  374. url = res.body[i]["requestUri"]
  375. cnt = res.body[i]["cnt"]
  376. sql = "UPDATE `reuqest_url_list` set `rt_1`=%s WHERE `request_url` ='%s' and `apptype`=%s" % (
  377. cnt, url, type)
  378. cursor.execute(sql)
  379. conn.commit()
  380. res = count_rt_less_time_count(type, 200, 500)
  381. for i in range(len(res.body)):
  382. url = res.body[i]["requestUri"]
  383. cnt = res.body[i]["cnt"]
  384. sql = "UPDATE `reuqest_url_list` set `rt_2`=%s WHERE `request_url` ='%s' and `apptype`=%s" % (
  385. cnt, url, type)
  386. cursor.execute(sql)
  387. conn.commit()
  388. res = count_rt_less_time_count(type, 500, 1000)
  389. for i in range(len(res.body)):
  390. url = res.body[i]["requestUri"]
  391. cnt = res.body[i]["cnt"]
  392. sql = "UPDATE `reuqest_url_list` set `rt_3`=%s WHERE `request_url` ='%s' and `apptype`=%s" % (
  393. cnt, url, type)
  394. cursor.execute(sql)
  395. conn.commit()
  396. res = count_rt_less_time_count(type, 1000, 10000)
  397. for i in range(len(res.body)):
  398. url = res.body[i]["requestUri"]
  399. cnt = res.body[i]["cnt"]
  400. sql = "UPDATE `reuqest_url_list` set `rt_4`=%s WHERE `request_url` ='%s' and `apptype`=%s" % (
  401. cnt, url, type)
  402. cursor.execute(sql)
  403. conn.commit()
  404. def produce_video_task_cnt():
  405. start_time = int(time.strftime("%Y%m%d", time.localtime())) * 1000000000000000
  406. end_time = int(time.strftime("%Y%m%d%H%M", time.localtime())) * 100000000000
  407. query_sql = ("select count(*) as totalCount,"
  408. "sum(case when produce_status in (5,6,7,8) then 1 else 0 end) as successCount,"
  409. "sum(case when produce_status = 99 then 1 else 0 end) as failCount , "
  410. "sum(case when produce_status in(0,1,2,3,4) then 1 else 0 end) as processingCount,"
  411. "sum(case when produce_status in(5,6,7,8) and (rate < 0.5 or rate is null) then 1 else 0 end) processingCount1,"
  412. "sum(case when produce_status in(5,6,7,8) and rate >= 0.5 and rate < 0.7 then 1 else 0 end) processingCount2 ,"
  413. "sum(case when produce_status in(5,6,7,8) and rate >= 0.7 and rate < 1 then 1 else 0 end) processingCount3 ,"
  414. "sum(case when produce_status in(5,6,7,8) and rate >= 1 and rate < 1.5 then 1 else 0 end) processingCount4 ,"
  415. "sum(case when produce_status in(5,6,7,8) and rate >= 1.5 and rate < 2 then 2 else 0 end) processingCount5 ,"
  416. "sum(case when produce_status in(5,6,7,8) and rate >2 then 1 else 0 end) processingCount6 from "
  417. "(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 "
  418. "left join produce_video_project_connect_time t2 on t1.project_id = t2.project_id "
  419. "where t1.project_id > %s and t1.project_id < %s and t1.app_type not in (1,13,15)) s1 " %(start_time ,end_time)
  420. )
  421. res = db_query(query_sql)
  422. return res
  423. def produce_video_ratio_cnt():
  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. start_time = int((date.today() + timedelta(days=-1)).strftime("%Y%m%d")) * 1000000000000000
  432. end_time = int(date.today().strftime("%Y%m%d")) * 1000000000000000
  433. # end_time = int((date.today() + timedelta(days=0)).strftime("%Y%m%d")) * 1000000000000000
  434. sql = ("select count(*) as totalCount, "
  435. "sum(case when rate < 0.5 then 1 else 0 end) as r1,"
  436. "sum(case when (rate >= 0.5 and rate < 0.7) then 1 else 0 end) as r2,"
  437. "sum(case when (rate >= 0.7 and rate < 1) then 1 else 0 end) as r3,"
  438. "sum(case when (rate >= 1 and rate < 1.5) then 1 else 0 end) as r4,"
  439. "sum(case when (rate >= 1.5 and rate < 2) then 1 else 0 end) as r5,"
  440. "sum(case when rate >= 2 then 1 else 0 end) as r6 from "
  441. "(select project_id, round((video_duration/1000) / (produce_done_timestamp - submit_timestamp),1) as rate from "
  442. "(select project_id, draftbox_id,video_duration,submit_timestamp,produce_done_timestamp from "
  443. "(select project_id, draftbox_id,video_duration,submit_timestamp,produce_done_timestamp from "
  444. "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)
  445. )
  446. print(sql)
  447. y_date = (date.today() + timedelta(days=-1)).strftime("%Y%m%d")
  448. res = db_query(sql)
  449. if res[0]:
  450. cnt = res[0]
  451. else:
  452. cnt = 0
  453. if res[1]:
  454. r1 = res[1]
  455. else:
  456. r1 = 0
  457. if res[2]:
  458. r2 = res[2]
  459. else:
  460. r2 = 0
  461. if res[3]:
  462. r3 = res[3]
  463. else:
  464. r3 = 0
  465. if res[4]:
  466. r4 = res[4]
  467. else:
  468. r4 = 0
  469. if res[5]:
  470. r5 = res[5]
  471. else:
  472. r5 = 0
  473. if res[6]:
  474. r6 = res[6]
  475. else:
  476. r6 = 0
  477. 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)
  478. )
  479. cursor.execute(sql)
  480. conn.commit()
  481. if __name__ == '__main__':
  482. produce_video_ratio_cnt()