platform_utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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, ignore_errors=False):
  205. """shutil.rmtree(path) wrapper with support for long paths on Windows.
  206. Availability: Unix, Windows."""
  207. onerror = None
  208. if isWindows():
  209. path = _makelongpath(path)
  210. onerror = handle_rmtree_error
  211. shutil.rmtree(path, ignore_errors=ignore_errors, onerror=onerror)
  212. def handle_rmtree_error(function, path, excinfo):
  213. # Allow deleting read-only files
  214. os.chmod(path, stat.S_IWRITE)
  215. function(path)
  216. def rename(src, dst):
  217. """os.rename(src, dst) wrapper with support for long paths on Windows.
  218. Availability: Unix, Windows."""
  219. if isWindows():
  220. # On Windows, rename fails if destination exists, see
  221. # https://docs.python.org/2/library/os.html#os.rename
  222. try:
  223. os.rename(_makelongpath(src), _makelongpath(dst))
  224. except OSError as e:
  225. if e.errno == errno.EEXIST:
  226. os.remove(_makelongpath(dst))
  227. os.rename(_makelongpath(src), _makelongpath(dst))
  228. else:
  229. raise
  230. else:
  231. os.rename(src, dst)
  232. def remove(path):
  233. """Remove (delete) the file path. This is a replacement for os.remove that
  234. allows deleting read-only files on Windows, with support for long paths and
  235. for deleting directory symbolic links.
  236. Availability: Unix, Windows."""
  237. if isWindows():
  238. longpath = _makelongpath(path)
  239. try:
  240. os.remove(longpath)
  241. except OSError as e:
  242. if e.errno == errno.EACCES:
  243. os.chmod(longpath, stat.S_IWRITE)
  244. # Directory symbolic links must be deleted with 'rmdir'.
  245. if islink(longpath) and isdir(longpath):
  246. os.rmdir(longpath)
  247. else:
  248. os.remove(longpath)
  249. else:
  250. raise
  251. else:
  252. os.remove(path)
  253. def walk(top, topdown=True, onerror=None, followlinks=False):
  254. """os.walk(path) wrapper with support for long paths on Windows.
  255. Availability: Windows, Unix.
  256. """
  257. if isWindows():
  258. return _walk_windows_impl(top, topdown, onerror, followlinks)
  259. else:
  260. return os.walk(top, topdown, onerror, followlinks)
  261. def _walk_windows_impl(top, topdown, onerror, followlinks):
  262. try:
  263. names = listdir(top)
  264. except Exception as err:
  265. if onerror is not None:
  266. onerror(err)
  267. return
  268. dirs, nondirs = [], []
  269. for name in names:
  270. if isdir(os.path.join(top, name)):
  271. dirs.append(name)
  272. else:
  273. nondirs.append(name)
  274. if topdown:
  275. yield top, dirs, nondirs
  276. for name in dirs:
  277. new_path = os.path.join(top, name)
  278. if followlinks or not islink(new_path):
  279. for x in _walk_windows_impl(new_path, topdown, onerror, followlinks):
  280. yield x
  281. if not topdown:
  282. yield top, dirs, nondirs
  283. def listdir(path):
  284. """os.listdir(path) wrapper with support for long paths on Windows.
  285. Availability: Windows, Unix.
  286. """
  287. return os.listdir(_makelongpath(path))
  288. def rmdir(path):
  289. """os.rmdir(path) wrapper with support for long paths on Windows.
  290. Availability: Windows, Unix.
  291. """
  292. os.rmdir(_makelongpath(path))
  293. def isdir(path):
  294. """os.path.isdir(path) wrapper with support for long paths on Windows.
  295. Availability: Windows, Unix.
  296. """
  297. return os.path.isdir(_makelongpath(path))
  298. def islink(path):
  299. """os.path.islink(path) wrapper with support for long paths on Windows.
  300. Availability: Windows, Unix.
  301. """
  302. if isWindows():
  303. import platform_utils_win32
  304. return platform_utils_win32.islink(_makelongpath(path))
  305. else:
  306. return os.path.islink(path)
  307. def readlink(path):
  308. """Return a string representing the path to which the symbolic link
  309. points. The result may be either an absolute or relative pathname;
  310. if it is relative, it may be converted to an absolute pathname using
  311. os.path.join(os.path.dirname(path), result).
  312. Availability: Windows, Unix.
  313. """
  314. if isWindows():
  315. import platform_utils_win32
  316. return platform_utils_win32.readlink(_makelongpath(path))
  317. else:
  318. return os.readlink(path)
  319. def realpath(path):
  320. """Return the canonical path of the specified filename, eliminating
  321. any symbolic links encountered in the path.
  322. Availability: Windows, Unix.
  323. """
  324. if isWindows():
  325. current_path = os.path.abspath(path)
  326. path_tail = []
  327. for c in range(0, 100): # Avoid cycles
  328. if islink(current_path):
  329. target = readlink(current_path)
  330. current_path = os.path.join(os.path.dirname(current_path), target)
  331. else:
  332. basename = os.path.basename(current_path)
  333. if basename == '':
  334. path_tail.append(current_path)
  335. break
  336. path_tail.append(basename)
  337. current_path = os.path.dirname(current_path)
  338. path_tail.reverse()
  339. result = os.path.normpath(os.path.join(*path_tail))
  340. return result
  341. else:
  342. return os.path.realpath(path)