platform_utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. # -*- coding:utf-8 -*-
  2. #
  3. # Copyright (C) 2016 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import errno
  17. import os
  18. import platform
  19. import select
  20. import shutil
  21. import stat
  22. from pyversion import is_python3
  23. if is_python3():
  24. from queue import Queue
  25. else:
  26. from Queue import Queue
  27. from threading import Thread
  28. def isWindows():
  29. """ Returns True when running with the native port of Python for Windows,
  30. False when running on any other platform (including the Cygwin port of
  31. Python).
  32. """
  33. # Note: The cygwin port of Python returns "CYGWIN_NT_xxx"
  34. return platform.system() == "Windows"
  35. class FileDescriptorStreams(object):
  36. """ Platform agnostic abstraction enabling non-blocking I/O over a
  37. collection of file descriptors. This abstraction is required because
  38. fctnl(os.O_NONBLOCK) is not supported on Windows.
  39. """
  40. @classmethod
  41. def create(cls):
  42. """ Factory method: instantiates the concrete class according to the
  43. current platform.
  44. """
  45. if isWindows():
  46. return _FileDescriptorStreamsThreads()
  47. else:
  48. return _FileDescriptorStreamsNonBlocking()
  49. def __init__(self):
  50. self.streams = []
  51. def add(self, fd, dest, std_name):
  52. """ Wraps an existing file descriptor as a stream.
  53. """
  54. self.streams.append(self._create_stream(fd, dest, std_name))
  55. def remove(self, stream):
  56. """ Removes a stream, when done with it.
  57. """
  58. self.streams.remove(stream)
  59. @property
  60. def is_done(self):
  61. """ Returns True when all streams have been processed.
  62. """
  63. return len(self.streams) == 0
  64. def select(self):
  65. """ Returns the set of streams that have data available to read.
  66. The returned streams each expose a read() and a close() method.
  67. When done with a stream, call the remove(stream) method.
  68. """
  69. raise NotImplementedError
  70. def _create_stream(fd, dest, std_name):
  71. """ Creates a new stream wrapping an existing file descriptor.
  72. """
  73. raise NotImplementedError
  74. class _FileDescriptorStreamsNonBlocking(FileDescriptorStreams):
  75. """ Implementation of FileDescriptorStreams for platforms that support
  76. non blocking I/O.
  77. """
  78. class Stream(object):
  79. """ Encapsulates a file descriptor """
  80. def __init__(self, fd, dest, std_name):
  81. self.fd = fd
  82. self.dest = dest
  83. self.std_name = std_name
  84. self.set_non_blocking()
  85. def set_non_blocking(self):
  86. import fcntl
  87. flags = fcntl.fcntl(self.fd, fcntl.F_GETFL)
  88. fcntl.fcntl(self.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
  89. def fileno(self):
  90. return self.fd.fileno()
  91. def read(self):
  92. return self.fd.read(4096)
  93. def close(self):
  94. self.fd.close()
  95. def _create_stream(self, fd, dest, std_name):
  96. return self.Stream(fd, dest, std_name)
  97. def select(self):
  98. ready_streams, _, _ = select.select(self.streams, [], [])
  99. return ready_streams
  100. class _FileDescriptorStreamsThreads(FileDescriptorStreams):
  101. """ Implementation of FileDescriptorStreams for platforms that don't support
  102. non blocking I/O. This implementation requires creating threads issuing
  103. blocking read operations on file descriptors.
  104. """
  105. def __init__(self):
  106. super(_FileDescriptorStreamsThreads, self).__init__()
  107. # The queue is shared accross all threads so we can simulate the
  108. # behavior of the select() function
  109. self.queue = Queue(10) # Limit incoming data from streams
  110. def _create_stream(self, fd, dest, std_name):
  111. return self.Stream(fd, dest, std_name, self.queue)
  112. def select(self):
  113. # Return only one stream at a time, as it is the most straighforward
  114. # thing to do and it is compatible with the select() function.
  115. item = self.queue.get()
  116. stream = item.stream
  117. stream.data = item.data
  118. return [stream]
  119. class QueueItem(object):
  120. """ Item put in the shared queue """
  121. def __init__(self, stream, data):
  122. self.stream = stream
  123. self.data = data
  124. class Stream(object):
  125. """ Encapsulates a file descriptor """
  126. def __init__(self, fd, dest, std_name, queue):
  127. self.fd = fd
  128. self.dest = dest
  129. self.std_name = std_name
  130. self.queue = queue
  131. self.data = None
  132. self.thread = Thread(target=self.read_to_queue)
  133. self.thread.daemon = True
  134. self.thread.start()
  135. def close(self):
  136. self.fd.close()
  137. def read(self):
  138. data = self.data
  139. self.data = None
  140. return data
  141. def read_to_queue(self):
  142. """ The thread function: reads everything from the file descriptor into
  143. the shared queue and terminates when reaching EOF.
  144. """
  145. for line in iter(self.fd.readline, b''):
  146. self.queue.put(_FileDescriptorStreamsThreads.QueueItem(self, line))
  147. self.fd.close()
  148. self.queue.put(_FileDescriptorStreamsThreads.QueueItem(self, None))
  149. def symlink(source, link_name):
  150. """Creates a symbolic link pointing to source named link_name.
  151. Note: On Windows, source must exist on disk, as the implementation needs
  152. to know whether to create a "File" or a "Directory" symbolic link.
  153. """
  154. if isWindows():
  155. import platform_utils_win32
  156. source = _validate_winpath(source)
  157. link_name = _validate_winpath(link_name)
  158. target = os.path.join(os.path.dirname(link_name), source)
  159. if isdir(target):
  160. platform_utils_win32.create_dirsymlink(_makelongpath(source), link_name)
  161. else:
  162. platform_utils_win32.create_filesymlink(_makelongpath(source), link_name)
  163. else:
  164. return os.symlink(source, link_name)
  165. def _validate_winpath(path):
  166. path = os.path.normpath(path)
  167. if _winpath_is_valid(path):
  168. return path
  169. raise ValueError("Path \"%s\" must be a relative path or an absolute "
  170. "path starting with a drive letter".format(path))
  171. def _winpath_is_valid(path):
  172. """Windows only: returns True if path is relative (e.g. ".\\foo") or is
  173. absolute including a drive letter (e.g. "c:\\foo"). Returns False if path
  174. is ambiguous (e.g. "x:foo" or "\\foo").
  175. """
  176. assert isWindows()
  177. path = os.path.normpath(path)
  178. drive, tail = os.path.splitdrive(path)
  179. if tail:
  180. if not drive:
  181. return tail[0] != os.sep # "\\foo" is invalid
  182. else:
  183. return tail[0] == os.sep # "x:foo" is invalid
  184. else:
  185. return not drive # "x:" is invalid
  186. def _makelongpath(path):
  187. """Return the input path normalized to support the Windows long path syntax
  188. ("\\\\?\\" prefix) if needed, i.e. if the input path is longer than the
  189. MAX_PATH limit.
  190. """
  191. if isWindows():
  192. # Note: MAX_PATH is 260, but, for directories, the maximum value is actually 246.
  193. if len(path) < 246:
  194. return path
  195. if path.startswith(u"\\\\?\\"):
  196. return path
  197. if not os.path.isabs(path):
  198. return path
  199. # Append prefix and ensure unicode so that the special longpath syntax
  200. # is supported by underlying Win32 API calls
  201. return u"\\\\?\\" + os.path.normpath(path)
  202. else:
  203. return path
  204. def rmtree(path):
  205. """shutil.rmtree(path) wrapper with support for long paths on Windows.
  206. Availability: Unix, Windows."""
  207. if isWindows():
  208. shutil.rmtree(_makelongpath(path), onerror=handle_rmtree_error)
  209. else:
  210. shutil.rmtree(path)
  211. def handle_rmtree_error(function, path, excinfo):
  212. # Allow deleting read-only files
  213. os.chmod(path, stat.S_IWRITE)
  214. function(path)
  215. def rename(src, dst):
  216. """os.rename(src, dst) wrapper with support for long paths on Windows.
  217. Availability: Unix, Windows."""
  218. if isWindows():
  219. # On Windows, rename fails if destination exists, see
  220. # https://docs.python.org/2/library/os.html#os.rename
  221. try:
  222. os.rename(_makelongpath(src), _makelongpath(dst))
  223. except OSError as e:
  224. if e.errno == errno.EEXIST:
  225. os.remove(_makelongpath(dst))
  226. os.rename(_makelongpath(src), _makelongpath(dst))
  227. else:
  228. raise
  229. else:
  230. os.rename(src, dst)
  231. def remove(path):
  232. """Remove (delete) the file path. This is a replacement for os.remove that
  233. allows deleting read-only files on Windows, with support for long paths and
  234. for deleting directory symbolic links.
  235. Availability: Unix, Windows."""
  236. if isWindows():
  237. longpath = _makelongpath(path)
  238. try:
  239. os.remove(longpath)
  240. except OSError as e:
  241. if e.errno == errno.EACCES:
  242. os.chmod(longpath, stat.S_IWRITE)
  243. # Directory symbolic links must be deleted with 'rmdir'.
  244. if islink(longpath) and isdir(longpath):
  245. os.rmdir(longpath)
  246. else:
  247. os.remove(longpath)
  248. else:
  249. raise
  250. else:
  251. os.remove(path)
  252. def walk(top, topdown=True, onerror=None, followlinks=False):
  253. """os.walk(path) wrapper with support for long paths on Windows.
  254. Availability: Windows, Unix.
  255. """
  256. if isWindows():
  257. return _walk_windows_impl(top, topdown, onerror, followlinks)
  258. else:
  259. return os.walk(top, topdown, onerror, followlinks)
  260. def _walk_windows_impl(top, topdown, onerror, followlinks):
  261. try:
  262. names = listdir(top)
  263. except Exception as err:
  264. if onerror is not None:
  265. onerror(err)
  266. return
  267. dirs, nondirs = [], []
  268. for name in names:
  269. if isdir(os.path.join(top, name)):
  270. dirs.append(name)
  271. else:
  272. nondirs.append(name)
  273. if topdown:
  274. yield top, dirs, nondirs
  275. for name in dirs:
  276. new_path = os.path.join(top, name)
  277. if followlinks or not islink(new_path):
  278. for x in _walk_windows_impl(new_path, topdown, onerror, followlinks):
  279. yield x
  280. if not topdown:
  281. yield top, dirs, nondirs
  282. def listdir(path):
  283. """os.listdir(path) wrapper with support for long paths on Windows.
  284. Availability: Windows, Unix.
  285. """
  286. return os.listdir(_makelongpath(path))
  287. def rmdir(path):
  288. """os.rmdir(path) wrapper with support for long paths on Windows.
  289. Availability: Windows, Unix.
  290. """
  291. os.rmdir(_makelongpath(path))
  292. def isdir(path):
  293. """os.path.isdir(path) wrapper with support for long paths on Windows.
  294. Availability: Windows, Unix.
  295. """
  296. return os.path.isdir(_makelongpath(path))
  297. def islink(path):
  298. """os.path.islink(path) wrapper with support for long paths on Windows.
  299. Availability: Windows, Unix.
  300. """
  301. if isWindows():
  302. import platform_utils_win32
  303. return platform_utils_win32.islink(_makelongpath(path))
  304. else:
  305. return os.path.islink(path)
  306. def readlink(path):
  307. """Return a string representing the path to which the symbolic link
  308. points. The result may be either an absolute or relative pathname;
  309. if it is relative, it may be converted to an absolute pathname using
  310. os.path.join(os.path.dirname(path), result).
  311. Availability: Windows, Unix.
  312. """
  313. if isWindows():
  314. import platform_utils_win32
  315. return platform_utils_win32.readlink(_makelongpath(path))
  316. else:
  317. return os.readlink(path)
  318. def realpath(path):
  319. """Return the canonical path of the specified filename, eliminating
  320. any symbolic links encountered in the path.
  321. Availability: Windows, Unix.
  322. """
  323. if isWindows():
  324. current_path = os.path.abspath(path)
  325. path_tail = []
  326. for c in range(0, 100): # Avoid cycles
  327. if islink(current_path):
  328. target = readlink(current_path)
  329. current_path = os.path.join(os.path.dirname(current_path), target)
  330. else:
  331. basename = os.path.basename(current_path)
  332. if basename == '':
  333. path_tail.append(current_path)
  334. break
  335. path_tail.append(basename)
  336. current_path = os.path.dirname(current_path)
  337. path_tail.reverse()
  338. result = os.path.normpath(os.path.join(*path_tail))
  339. return result
  340. else:
  341. return os.path.realpath(path)