You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

kernel_build_server.py 4.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """kernel build server"""
  16. import os
  17. import time
  18. class Messager:
  19. '''Messager'''
  20. def __init__(self, fdin, fdout):
  21. self.fdin = fdin
  22. self.fdout = fdout
  23. self.fin = os.fdopen(fdin, "r")
  24. self.fout = os.fdopen(fdout, "w")
  25. self.message = ''
  26. def __del__(self):
  27. os.close(self.fdin)
  28. os.close(self.fdout)
  29. def get_message(self):
  30. """
  31. Get message from remote
  32. Returns:
  33. message
  34. """
  35. try:
  36. # Not read by input() anymore
  37. res = self.fin.readline()
  38. if not res:
  39. logger.debug('[TRACE]', "read nothing...")
  40. self.exit()
  41. if res[len(res) - 1] == '\n':
  42. res = res[0:len(res)-1]
  43. self.message = res
  44. logger.debug('[IN]', self.message)
  45. except (EOFError, KeyboardInterrupt):
  46. self.exit()
  47. finally:
  48. pass
  49. if self.message == '' or self.message == 'FINISH':
  50. self.send_ack()
  51. self.exit()
  52. return self.message
  53. def send_res(self, res, keep_format=True):
  54. """
  55. Send result to remote
  56. Args:
  57. keep_format: True or False
  58. """
  59. logger.debug('[OUT]', str(res))
  60. if keep_format:
  61. res_str = str(res).replace('\n', '[LF]').replace('\r', '[CR]').replace(' ', '[SP]')
  62. else:
  63. res_str = str(res).replace('\n', '').replace('\r', '').replace(' ', '')
  64. tag = '[~]' # The same as client kTAG
  65. # Not write by print(tag + res_str, flush=True) any more
  66. try:
  67. self.fout.write(tag + res_str + "\n")
  68. self.fout.flush()
  69. except BrokenPipeError as err:
  70. logger.info('[TRACE]', 'Write, ' + str(err))
  71. self.exit()
  72. finally:
  73. pass
  74. def send_ack(self, success=True):
  75. """
  76. Send ack to remote
  77. Args:
  78. success: True or False
  79. """
  80. if success:
  81. self.send_res('ACK')
  82. else:
  83. self.send_res('ERR')
  84. def loop(self):
  85. """
  86. Messaging loop
  87. """
  88. while True:
  89. self.handle()
  90. def run(self):
  91. self.loop()
  92. def handle(self):
  93. """
  94. A interface communicates with remote.
  95. Note:
  96. All subclasses should override this interface.
  97. """
  98. raise NotImplementedError
  99. def exit(self):
  100. """
  101. A interface handles the procedure before exit.
  102. Note:
  103. All subclasses should override this interface.
  104. """
  105. raise NotImplementedError
  106. class Logger:
  107. """
  108. Replace dummy 'logger' to output log as below:
  109. logger = Logger(0, True, "remote_kernel_build_" + time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime()) + ".log")
  110. """
  111. def __init__(self, level=1, dumpfile=False, filename='Logger.log'):
  112. """
  113. Args:
  114. level: 0 for debug and info, 1 for info
  115. dumpfile: if dump log into file
  116. """
  117. self.level = level
  118. self.dumpfile = dumpfile
  119. if self.dumpfile:
  120. self.log = open(filename, "a")
  121. def write(self, msg):
  122. self.log.write(msg)
  123. self.flush()
  124. def writeline(self, tag, msg):
  125. prefix = tag + ' REMOTE(' + str(os.getpid()) + ',python)'
  126. line = prefix + '\t' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ':\t' + msg
  127. print(line, flush=True)
  128. if self.dumpfile:
  129. self.write(line + '\n')
  130. def debug(self, tag, msg):
  131. if self.level == 0:
  132. self.writeline('[DEBUG]' + tag, msg)
  133. def info(self, tag, msg):
  134. self.writeline('[INFO]' + tag, msg)
  135. def flush(self):
  136. self.log.flush()
  137. class DummyLogger:
  138. """DummyLogger"""
  139. def __init__(self):
  140. pass
  141. def debug(self, tag, msg):
  142. pass
  143. def info(self, tag, msg):
  144. pass
  145. logger = DummyLogger()
  146. def get_logger():
  147. return logger