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