-
Notifications
You must be signed in to change notification settings - Fork 34
/
image-download
executable file
·316 lines (255 loc) · 10.6 KB
/
image-download
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
#!/usr/bin/env python3
# This file is part of Cockpit.
#
# Copyright (C) 2013 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
#
# Download images or other state
#
# Images usually have a name specific link committed to git. These
# are referred to as 'committed'
#
# Other state is simply referenced by name without a link in git
# This is referred to as 'state'
#
# The stores are places to look for images or other state
#
import argparse
import contextlib
import email
import fcntl
import io
import os
import shutil
import stat
import subprocess
import sys
import time
import urllib.parse
from collections.abc import Iterator, Sequence
from lib import s3
from lib.constants import IMAGES_DIR
from lib.directories import get_images_data_dir
from lib.network import get_curl_ca_arg, redhat_network
from lib.stores import PUBLIC_STORES, REDHAT_STORES
from lib.testmap import get_test_image
EPOCH = "Thu, 1 Jan 1970 00:00:00 GMT"
if os.isatty(1):
SYMBOLS = {'present': ' ✔', 'absent': ' ⨯', 'selected': '❯❯'} # noqa: RUF001
else:
SYMBOLS = {'present': ' >', 'absent': ' x', 'selected': '=>'}
def show_status(quiet: bool, status: str, *args: str, prefix: str = '') -> None:
if not quiet:
message = ' '.join(args)
sys.stderr.write(f'{prefix}{SYMBOLS[status]} {message}\n')
def curl_cmd(args: Sequence[str]) -> Sequence[str]:
return ['curl', '--connect-timeout', '10', '--fail', *args]
def check_curl_args(args: Sequence[str]) -> tuple[str, float] | None:
head_args = ['--silent', '--head'] # only used for this check
try:
start = time.time()
output = subprocess.check_output(curl_cmd((*args, *head_args)), text=True)
duration = time.time() - start
return output, duration
except subprocess.CalledProcessError:
return None
def find(name: str, stores: Sequence[str], latest: float, quiet: bool) -> tuple[list[str], str] | None:
found = []
for store in stores:
url = urllib.parse.urlparse(urllib.parse.urljoin(store, name))
args = get_curl_ca_arg(url.netloc)
# First, check if this is an S3 store for which we have a key
if s3.is_key_present(url):
result = check_curl_args((*args, *s3.sign_curl(url, method='HEAD')))
if result:
show_status(quiet, 'present', store, '(authenticated)')
found.append(([*args, *s3.sign_curl(url)], result, store)) # GET
continue
else:
# access the URL directly, without further authentication
args.append(url.geturl())
result = check_curl_args(args)
if result:
show_status(quiet, 'present', store)
found.append((args, result, store))
continue
show_status(quiet, 'absent', store)
# If we couldn't find the file, but it exists, we're good
if not found:
return None
# Find the most recent version of this file
def header_date(args: tuple[Sequence[str], tuple[str, float], str]) -> str | float:
_, (output, _duration), _message = args
try:
_reply_line, headers_alone = output.split('\n', 1)
last_modified = email.message_from_file(io.StringIO(headers_alone)).get("Last-Modified", "")
return time.mktime(time.strptime(last_modified, '%a, %d %b %Y %H:%M:%S %Z'))
except ValueError:
return ""
if latest:
# if we depend on getting the latest info, only download it from that one store
found.sort(reverse=True, key=header_date)
else:
found.sort(reverse=False, key=lambda x: x[1][1])
return found[0][0], found[0][2]
def download(dest: str, force: bool, state: bool, quiet: bool, stores: Sequence[str]) -> None:
name = os.path.basename(dest)
if not stores:
stores = list(PUBLIC_STORES)
if redhat_network():
stores += REDHAT_STORES
image_upload_store = os.environ.get('COCKPIT_IMAGE_UPLOAD_STORE')
if image_upload_store:
# NB: This is an *addition* to the built-in stores, used for
# testing. Compare with image-upload which *only* uploads to this
# store, if it's present.
stores += [image_upload_store]
# The time condition for If-Modified-Since
exists = not force and os.path.exists(dest)
if exists:
since = dest
else:
since = EPOCH
result = find(name, stores, latest=state, quiet=quiet)
# If we couldn't find the file, but it exists, we're good
if result is None:
if exists:
return
raise RuntimeError(f"image-download: couldn't find file anywhere: {name}")
args, message = result
show_status(quiet, 'selected', urllib.parse.urljoin(message, name))
temp = dest + ".partial"
# Adjust the arguments above that worked to make it visible and download real stuff
args.append("--show-error")
if not quiet and os.isatty(sys.stdout.fileno()):
args.append("--progress-bar")
else:
args.append("--silent")
args.append("--remote-time")
args.append("--time-cond")
args.append(since)
args.append("--output")
args.append(temp)
if os.path.exists(temp):
if force:
os.remove(temp)
else:
args.append("-C")
args.append("-")
# Always create the destination file (because --state)
else:
open(temp, 'a').close()
curl = subprocess.Popen(curl_cmd(args))
ret = curl.wait()
if ret != 0:
raise RuntimeError(f"curl: unable to download {message} (returned: {ret})")
os.chmod(temp, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
# Due to time-cond the file size may be zero
# A new file downloaded, put it in place
if not exists or os.path.getsize(temp) > 0:
shutil.move(temp, dest)
# Calculate a place to put images where links are not committed in git
def state_target(path: str) -> str:
data_dir = get_images_data_dir()
os.makedirs(data_dir, mode=0o775, exist_ok=True)
return os.path.join(data_dir, path)
# Calculate a place to put images where links are committed in git
def committed_target(image: str) -> str:
link = os.path.join(IMAGES_DIR, image)
if not os.path.islink(link):
raise RuntimeError("image link does not exist: " + image)
dest = os.readlink(link)
relative_dir = os.path.dirname(os.path.abspath(link))
full_dest = os.path.join(relative_dir, dest)
while os.path.islink(full_dest):
link = full_dest
dest = os.readlink(link)
relative_dir = os.path.dirname(os.path.abspath(link))
full_dest = os.path.join(relative_dir, dest)
dest = os.path.join(get_images_data_dir(), dest)
# We have the file but there is not valid link
if os.path.exists(dest):
try:
os.symlink(dest, os.path.join(IMAGES_DIR, os.readlink(link)))
except FileExistsError:
# can happen in unclean trees and deleting the image in the cache dir directly
pass
# The image file in the images directory, may be same as dest
image_file = os.path.join(IMAGES_DIR, os.readlink(link))
# Double check that symlink in place
if os.path.abspath(dest) != os.path.abspath(image_file):
try:
os.symlink(os.path.abspath(dest), image_file)
except FileExistsError:
# .. but never make a cycle
pass
return dest
@contextlib.contextmanager
def wait_lock(target: str) -> Iterator[None]:
lockfile = os.path.join(os.path.dirname(target), ".lock." + os.path.basename(target))
# we need to keep the lock fd open throughout the entire runtime, so remember it in a global-scoped variable
with open(lockfile, "w") as file:
for retry in range(360):
try:
fcntl.flock(file, fcntl.LOCK_NB | fcntl.LOCK_EX)
break
except BlockingIOError:
if retry == 0:
print("Waiting for concurrent image-download of %s..." % os.path.basename(target))
time.sleep(10)
else:
raise TimeoutError("timed out waiting for concurrent downloads of %s\n" % target)
yield
# clean up lock file
try:
os.unlink(lockfile)
except FileNotFoundError:
# parallel runs may remove it already
pass
def download_images(image_list: Sequence[str], force: bool, quiet: bool, state: bool, stores: Sequence[str]) -> None:
data_dir = get_images_data_dir()
os.makedirs(data_dir, exist_ok=True)
# A default set of images are all links in git. These links have
# no directory part. Other links might exist, such as the
# auxiliary links created by committed_target above, and we ignore
# them.
if not image_list:
image_list = []
if not state:
for filename in os.listdir(IMAGES_DIR):
link = os.path.join(IMAGES_DIR, filename)
if os.path.islink(link) and os.path.dirname(os.readlink(link)) == "":
image_list.append(filename)
for image in image_list:
image = get_test_image(image)
if state:
target = state_target(image)
else:
target = committed_target(image)
# don't download the same thing multiple times in parallel
with wait_lock(target):
if force or state or not os.path.exists(target):
download(target, force, state, quiet, stores)
def main() -> None:
parser = argparse.ArgumentParser(description='Download a bot state or images')
parser.add_argument("--force", action="store_true", help="Force unnecessary downloads")
parser.add_argument("--store", action="append", help="Where to find state or images")
parser.add_argument("--quiet", action="store_true", help="Make downloading quieter")
parser.add_argument("--state", action="store_true", help="Images or state not recorded in git")
parser.add_argument('image', nargs='*')
args = parser.parse_args()
download_images(args.image, args.force, args.quiet, args.state, args.store)
if __name__ == '__main__':
main()