]> jfr.im git - yt-dlp.git/blame - youtube_dl/downloader/http.py
[downloader/http] Retry download when urlopen times out (#26603) (refs #10935)
[yt-dlp.git] / youtube_dl / downloader / http.py
CommitLineData
4d2d638d
PH
1from __future__ import unicode_literals
2
16e7711e 3import errno
3bc2ddcc 4import os
16e7711e 5import socket
3bc2ddcc 6import time
b91a7a4e 7import random
8d5b8b47 8import re
3bc2ddcc
JMF
9
10from .common import FileDownloader
ba515388
S
11from ..compat import (
12 compat_str,
13 compat_urllib_error,
14)
1cc79574 15from ..utils import (
3bc2ddcc 16 ContentTooShortError,
3bc2ddcc 17 encodeFilename,
ba515388 18 int_or_none,
3bc2ddcc 19 sanitize_open,
5c2266df 20 sanitized_Request,
d7753d19
YCH
21 write_xattr,
22 XAttrMetadataError,
23 XAttrUnavailableError,
3bc2ddcc
JMF
24)
25
26
27class HttpFD(FileDownloader):
d3f0687c 28 def real_download(self, filename, info_dict):
3bc2ddcc 29 url = info_dict['url']
a3c3a1e1
S
30
31 class DownloadContext(dict):
32 __getattr__ = dict.get
33 __setattr__ = dict.__setitem__
34 __delattr__ = dict.__delitem__
35
36 ctx = DownloadContext()
37 ctx.filename = filename
38 ctx.tmpfilename = self.temp_name(filename)
39 ctx.stream = None
3bc2ddcc
JMF
40
41 # Do not include the Accept-Encoding header
42 headers = {'Youtubedl-no-compression': 'True'}
d769be6c
PH
43 add_headers = info_dict.get('http_headers')
44 if add_headers:
45 headers.update(add_headers)
3bc2ddcc 46
df297c87 47 is_test = self.params.get('test', False)
ba515388 48 chunk_size = self._TEST_FILE_SIZE if is_test else (
3089bc74
S
49 info_dict.get('downloader_options', {}).get('http_chunk_size')
50 or self.params.get('http_chunk_size') or 0)
3bc2ddcc 51
a3c3a1e1
S
52 ctx.open_mode = 'wb'
53 ctx.resume_len = 0
ba515388
S
54 ctx.data_len = None
55 ctx.block_size = self.params.get('buffersize', 1024)
56 ctx.start_time = time.time()
b91a7a4e 57 ctx.chunk_size = None
a3c3a1e1
S
58
59 if self.params.get('continuedl', True):
60 # Establish possible resume length
61 if os.path.isfile(encodeFilename(ctx.tmpfilename)):
ba515388
S
62 ctx.resume_len = os.path.getsize(
63 encodeFilename(ctx.tmpfilename))
64
65 ctx.is_resume = ctx.resume_len > 0
3bc2ddcc
JMF
66
67 count = 0
68 retries = self.params.get('retries', 0)
a3c3a1e1
S
69
70 class SucceedDownload(Exception):
71 pass
72
73 class RetryDownload(Exception):
74 def __init__(self, source_error):
75 self.source_error = source_error
76
ba515388
S
77 class NextFragment(Exception):
78 pass
79
80 def set_range(req, start, end):
81 range_header = 'bytes=%d-' % start
82 if end:
83 range_header += compat_str(end)
84 req.add_header('Range', range_header)
85
a3c3a1e1 86 def establish_connection():
b91a7a4e
S
87 ctx.chunk_size = (random.randint(int(chunk_size * 0.95), chunk_size)
88 if not is_test and chunk_size else chunk_size)
ba515388
S
89 if ctx.resume_len > 0:
90 range_start = ctx.resume_len
91 if ctx.is_resume:
92 self.report_resuming_byte(ctx.resume_len)
a3c3a1e1 93 ctx.open_mode = 'ab'
b91a7a4e 94 elif ctx.chunk_size > 0:
ba515388
S
95 range_start = 0
96 else:
97 range_start = None
98 ctx.is_resume = False
b91a7a4e 99 range_end = range_start + ctx.chunk_size - 1 if ctx.chunk_size else None
ba515388
S
100 if range_end and ctx.data_len is not None and range_end >= ctx.data_len:
101 range_end = ctx.data_len - 1
102 has_range = range_start is not None
103 ctx.has_range = has_range
cf7259bc 104 request = sanitized_Request(url, None, headers)
ba515388
S
105 if has_range:
106 set_range(request, range_start, range_end)
3bc2ddcc
JMF
107 # Establish connection
108 try:
86b7c00a
OA
109 try:
110 ctx.data = self.ydl.urlopen(request)
111 except (compat_urllib_error.URLError, ) as err:
112 if isinstance(err.reason, socket.timeout):
113 raise RetryDownload(err)
114 raise err
84bc4dcb
S
115 # When trying to resume, Content-Range HTTP header of response has to be checked
116 # to match the value of requested Range HTTP header. This is due to a webservers
117 # that don't support resuming and serve a whole file with no Content-Range
118 # set in response despite of requested Range (see
067aa17e 119 # https://github.com/ytdl-org/youtube-dl/issues/6057#issuecomment-126129799)
ba515388 120 if has_range:
a3c3a1e1 121 content_range = ctx.data.headers.get('Content-Range')
d7d2a9a3 122 if content_range:
ba515388 123 content_range_m = re.search(r'bytes (\d+)-(\d+)?(?:/(\d+))?', content_range)
84bc4dcb 124 # Content-Range is present and matches requested Range, resume is possible
ba515388
S
125 if content_range_m:
126 if range_start == int(content_range_m.group(1)):
127 content_range_end = int_or_none(content_range_m.group(2))
128 content_len = int_or_none(content_range_m.group(3))
129 accept_content_len = (
130 # Non-chunked download
3089bc74 131 not ctx.chunk_size
ba515388
S
132 # Chunked download and requested piece or
133 # its part is promised to be served
3089bc74
S
134 or content_range_end == range_end
135 or content_len < range_end)
ba515388
S
136 if accept_content_len:
137 ctx.data_len = content_len
138 return
84bc4dcb
S
139 # Content-Range is either not present or invalid. Assuming remote webserver is
140 # trying to send the whole file, resume is not possible, so wiping the local file
141 # and performing entire redownload
10eaa8ef 142 self.report_unable_to_resume()
a3c3a1e1
S
143 ctx.resume_len = 0
144 ctx.open_mode = 'wb'
ba515388 145 ctx.data_len = int_or_none(ctx.data.info().get('Content-length', None))
a3c3a1e1 146 return
3bc2ddcc 147 except (compat_urllib_error.HTTPError, ) as err:
ba515388 148 if err.code == 416:
3bc2ddcc
JMF
149 # Unable to resume (requested range not satisfiable)
150 try:
151 # Open the connection again without the range header
cf7259bc
S
152 ctx.data = self.ydl.urlopen(
153 sanitized_Request(url, None, headers))
a3c3a1e1 154 content_length = ctx.data.info()['Content-Length']
3bc2ddcc
JMF
155 except (compat_urllib_error.HTTPError, ) as err:
156 if err.code < 500 or err.code >= 600:
157 raise
158 else:
159 # Examine the reported length
3089bc74
S
160 if (content_length is not None
161 and (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)):
3bc2ddcc
JMF
162 # The file had already been fully downloaded.
163 # Explanation to the above condition: in issue #175 it was revealed that
164 # YouTube sometimes adds or removes a few bytes from the end of the file,
165 # changing the file size slightly and causing problems for some users. So
166 # I decided to implement a suggested change and consider the file
167 # completely downloaded if the file size differs less than 100 bytes from
168 # the one in the hard drive.
a3c3a1e1
S
169 self.report_file_already_downloaded(ctx.filename)
170 self.try_rename(ctx.tmpfilename, ctx.filename)
3bc2ddcc 171 self._hook_progress({
a3c3a1e1 172 'filename': ctx.filename,
3bc2ddcc 173 'status': 'finished',
a3c3a1e1
S
174 'downloaded_bytes': ctx.resume_len,
175 'total_bytes': ctx.resume_len,
3bc2ddcc 176 })
a3c3a1e1 177 raise SucceedDownload()
3bc2ddcc
JMF
178 else:
179 # The length does not match, we start the download over
180 self.report_unable_to_resume()
a3c3a1e1
S
181 ctx.resume_len = 0
182 ctx.open_mode = 'wb'
183 return
ba515388
S
184 elif err.code < 500 or err.code >= 600:
185 # Unexpected HTTP error
186 raise
a3c3a1e1
S
187 raise RetryDownload(err)
188 except socket.error as err:
189 if err.errno != errno.ECONNRESET:
12832049
PH
190 # Connection reset is no problem, just retry
191 raise
a3c3a1e1
S
192 raise RetryDownload(err)
193
194 def download():
195 data_len = ctx.data.info().get('Content-length', None)
196
197 # Range HTTP header may be ignored/unsupported by a webserver
198 # (e.g. extractor/scivee.py, extractor/bambuser.py).
199 # However, for a test we still would like to download just a piece of a file.
200 # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control
201 # block size when downloading a file.
202 if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):
203 data_len = self._TEST_FILE_SIZE
204
205 if data_len is not None:
206 data_len = int(data_len) + ctx.resume_len
207 min_data_len = self.params.get('min_filesize')
208 max_data_len = self.params.get('max_filesize')
209 if min_data_len is not None and data_len < min_data_len:
210 self.to_screen('\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
211 return False
212 if max_data_len is not None and data_len > max_data_len:
213 self.to_screen('\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
214 return False
12832049 215
a3c3a1e1 216 byte_counter = 0 + ctx.resume_len
ba515388 217 block_size = ctx.block_size
a3c3a1e1 218 start = time.time()
c7667c2d 219
a3c3a1e1
S
220 # measure time over whole while-loop, so slow_down() and best_block_size() work together properly
221 now = None # needed for slow_down() in the first loop run
222 before = start # start measuring
c7667c2d 223
a3c3a1e1 224 def retry(e):
5d6c81b6
S
225 to_stdout = ctx.tmpfilename == '-'
226 if not to_stdout:
a3c3a1e1
S
227 ctx.stream.close()
228 ctx.stream = None
5d6c81b6 229 ctx.resume_len = byte_counter if to_stdout else os.path.getsize(encodeFilename(ctx.tmpfilename))
a3c3a1e1 230 raise RetryDownload(e)
c7667c2d 231
a3c3a1e1
S
232 while True:
233 try:
234 # Download and write
6c907eb3 235 data_block = ctx.data.read(block_size if data_len is None else min(block_size, data_len - byte_counter))
a3c3a1e1
S
236 # socket.timeout is a subclass of socket.error but may not have
237 # errno set
238 except socket.timeout as e:
239 retry(e)
240 except socket.error as e:
241 if e.errno not in (errno.ECONNRESET, errno.ETIMEDOUT):
242 raise
243 retry(e)
244
245 byte_counter += len(data_block)
246
247 # exit loop when download is finished
248 if len(data_block) == 0:
249 break
250
251 # Open destination file just in time
252 if ctx.stream is None:
253 try:
254 ctx.stream, ctx.tmpfilename = sanitize_open(
255 ctx.tmpfilename, ctx.open_mode)
256 assert ctx.stream is not None
257 ctx.filename = self.undo_temp_name(ctx.tmpfilename)
258 self.report_destination(ctx.filename)
259 except (OSError, IOError) as err:
260 self.report_error('unable to open for writing: %s' % str(err))
261 return False
262
263 if self.params.get('xattr_set_filesize', False) and data_len is not None:
264 try:
265 write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode('utf-8'))
266 except (XAttrUnavailableError, XAttrMetadataError) as err:
267 self.report_error('unable to set filesize xattr: %s' % str(err))
3bc2ddcc 268
3bc2ddcc 269 try:
a3c3a1e1
S
270 ctx.stream.write(data_block)
271 except (IOError, OSError) as err:
272 self.to_stderr('\n')
273 self.report_error('unable to write data: %s' % str(err))
3bc2ddcc 274 return False
881e6a1f 275
a3c3a1e1
S
276 # Apply rate limit
277 self.slow_down(start, now, byte_counter - ctx.resume_len)
278
279 # end measuring of one loop run
280 now = time.time()
281 after = now
282
283 # Adjust block size
284 if not self.params.get('noresizebuffer', False):
285 block_size = self.best_block_size(after - before, len(data_block))
286
287 before = after
288
289 # Progress message
290 speed = self.calc_speed(start, now, byte_counter - ctx.resume_len)
ba515388 291 if ctx.data_len is None:
a3c3a1e1
S
292 eta = None
293 else:
ba515388 294 eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len)
a3c3a1e1
S
295
296 self._hook_progress({
297 'status': 'downloading',
298 'downloaded_bytes': byte_counter,
ba515388 299 'total_bytes': ctx.data_len,
a3c3a1e1
S
300 'tmpfilename': ctx.tmpfilename,
301 'filename': ctx.filename,
302 'eta': eta,
303 'speed': speed,
ba515388 304 'elapsed': now - ctx.start_time,
a3c3a1e1
S
305 })
306
f7b42518 307 if data_len is not None and byte_counter == data_len:
a3c3a1e1
S
308 break
309
b91a7a4e 310 if not is_test and ctx.chunk_size and ctx.data_len is not None and byte_counter < ctx.data_len:
ba515388
S
311 ctx.resume_len = byte_counter
312 # ctx.block_size = block_size
313 raise NextFragment()
314
a3c3a1e1 315 if ctx.stream is None:
4d2d638d 316 self.to_stderr('\n')
a3c3a1e1 317 self.report_error('Did not get any data blocks')
3bc2ddcc 318 return False
a3c3a1e1
S
319 if ctx.tmpfilename != '-':
320 ctx.stream.close()
c7667c2d 321
a3c3a1e1
S
322 if data_len is not None and byte_counter != data_len:
323 err = ContentTooShortError(byte_counter, int(data_len))
324 if count <= retries:
325 retry(err)
326 raise err
c7667c2d 327
a3c3a1e1 328 self.try_rename(ctx.tmpfilename, ctx.filename)
c7667c2d 329
a3c3a1e1
S
330 # Update file modification time
331 if self.params.get('updatetime', True):
332 info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None))
3bc2ddcc
JMF
333
334 self._hook_progress({
335 'downloaded_bytes': byte_counter,
a3c3a1e1
S
336 'total_bytes': byte_counter,
337 'filename': ctx.filename,
338 'status': 'finished',
ba515388 339 'elapsed': time.time() - ctx.start_time,
3bc2ddcc
JMF
340 })
341
a3c3a1e1
S
342 return True
343
344 while count <= retries:
345 try:
346 establish_connection()
bec49996 347 return download()
a3c3a1e1
S
348 except RetryDownload as e:
349 count += 1
350 if count <= retries:
351 self.report_retry(e.source_error, count, retries)
352 continue
ba515388
S
353 except NextFragment:
354 continue
a3c3a1e1
S
355 except SucceedDownload:
356 return True
357
358 self.report_error('giving up after %s retries' % retries)
359 return False