appclean.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. #!/usr/bin/python3
  2. # --*-- coding:utf-8 --*--
  3. import requests, json, os, time
  4. import pymysql
  5. import time, datetime
  6. import logging
  7. import logging.handlers
  8. logger = logging.getLogger('/root/xcloudclean/app_info.log')
  9. logger.setLevel(logging.DEBUG)
  10. rf_handler = logging.handlers.TimedRotatingFileHandler('/root/xcloudclean/app_clear.log', when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
  11. rf_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
  12. f_handler = logging.FileHandler('/root/xcloudclean/app_error.log')
  13. f_handler.setLevel(logging.ERROR)
  14. f_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s"))
  15. logger.addHandler(rf_handler)
  16. logger.addHandler(f_handler)
  17. # logging.basicConfig(filename='./clear_info.log', level=logging.INFO)
  18. CLEAR_ID = []
  19. CLEAN_ERROR_ID = []
  20. CLEAN_SUCCESS_ID = []
  21. CLEAN_PENDING_ID = []
  22. STRATE_TIME = datetime.datetime.now()
  23. # clear_status : 1.清理完成 2.待清理 3.清理中 4.清理失败
  24. def get_data():
  25. conn1 = pymysql.connect(
  26. host='10.99.1.85',
  27. port=3306,
  28. user='gluttony',
  29. passwd='gluttony',
  30. db='awsregistry',
  31. charset='utf8mb4')
  32. cs1 = conn1.cursor()
  33. select_sql = "SELECT id FROM r_aws_account_info WHERE clear_status=2;"
  34. cs1.execute(select_sql)
  35. response = cs1.fetchall()
  36. cs1.close()
  37. conn1.close()
  38. yield response
  39. def updata_db(info_sql):
  40. conn2 = pymysql.connect(
  41. host='10.99.1.85',
  42. port=3306,
  43. user='gluttony',
  44. passwd='gluttony',
  45. db='awsregistry',
  46. charset='utf8mb4')
  47. cs2 = conn2.cursor()
  48. try:
  49. cs2.execute(info_sql)
  50. conn2.commit()
  51. logger.info(f" Exec_SQL_Syntax: {info_sql}")
  52. except Exception as e:
  53. conn2.rollback()
  54. logger.error(f" Exec_SQL_Syntax_ERROR: {e}\t,{info_sql}")
  55. finally:
  56. conn2.close()
  57. def send_email(error_id):
  58. import smtplib
  59. from email.mime.text import MIMEText
  60. from email.header import Header
  61. mail_host="smtp.qiye.163.com"
  62. mail_user="cloud@cstor.cn"
  63. mail_pass="Cstor0820"
  64. sender = 'cloud@cstor.cn'
  65. receivers = ['xclouds@qq.com','xiechao@cstor.cn',
  66. 'suzeyue@cstor.cn','taozhongyuan@cstor.cn','panhaonan@cstor.cn',
  67. 'xuchong@cstor.cn','2214395275@qq.com']
  68. # receivers = ['xclouds@qq.com']
  69. message = MIMEText('gluttony.cstor.cn Resource 清理异常......\n\n请及时处理。', 'plain', 'utf-8')
  70. message['From'] = Header("gluttony", 'utf-8')
  71. message['To'] = Header("平台部云计算项目组", 'utf-8')
  72. subject = f'AWS清理失败(ACCOUNT ID: {error_id})'
  73. message['Subject'] = Header(subject, 'utf-8')
  74. try:
  75. smtpObj = smtplib.SMTP()
  76. smtpObj.connect(mail_host, 25)
  77. smtpObj.login(mail_user,mail_pass)
  78. smtpObj.sendmail(sender, receivers, message.as_string())
  79. logger.info("邮件发送成功")
  80. except smtplib.SMTPException as e:
  81. logger.error(f"Error: 无法发送邮件\t {e}")
  82. def auth_post():
  83. url_auth = "http://localhost:8000/api/user/auth"
  84. auth_body = {"username": "admin", "password": "admin"}
  85. auth_headers = {
  86. "Content-Type": "application/json, charset=UTF-8"
  87. }
  88. auth_original = requests.request('post', url_auth, json=auth_body, headers=auth_headers)
  89. access_token_original = auth_original.json()
  90. access_token = access_token_original['access_token']
  91. return access_token
  92. def get_status():
  93. CLEAR_ID_orginal = get_data()
  94. for i in CLEAR_ID_orginal:
  95. id_list = list(i)
  96. for a in id_list:
  97. b = list(a)
  98. for c in b:
  99. CLEAR_ID.append(c)
  100. return CLEAR_ID
  101. def clear_post():
  102. url_clear = "http://localhost:8000/api/resource/clear/range"
  103. data_headers = {
  104. 'Content-Type': 'application/json',
  105. 'Authorization': 'Bearer ' + auth_post()
  106. }
  107. json_id = {'ID': CLEAR_ID}
  108. data_original = requests.post(url_clear, json=json_id, headers=data_headers)
  109. try:
  110. if "message" in data_original.text:
  111. raise TypeError(data_original.text)
  112. except TypeError as e:
  113. logger.error(f" ERROR {e}")
  114. logger.info(f" Clear ID = {json_id}")
  115. logger.info(f" HTTP Response {data_original.text}")
  116. # return data_original
  117. def init_post(init_id):
  118. init_headers = {'content-type': 'application/x-www-form-urlencoded'}
  119. init_url = "http://10.99.1.85:8081/account/init"
  120. params = {"account_ids":init_id}
  121. resp = requests.post(init_url, data=params, headers=init_headers)
  122. logger.info(f"init_id: {init_id}, Status:{resp.text}")
  123. def dbs_pending_status(sql_clear_id):
  124. id_tup = tuple(sql_clear_id)
  125. if len(id_tup) == 1:
  126. sql_old = f"UPDATE r_aws_account_info SET clear_status=3 WHERE clear_status=2 AND id IN {id_tup};"
  127. sql_exec = sql_old.replace(",", "")
  128. updata_db(sql_exec)
  129. else:
  130. sql_exec = f"UPDATE r_aws_account_info SET clear_status=3 WHERE clear_status=2 AND id IN {id_tup};"
  131. updata_db(sql_exec)
  132. def updata_db_pending(sql_clear_id):
  133. sql_old = f"UPDATE r_aws_account_info SET clear_status=3 WHERE clear_status=2 AND id IN ({sql_clear_id});"
  134. updata_db(sql_old)
  135. def updata_db_success(sql_clear_id):
  136. sql_old = f"UPDATE r_aws_account_info SET clear_status=1 WHERE clear_status=3 AND id IN ({sql_clear_id});"
  137. updata_db(sql_old)
  138. def updata_db_error(sql_clear_id):
  139. # id_tup = tuple(sql_clear_id)
  140. # if len(id_tup) == 1:
  141. sql_old = f"UPDATE r_aws_account_info SET clear_status=4 WHERE clear_status=3 AND id IN ({sql_clear_id});"
  142. # sql_exec = sql_old.replace(",", "")
  143. updata_db(sql_old)
  144. # else:
  145. # sql_exec = f"UPDATE r_aws_account_info SET clear_status=4 WHERE clear_status=3 AND id IN {id_tup};"
  146. # updata_db(sql_exec)
  147. CLEAN_STATUS_GET_HEADER = {
  148. 'Content-Type': 'application/json',
  149. 'Authorization': 'Bearer ' + auth_post()}
  150. def clean_status_get(r_id):
  151. status_url = f"http://127.0.0.1:8000/api/status/account/state/{r_id}"
  152. resp = requests.get(status_url,headers=CLEAN_STATUS_GET_HEADER)
  153. logger.info(f"Clean_Status:{resp.text}")
  154. if "SUCCESS" in json.loads(resp.text)["account_clean_status"]:
  155. # {"account_clean_status":"SUCCESS","id":"8","start_time":"2021-01-06 16:02:00.018024","state":"200"}
  156. CLEAN_SUCCESS_ID.append(r_id)
  157. updata_db_success(r_id)
  158. if r_id in CLEAN_PENDING_ID:
  159. CLEAN_PENDING_ID.remove(r_id)
  160. elif "PENDING" in json.loads(resp.text)["account_clean_status"]:
  161. # {"account_clean_status":"PENDING","id":"102","start_time":"2021-01-06 17:42:10.059127"}
  162. if r_id in CLEAN_PENDING_ID:
  163. pass
  164. else:
  165. CLEAN_PENDING_ID.append(r_id)
  166. else:
  167. CLEAN_ERROR_ID.append(r_id)
  168. updata_db_error(r_id)
  169. if r_id in CLEAN_PENDING_ID:
  170. CLEAN_PENDING_ID.remove(r_id)
  171. def while_pending_status(pending_id):
  172. while len(CLEAN_PENDING_ID) > 0:
  173. time.sleep(180)
  174. current_time = datetime.datetime.now()
  175. process_time = (current_time - STRATE_TIME).seconds
  176. if process_time < 2400:
  177. for i in pending_id:
  178. clean_status_get(i)
  179. elif process_time > 2400:
  180. for err_id in pending_id:
  181. CLEAN_ERROR_ID.append(err_id)
  182. CLEAN_PENDING_ID.remove(err_id)
  183. # updata_db_error(err_id)
  184. # return
  185. def start_now():
  186. global CLEAR_ID
  187. global CLEAN_ERROR_ID
  188. global CLEAN_SUCCESS_ID
  189. global CLEAN_PENDING_ID
  190. get_status()
  191. logger.info(f" Start: NOW")
  192. logger.info(f" Id: {CLEAR_ID}")
  193. if CLEAR_ID == []:
  194. logger.info("ID: None ")
  195. logger.info("None exit cleanapp")
  196. os._exit(0)
  197. else:
  198. clear_post()
  199. # clear_status : 1.清理完成 2.待清理 3.清理中 4.清理失败
  200. dbs_pending_status(CLEAR_ID) # status 2 --> 3
  201. time.sleep(600)
  202. for i in CLEAR_ID:
  203. clean_status_get(i)
  204. if CLEAN_PENDING_ID == [] and CLEAN_ERROR_ID == []:
  205. pass
  206. elif CLEAN_PENDING_ID != []:
  207. while_pending_status(CLEAN_PENDING_ID)
  208. elif CLEAN_ERROR_ID != []:
  209. send_email(CLEAN_ERROR_ID)
  210. for i in CLEAN_SUCCESS_ID:
  211. init_post(i)
  212. logger.info(f"clean SUCCESS ID: {CLEAN_SUCCESS_ID}")
  213. logger.info(f"clean PENDING ID: {CLEAN_PENDING_ID}")
  214. if CLEAN_ERROR_ID == []:
  215. pass
  216. else:
  217. logger.error(f"clean ERROR ID: {CLEAN_ERROR_ID}")
  218. logger.info("End: end")
  219. logger.info("\n")
  220. if __name__ == '__main__':
  221. start_now()ls