-
Notifications
You must be signed in to change notification settings - Fork 154
/
gopen.py
395 lines (335 loc) · 10.9 KB
/
gopen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#
# Copyright (c) 2017-2021 NVIDIA CORPORATION. All rights reserved.
# This file is part of the WebDataset library.
# See the LICENSE file for licensing terms (BSD-style).
#
"""Open URLs by calling subcommands."""
import os
import sys
import re
from subprocess import PIPE, Popen
from urllib.parse import urlparse
# global used for printing additional node information during verbose output
info = {}
class Pipe:
"""Wrapper class for subprocess.Pipe.
This class looks like a stream from the outside, but it checks
subprocess status and handles timeouts with exceptions.
This way, clients of the class do not need to know that they are
dealing with subprocesses.
:param *args: passed to `subprocess.Pipe`
:param **kw: passed to `subprocess.Pipe`
:param timeout: timeout for closing/waiting
:param ignore_errors: don't raise exceptions on subprocess errors
:param ignore_status: list of status codes to ignore
"""
def __init__(
self,
*args,
mode=None,
timeout=7200.0,
ignore_errors=False,
ignore_status=[],
**kw,
):
"""Create an IO Pipe."""
self.ignore_errors = ignore_errors
self.ignore_status = [0] + ignore_status
self.timeout = timeout
self.args = (args, kw)
if mode[0] == "r":
self.proc = Popen(*args, stdout=PIPE, **kw)
self.stream = self.proc.stdout
if self.stream is None:
raise ValueError(f"{args}: couldn't open")
elif mode[0] == "w":
self.proc = Popen(*args, stdin=PIPE, **kw)
self.stream = self.proc.stdin
if self.stream is None:
raise ValueError(f"{args}: couldn't open")
self.status = None
def __str__(self):
return f"<Pipe {self.args}>"
def check_status(self):
"""Poll the process and handle any errors."""
status = self.proc.poll()
if status is not None:
self.wait_for_child()
def wait_for_child(self):
"""Check the status variable and raise an exception if necessary."""
verbose = int(os.environ.get("GOPEN_VERBOSE", 0))
if self.status is not None and verbose:
# print(f"(waiting again [{self.status} {os.getpid()}:{self.proc.pid}])", file=sys.stderr)
return
self.status = self.proc.wait()
if verbose:
print(
f"pipe exit [{self.status} {os.getpid()}:{self.proc.pid}] {self.args} {info}",
file=sys.stderr,
)
if self.status not in self.ignore_status and not self.ignore_errors:
raise IOError(f"{self.args}: exit {self.status} (read) {info}")
def read(self, *args, **kw):
"""Wrap stream.read and checks status."""
result = self.stream.read(*args, **kw)
self.check_status()
return result
def write(self, *args, **kw):
"""Wrap stream.write and checks status."""
result = self.stream.write(*args, **kw)
self.check_status()
return result
def readLine(self, *args, **kw):
"""Wrap stream.readLine and checks status."""
result = self.stream.readLine(*args, **kw)
self.status = self.proc.poll()
self.check_status()
return result
def close(self):
"""Wrap stream.close, wait for the subprocess, and handle errors."""
self.stream.close()
self.status = self.proc.wait(self.timeout)
self.wait_for_child()
def __enter__(self):
"""Context handler."""
return self
def __exit__(self, etype, value, traceback):
"""Context handler."""
self.close()
def set_options(
obj, timeout=None, ignore_errors=None, ignore_status=None, handler=None
):
"""Set options for Pipes.
This function can be called on any stream. It will set pipe options only
when its argument is a pipe.
:param obj: any kind of stream
:param timeout: desired timeout
:param ignore_errors: desired ignore_errors setting
:param ignore_status: desired ignore_status setting
:param handler: desired error handler
"""
if not isinstance(obj, Pipe):
return False
if timeout is not None:
obj.timeout = timeout
if ignore_errors is not None:
obj.ignore_errors = ignore_errors
if ignore_status is not None:
obj.ignore_status = ignore_status
if handler is not None:
obj.handler = handler
return True
def gopen_file(url, mode="rb", bufsize=8192):
"""Open a file.
This works for local files; path names only.
:param url: URL to be opened
:param mode: mode to open it with
:param bufsize: requested buffer size
"""
if url.startswith("file:"):
url = re.sub(r"^file://?", "", url)
return open(url, mode)
def gopen_pipe(url, mode="rb", bufsize=8192):
"""Use gopen to open a pipe.
:param url: a pipe: URL
:param mode: desired mode
:param bufsize: desired buffer size
"""
assert url.startswith("pipe:")
cmd = url[5:]
if mode[0] == "r":
return Pipe(
cmd,
mode=mode,
shell=True,
bufsize=bufsize,
ignore_status=[141],
) # skipcq: BAN-B604
elif mode[0] == "w":
return Pipe(
cmd,
mode=mode,
shell=True,
bufsize=bufsize,
ignore_status=[141],
) # skipcq: BAN-B604
else:
raise ValueError(f"{mode}: unknown mode")
def gopen_curl(url, mode="rb", bufsize=8192):
"""Open a URL with `curl`.
:param url: url (usually, http:// etc.)
:param mode: file mode
:param bufsize: buffer size
"""
if mode[0] == "r":
cmd = f"curl -f -s -L '{url}'"
return Pipe(
cmd,
mode=mode,
shell=True,
bufsize=bufsize,
ignore_status=[141, 23],
) # skipcq: BAN-B604
elif mode[0] == "w":
cmd = f"curl -f -s -X PUT -L -T - '{url}'"
return Pipe(
cmd,
mode=mode,
shell=True,
bufsize=bufsize,
ignore_status=[141, 26],
) # skipcq: BAN-B604
else:
raise ValueError(f"{mode}: unknown mode")
def gopen_htgs(url, mode="rb", bufsize=8192):
"""Open a URL with `curl`.
:param url: url (usually, http:// etc.)
:param mode: file mode
:param bufsize: buffer size
"""
if mode[0] == "r":
url = re.sub(r"(?i)^htgs://", "gs://", url)
cmd = f"curl -s -L '{url}'"
return Pipe(
cmd,
mode=mode,
shell=True,
bufsize=bufsize,
ignore_status=[141, 23],
) # skipcq: BAN-B604
elif mode[0] == "w":
raise ValueError(f"{mode}: cannot write")
else:
raise ValueError(f"{mode}: unknown mode")
def gopen_gsutil(url, mode="rb", bufsize=8192):
"""Open a URL with `curl`.
:param url: url (usually, http:// etc.)
:param mode: file mode
:param bufsize: buffer size
"""
if mode[0] == "r":
cmd = f"gsutil cat '{url}'"
return Pipe(
cmd,
mode=mode,
shell=True,
bufsize=bufsize,
ignore_status=[141, 23],
) # skipcq: BAN-B604
elif mode[0] == "w":
cmd = f"gsutil cp - '{url}'"
return Pipe(
cmd,
mode=mode,
shell=True,
bufsize=bufsize,
ignore_status=[141, 26],
) # skipcq: BAN-B604
else:
raise ValueError(f"{mode}: unknown mode")
def gopen_ais(url, mode="rb", bufsize=8192):
"""Open a URL with `curl`.
:param url: url (usually, http:// etc.)
:param mode: file mode
:param bufsize: buffer size
"""
if mode[0] == "r":
cmd = f"ais get '{url}' -"
return Pipe(
cmd,
mode=mode,
shell=True,
bufsize=bufsize,
ignore_status=[141, 23],
) # skipcq: BAN-B604
elif mode[0] == "w":
cmd = f"ais put - '{url}'"
return Pipe(
cmd,
mode=mode,
shell=True,
bufsize=bufsize,
ignore_status=[141, 26],
) # skipcq: BAN-B604
else:
raise ValueError(f"{mode}: unknown mode")
def gopen_error(url, *args, **kw):
"""Raise a value error.
:param url: url
:param args: other arguments
:param kw: other keywords
"""
raise ValueError(f"{url}: no gopen handler defined")
"""A dispatch table mapping URL schemes to handlers."""
gopen_schemes = dict(
__default__=gopen_error,
pipe=gopen_pipe,
http=gopen_curl,
https=gopen_curl,
ais=gopen_ais,
sftp=gopen_curl,
ftps=gopen_curl,
scp=gopen_curl,
gs=gopen_gsutil,
htgs=gopen_htgs,
)
if "USE_AIS_FOR" in os.environ:
for proto in os.environ["USE_AIS_FOR"].split(":"):
gopen_schemes[proto] = gopen_ais
def rewrite_url(url):
name = "GOPEN_REWRITE"
verbose = int(os.environ.get("GOPEN_VERBOSE", 0))
if name not in os.environ:
return url
for r in os.environ[name].split(";"):
k, v = r.split("=", 1)
nurl = re.sub("^" + k, v, url)
if nurl != url:
if verbose:
print(f"GOPEN REWRITE {url} -> {nurl}")
return nurl
return url
def gopen(url, mode="rb", bufsize=8192, **kw):
"""Open the URL.
This uses the `gopen_schemes` dispatch table to dispatch based
on scheme.
Support for the following schemes is built-in: pipe, file,
http, https, sftp, ftps, scp.
When no scheme is given the url is treated as a file.
You can use the GOPEN_VERBOSE argument to get info about
files being opened.
YOu can use the USE_AIS_FOR=aws:gs:s3 to use AIS (and its cache)
to access urls via the "ais" command.
:param url: the source URL
:param mode: the mode ("rb", "r")
:param bufsize: the buffer size
"""
global fallback_gopen
verbose = int(os.environ.get("GOPEN_VERBOSE", 0))
if verbose:
print("GOPEN", url, info, file=sys.stderr)
assert mode in ["rb", "wb"], mode
if url == "-":
if mode == "rb":
return sys.stdin.buffer
elif mode == "wb":
return sys.stdout.buffer
else:
raise ValueError(f"unknown mode {mode}")
url = rewrite_url(url)
pr = urlparse(url)
if pr.scheme == "":
bufsize = int(os.environ.get("GOPEN_BUFFER", -1))
return open(url, mode, buffering=bufsize)
if pr.scheme == "file":
bufsize = int(os.environ.get("GOPEN_BUFFER", -1))
return open(pr.path, mode, buffering=bufsize)
handler = gopen_schemes["__default__"]
handler = gopen_schemes.get(pr.scheme, handler)
return handler(url, mode, bufsize, **kw)
def reader(url, **kw):
"""Open url with gopen and mode "rb".
:param url: source URL
:param kw: other keywords forwarded to gopen
"""
return gopen(url, "rb", **kw)