upload.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import json
  4. from threading import Lock
  5. import logging
  6. import datetime
  7. from os import path
  8. import time
  9. import shutil
  10. class Handle:
  11. def __init__(self, max_length, temp_file, official_dir, interval=5 * 60):
  12. """
  13. :param max_length: Every 1000 rows of data are deposited in an official file.
  14. :param temp_file: Temporary file path.
  15. :param official_dir: Official folder Path.
  16. :param interval: Put temporary files into official files to upload at regular intervals.
  17. """
  18. self.lock = Lock()
  19. # Data results collected by multiple plug-ins need to be queued to write to files.
  20. # The Q is the queue.
  21. self.Q = []
  22. self.max_item_length = max_length
  23. self.temp_file = temp_file
  24. self.official_dir = official_dir
  25. self.interval = interval
  26. self.current_row = 0
  27. def add_task(self, content):
  28. if not isinstance(content, dict):
  29. logging.warning('[HANDLE] add task content: %s but type is not dict', content)
  30. return
  31. self.lock.acquire()
  32. content = self.content_format(content)
  33. self.Q.append(content)
  34. self.lock.release()
  35. @staticmethod
  36. def content_format(content):
  37. if not content.__contains__('dev_ip'):
  38. content['dev_ip'] = ''
  39. if not content.__contains__('expr'):
  40. content['expr'] = 1
  41. if not content.__contains__('dev_id'):
  42. content['dev_id'] = ''
  43. if not content.__contains__('port'):
  44. content['port'] = ''
  45. if not content.__contains__('type'):
  46. content['type'] = ''
  47. if not content.__contains__('schema'):
  48. content['schema'] = ''
  49. if not content.__contains__('login_name'):
  50. content['login_name'] = ''
  51. if not content.__contains__('pwd'):
  52. content['pwd'] = ''
  53. if not content.__contains__('kpi'):
  54. content['kpi'] = {}
  55. return content
  56. def to_file(self, name):
  57. try:
  58. shutil.copy(self.temp_file, name)
  59. except Exception as e:
  60. return e
  61. return None
  62. def listen(self):
  63. temp_file_mode = 'a+'
  64. temp_file_ptr = self.create_temp_file(temp_file_mode)
  65. beg = int(datetime.datetime.now().timestamp())
  66. end = beg
  67. while True:
  68. self.sleep()
  69. end = int(datetime.datetime.now().timestamp())
  70. self.lock.acquire()
  71. q = self.Q
  72. self.lock.release()
  73. if len(q) < 1:
  74. continue
  75. # Open temp file ptr. It might get None again, so execute continue one more time.
  76. if temp_file_ptr is None or temp_file_ptr.closed:
  77. temp_file_ptr = self.create_temp_file(temp_file_mode)
  78. continue
  79. for item in q:
  80. item_value = ''
  81. try:
  82. item_value = json.dumps(item)
  83. temp_file_ptr.write(item_value)
  84. self.current_row += 1
  85. except Exception as e:
  86. logging.error("[HANDLE] write item(%s) error :%s", item_value, e)
  87. logging.debug('[HANDLE] listen and ')
  88. # If the currently recorded data line is greater than or equal to the largest data line,
  89. # the temporary file is written to the official file.
  90. # If the file has not been saved for more than three minutes, and the temporary file is
  91. # not empty, an official file is also saved.
  92. official_file = ''
  93. if self.current_row >= self.max_item_length or (end - beg >= 3 * 60 and self.current_row > 0):
  94. try:
  95. now = int(datetime.datetime.now().timestamp() * 1000)
  96. official_file = path.join(self.official_dir, str(now) + '.tok')
  97. msg = self.to_file(official_file)
  98. if msg is not None:
  99. logging.error('[HANDLE] to official file(%s) error: %s', official_file, msg)
  100. temp_file_mode = 'a+'
  101. continue
  102. temp_file_ptr.close()
  103. temp_file_mode = 'w+'
  104. self.current_row = 0
  105. beg = int(datetime.datetime.now().timestamp())
  106. except Exception as e:
  107. logging.error('[HANDLE] copy temp file(%s) to official file(%s) error: %s',
  108. self.temp_file, official_file, e)
  109. def create_temp_file(self, mode):
  110. try:
  111. f = open(self.temp_file, mode=mode)
  112. return f
  113. except Exception as e:
  114. logging.error('[HANDLE] create temp file(%s) error: %s', self.temp_file, e)
  115. return None
  116. @staticmethod
  117. def sleep():
  118. time.sleep(1)
  119. class Uploader:
  120. def __init__(self):
  121. pass