Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

96 lines
3.9KB

  1. # -*- coding: utf-8 -*-
  2. import sys
  3. from multiprocessing import Queue
  4. from threading import Thread
  5. from time import sleep
  6. from traceback import format_exc
  7. from loguru import logger
  8. from bean.Feedback import upload_http_result
  9. from common.Constant import get_task_record, get_share_queue
  10. from concurrency.http.HttpFeedbackThread import HttpFeedbackThread
  11. from concurrency.http.HttpUploadFileProcess import HttpUploadFileProcess
  12. from enums.ExceptionEnum import UploadStrExceptionType
  13. from enums.StatusEnum import UploadTaskStatusType
  14. from exception.CustomerException import ServiceException
  15. from util.QueUtil import get_no_block_queue
  16. class HttpServiceImpl:
  17. __slots__ = ()
  18. def __init__(self, service_config):
  19. service_thread = Thread(target=self.start_service, args=(service_config,))
  20. service_thread.setDaemon(True)
  21. service_thread.start()
  22. @staticmethod
  23. def start_service(service_config):
  24. fb_queue = Queue()
  25. task, msg_queue = get_task_record(), get_share_queue()
  26. handle_method = {
  27. "upload": lambda x, y, z, h: handle_upload(x, y, z, h)
  28. }
  29. feedbackThread = None
  30. while True:
  31. try:
  32. if task["upload"] is not None and not task["upload"].is_alive():
  33. task["upload"] = None
  34. feedbackThread = start_feedback_thread(feedbackThread, fb_queue)
  35. message = get_no_block_queue(msg_queue)
  36. if message is not None and isinstance(message, tuple) and len(message) == 2:
  37. if handle_method.get(message[0]) is not None:
  38. handle_method[message[0]](message[1], service_config, task, fb_queue)
  39. else:
  40. sleep(1)
  41. except Exception:
  42. logger.error("服务异常: {}", format_exc())
  43. def handle_upload(msg, service_config, task, fb_queue):
  44. try:
  45. command = msg["command"]
  46. if 'start' == command:
  47. if task["upload"] is not None:
  48. logger.warning("上传任务已存在!!!")
  49. upload_http_result(fb_queue, msg["callback_url"], msg["request_id"],
  50. errorCode=UploadStrExceptionType.UPLOAD_TASK_IS_AREADLY.value[0],
  51. errorMsg=UploadStrExceptionType.UPLOAD_TASK_IS_AREADLY.value[1],
  52. status=UploadTaskStatusType.FAILED.value[0])
  53. return
  54. upload_p = HttpUploadFileProcess(fb_queue, service_config, msg["callback_url"], msg["request_id"])
  55. upload_p.start()
  56. task["upload"] = upload_p
  57. elif 'stop' == command:
  58. if task["upload"] is None:
  59. logger.error("任务不存在, 任务无法停止!")
  60. return
  61. task["upload"].sendEvent({"command": "stop"})
  62. except ServiceException as s:
  63. logger.error("文件上传请求异常: {}", s.msg)
  64. upload_http_result(fb_queue, msg["callback_url"], msg["request_id"],
  65. errorCode=s.code,
  66. errorMsg=s.msg,
  67. status=UploadTaskStatusType.FAILED.value[0])
  68. except Exception:
  69. logger.error("消息处理异常: {}", format_exc())
  70. upload_http_result(fb_queue, msg["callback_url"], msg["request_id"],
  71. errorCode=UploadStrExceptionType.SERVICE_INNER_EXCEPTION.value[0],
  72. errorMsg=UploadStrExceptionType.SERVICE_INNER_EXCEPTION.value[1],
  73. status=UploadTaskStatusType.FAILED.value[0])
  74. finally:
  75. del msg
  76. def start_feedback_thread(feedbackThread, fb_queue):
  77. if feedbackThread is None:
  78. feedbackThread = HttpFeedbackThread(fb_queue)
  79. feedbackThread.setDaemon(True)
  80. feedbackThread.start()
  81. else:
  82. if not feedbackThread.is_alive():
  83. logger.error("反馈线程异常停止! 开始终止程序!")
  84. sys.exit()
  85. return feedbackThread