upload.py 5.3 KB

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