utils.py 19 KB

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