client.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. # Copyright 2019 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. # This class contains the basic functionality needed to run any interpreter
  12. # or an interpreter-based tool.
  13. from .common import CMakeException, CMakeConfiguration, CMakeBuildFile
  14. from .executor import CMakeExecutor
  15. from ..environment import Environment
  16. from ..mesonlib import MachineChoice
  17. from .. import mlog
  18. from contextlib import contextmanager
  19. from subprocess import Popen, PIPE, TimeoutExpired
  20. import typing as T
  21. import json
  22. import os
  23. CMAKE_SERVER_BEGIN_STR = '[== "CMake Server" ==['
  24. CMAKE_SERVER_END_STR = ']== "CMake Server" ==]'
  25. CMAKE_MESSAGE_TYPES = {
  26. 'error': ['cookie', 'errorMessage'],
  27. 'hello': ['supportedProtocolVersions'],
  28. 'message': ['cookie', 'message'],
  29. 'progress': ['cookie'],
  30. 'reply': ['cookie', 'inReplyTo'],
  31. 'signal': ['cookie', 'name'],
  32. }
  33. CMAKE_REPLY_TYPES = {
  34. 'handshake': [],
  35. 'configure': [],
  36. 'compute': [],
  37. 'cmakeInputs': ['buildFiles', 'cmakeRootDirectory', 'sourceDirectory'],
  38. 'codemodel': ['configurations']
  39. }
  40. # Base CMake server message classes
  41. class MessageBase:
  42. def __init__(self, msg_type: str, cookie: str):
  43. self.type = msg_type
  44. self.cookie = cookie
  45. def to_dict(self) -> dict:
  46. return {'type': self.type, 'cookie': self.cookie}
  47. def log(self) -> None:
  48. mlog.warning('CMake server message of type', mlog.bold(type(self).__name__), 'has no log function')
  49. class RequestBase(MessageBase):
  50. cookie_counter = 0
  51. def __init__(self, msg_type: str):
  52. super().__init__(msg_type, self.gen_cookie())
  53. @staticmethod
  54. def gen_cookie():
  55. RequestBase.cookie_counter += 1
  56. return 'meson_{}'.format(RequestBase.cookie_counter)
  57. class ReplyBase(MessageBase):
  58. def __init__(self, cookie: str, in_reply_to: str):
  59. super().__init__('reply', cookie)
  60. self.in_reply_to = in_reply_to
  61. class SignalBase(MessageBase):
  62. def __init__(self, cookie: str, signal_name: str):
  63. super().__init__('signal', cookie)
  64. self.signal_name = signal_name
  65. def log(self) -> None:
  66. mlog.log(mlog.bold('CMake signal:'), mlog.yellow(self.signal_name))
  67. # Special Message classes
  68. class Error(MessageBase):
  69. def __init__(self, cookie: str, message: str):
  70. super().__init__('error', cookie)
  71. self.message = message
  72. def log(self) -> None:
  73. mlog.error(mlog.bold('CMake server error:'), mlog.red(self.message))
  74. class Message(MessageBase):
  75. def __init__(self, cookie: str, message: str):
  76. super().__init__('message', cookie)
  77. self.message = message
  78. def log(self) -> None:
  79. #mlog.log(mlog.bold('CMake:'), self.message)
  80. pass
  81. class Progress(MessageBase):
  82. def __init__(self, cookie: str):
  83. super().__init__('progress', cookie)
  84. def log(self) -> None:
  85. pass
  86. class MessageHello(MessageBase):
  87. def __init__(self, supported_protocol_versions: T.List[dict]):
  88. super().__init__('hello', '')
  89. self.supported_protocol_versions = supported_protocol_versions
  90. def supports(self, major: int, minor: T.Optional[int] = None) -> bool:
  91. for i in self.supported_protocol_versions:
  92. if major == i['major']:
  93. if minor is None or minor == i['minor']:
  94. return True
  95. return False
  96. # Request classes
  97. class RequestHandShake(RequestBase):
  98. def __init__(self, src_dir: str, build_dir: str, generator: str, vers_major: int, vers_minor: T.Optional[int] = None):
  99. super().__init__('handshake')
  100. self.src_dir = src_dir
  101. self.build_dir = build_dir
  102. self.generator = generator
  103. self.vers_major = vers_major
  104. self.vers_minor = vers_minor
  105. def to_dict(self) -> dict:
  106. vers = {'major': self.vers_major}
  107. if self.vers_minor is not None:
  108. vers['minor'] = self.vers_minor
  109. # Old CMake versions (3.7) want '/' even on Windows
  110. src_list = os.path.normpath(self.src_dir).split(os.sep)
  111. bld_list = os.path.normpath(self.build_dir).split(os.sep)
  112. return {
  113. **super().to_dict(),
  114. 'sourceDirectory': '/'.join(src_list),
  115. 'buildDirectory': '/'.join(bld_list),
  116. 'generator': self.generator,
  117. 'protocolVersion': vers
  118. }
  119. class RequestConfigure(RequestBase):
  120. def __init__(self, args: T.Optional[T.List[str]] = None):
  121. super().__init__('configure')
  122. self.args = args
  123. def to_dict(self) -> dict:
  124. res = super().to_dict()
  125. if self.args:
  126. res['cacheArguments'] = self.args
  127. return res
  128. class RequestCompute(RequestBase):
  129. def __init__(self):
  130. super().__init__('compute')
  131. class RequestCMakeInputs(RequestBase):
  132. def __init__(self):
  133. super().__init__('cmakeInputs')
  134. class RequestCodeModel(RequestBase):
  135. def __init__(self):
  136. super().__init__('codemodel')
  137. # Reply classes
  138. class ReplyHandShake(ReplyBase):
  139. def __init__(self, cookie: str):
  140. super().__init__(cookie, 'handshake')
  141. class ReplyConfigure(ReplyBase):
  142. def __init__(self, cookie: str):
  143. super().__init__(cookie, 'configure')
  144. class ReplyCompute(ReplyBase):
  145. def __init__(self, cookie: str):
  146. super().__init__(cookie, 'compute')
  147. class ReplyCMakeInputs(ReplyBase):
  148. def __init__(self, cookie: str, cmake_root: str, src_dir: str, build_files: T.List[CMakeBuildFile]):
  149. super().__init__(cookie, 'cmakeInputs')
  150. self.cmake_root = cmake_root
  151. self.src_dir = src_dir
  152. self.build_files = build_files
  153. def log(self) -> None:
  154. mlog.log('CMake root: ', mlog.bold(self.cmake_root))
  155. mlog.log('Source dir: ', mlog.bold(self.src_dir))
  156. mlog.log('Build files:', mlog.bold(str(len(self.build_files))))
  157. with mlog.nested():
  158. for i in self.build_files:
  159. mlog.log(str(i))
  160. class ReplyCodeModel(ReplyBase):
  161. def __init__(self, data: dict):
  162. super().__init__(data['cookie'], 'codemodel')
  163. self.configs = []
  164. for i in data['configurations']:
  165. self.configs += [CMakeConfiguration(i)]
  166. def log(self) -> None:
  167. mlog.log('CMake code mode:')
  168. for idx, i in enumerate(self.configs):
  169. mlog.log('Configuration {}:'.format(idx))
  170. with mlog.nested():
  171. i.log()
  172. # Main client class
  173. class CMakeClient:
  174. def __init__(self, env: Environment):
  175. self.env = env
  176. self.proc = None
  177. self.type_map = {
  178. 'error': lambda data: Error(data['cookie'], data['errorMessage']),
  179. 'hello': lambda data: MessageHello(data['supportedProtocolVersions']),
  180. 'message': lambda data: Message(data['cookie'], data['message']),
  181. 'progress': lambda data: Progress(data['cookie']),
  182. 'reply': self.resolve_type_reply,
  183. 'signal': lambda data: SignalBase(data['cookie'], data['name'])
  184. }
  185. self.reply_map = {
  186. 'handshake': lambda data: ReplyHandShake(data['cookie']),
  187. 'configure': lambda data: ReplyConfigure(data['cookie']),
  188. 'compute': lambda data: ReplyCompute(data['cookie']),
  189. 'cmakeInputs': self.resolve_reply_cmakeInputs,
  190. 'codemodel': lambda data: ReplyCodeModel(data),
  191. }
  192. def readMessageRaw(self) -> dict:
  193. assert(self.proc is not None)
  194. rawData = []
  195. begin = False
  196. while self.proc.poll() is None:
  197. line = self.proc.stdout.readline()
  198. if not line:
  199. break
  200. line = line.decode('utf-8')
  201. line = line.strip()
  202. if begin and line == CMAKE_SERVER_END_STR:
  203. break # End of the message
  204. elif begin:
  205. rawData += [line]
  206. elif line == CMAKE_SERVER_BEGIN_STR:
  207. begin = True # Begin of the message
  208. if rawData:
  209. return json.loads('\n'.join(rawData))
  210. raise CMakeException('Failed to read data from the CMake server')
  211. def readMessage(self) -> MessageBase:
  212. raw_data = self.readMessageRaw()
  213. if 'type' not in raw_data:
  214. raise CMakeException('The "type" attribute is missing from the message')
  215. msg_type = raw_data['type']
  216. func = self.type_map.get(msg_type, None)
  217. if not func:
  218. raise CMakeException('Recieved unknown message type "{}"'.format(msg_type))
  219. for i in CMAKE_MESSAGE_TYPES[msg_type]:
  220. if i not in raw_data:
  221. raise CMakeException('Key "{}" is missing from CMake server message type {}'.format(i, msg_type))
  222. return func(raw_data)
  223. def writeMessage(self, msg: MessageBase) -> None:
  224. raw_data = '\n{}\n{}\n{}\n'.format(CMAKE_SERVER_BEGIN_STR, json.dumps(msg.to_dict(), indent=2), CMAKE_SERVER_END_STR)
  225. self.proc.stdin.write(raw_data.encode('ascii'))
  226. self.proc.stdin.flush()
  227. def query(self, request: RequestBase) -> MessageBase:
  228. self.writeMessage(request)
  229. while True:
  230. reply = self.readMessage()
  231. if reply.cookie == request.cookie and reply.type in ['reply', 'error']:
  232. return reply
  233. reply.log()
  234. def query_checked(self, request: RequestBase, message: str) -> ReplyBase:
  235. reply = self.query(request)
  236. h = mlog.green('SUCCEEDED') if reply.type == 'reply' else mlog.red('FAILED')
  237. mlog.log(message + ':', h)
  238. if reply.type != 'reply':
  239. reply.log()
  240. raise CMakeException('CMake server query failed')
  241. return reply
  242. def do_handshake(self, src_dir: str, build_dir: str, generator: str, vers_major: int, vers_minor: T.Optional[int] = None) -> None:
  243. # CMake prints the hello message on startup
  244. msg = self.readMessage()
  245. if not isinstance(msg, MessageHello):
  246. raise CMakeException('Recieved an unexpected message from the CMake server')
  247. request = RequestHandShake(src_dir, build_dir, generator, vers_major, vers_minor)
  248. self.query_checked(request, 'CMake server handshake')
  249. def resolve_type_reply(self, data: dict) -> ReplyBase:
  250. reply_type = data['inReplyTo']
  251. func = self.reply_map.get(reply_type, None)
  252. if not func:
  253. raise CMakeException('Recieved unknown reply type "{}"'.format(reply_type))
  254. for i in ['cookie'] + CMAKE_REPLY_TYPES[reply_type]:
  255. if i not in data:
  256. raise CMakeException('Key "{}" is missing from CMake server message type {}'.format(i, type))
  257. return func(data)
  258. def resolve_reply_cmakeInputs(self, data: dict) -> ReplyCMakeInputs:
  259. files = []
  260. for i in data['buildFiles']:
  261. for j in i['sources']:
  262. files += [CMakeBuildFile(j, i['isCMake'], i['isTemporary'])]
  263. return ReplyCMakeInputs(data['cookie'], data['cmakeRootDirectory'], data['sourceDirectory'], files)
  264. @contextmanager
  265. def connect(self):
  266. self.startup()
  267. try:
  268. yield
  269. finally:
  270. self.shutdown()
  271. def startup(self) -> None:
  272. if self.proc is not None:
  273. raise CMakeException('The CMake server was already started')
  274. for_machine = MachineChoice.HOST # TODO make parameter
  275. cmake_exe = CMakeExecutor(self.env, '>=3.7', for_machine)
  276. if not cmake_exe.found():
  277. raise CMakeException('Unable to find CMake')
  278. mlog.debug('Starting CMake server with CMake', mlog.bold(' '.join(cmake_exe.get_command())), 'version', mlog.cyan(cmake_exe.version()))
  279. self.proc = Popen(cmake_exe.get_command() + ['-E', 'server', '--experimental', '--debug'], stdin=PIPE, stdout=PIPE)
  280. def shutdown(self) -> None:
  281. if self.proc is None:
  282. return
  283. mlog.debug('Shutting down the CMake server')
  284. # Close the pipes to exit
  285. self.proc.stdin.close()
  286. self.proc.stdout.close()
  287. # Wait for CMake to finish
  288. try:
  289. self.proc.wait(timeout=2)
  290. except TimeoutExpired:
  291. # Terminate CMake if there is a timeout
  292. # terminate() may throw a platform specific exception if the process has already
  293. # terminated. This may be the case if there is a race condition (CMake exited after
  294. # the timeout but before the terminate() call). Additionally, this behavior can
  295. # also be triggered on cygwin if CMake crashes.
  296. # See https://github.com/mesonbuild/meson/pull/4969#issuecomment-499413233
  297. try:
  298. self.proc.terminate()
  299. except Exception:
  300. pass
  301. self.proc = None