|
1 | 1 | import json |
2 | 2 | import os |
3 | 3 |
|
| 4 | +import requests |
| 5 | + |
4 | 6 | from flask import g, abort, Response, send_file, request |
5 | 7 | from flask_restplus import Resource |
6 | 8 |
|
7 | 9 | from pyinfraboxutils import get_logger |
8 | 10 | from pyinfraboxutils.ibflask import auth_required, OK |
9 | 11 | from pyinfraboxutils.storage import storage |
10 | 12 | from api.namespaces import project as ns |
| 13 | +from pyinfraboxutils.token import encode_user_token |
11 | 14 |
|
12 | 15 | logger = get_logger('api') |
13 | 16 |
|
@@ -299,20 +302,50 @@ class ArchiveDownload(Resource): |
299 | 302 |
|
300 | 303 | @auth_required(['user'], allow_if_public=True) |
301 | 304 | def get(self, project_id, job_id): |
302 | | - f = request.args.get('filename', None) |
| 305 | + filename = request.args.get('filename', None) |
303 | 306 |
|
304 | | - if not f: |
| 307 | + if not filename: |
305 | 308 | abort(404) |
306 | 309 |
|
307 | | - key = '%s/%s' % (job_id, f) |
308 | | - f = storage.download_archive(key) |
| 310 | + result = g.db.execute_one_dict(''' |
| 311 | + SELECT cluster_name |
| 312 | + FROM job |
| 313 | + WHERE id = %s |
| 314 | + AND project_id = %s |
| 315 | + ''', [job_id, project_id]) |
| 316 | + |
| 317 | + if not result or not result['cluster_name']: |
| 318 | + abort(404) |
| 319 | + |
| 320 | + job_cluster = result['cluster_name'] |
| 321 | + key = '%s/%s' % (job_id, filename) |
| 322 | + |
| 323 | + if os.environ['INFRABOX_CLUSTER_NAME'] == job_cluster: |
| 324 | + f = storage.download_archive(key) |
| 325 | + else: |
| 326 | + c = g.db.execute_one_dict(''' |
| 327 | + SELECT * |
| 328 | + FROM cluster |
| 329 | + WHERE name=%s |
| 330 | + ''', [job_cluster]) |
| 331 | + url = '%s/api/v1/projects/%s/jobs/%s/archive/download?filename=%s' % (c['root_url'], project_id, job_id, filename) |
| 332 | + try: |
| 333 | + token = encode_user_token(g.token['user']['id']) |
| 334 | + except AttributeError: |
| 335 | + #public project has no token here. |
| 336 | + token = "" |
| 337 | + headers = {'Authorization': 'bearer ' + token} |
| 338 | + logger.info('get archive %s from %s', [filename, url]) |
| 339 | + |
| 340 | + # TODO(ib-steffen): allow custom ca bundles |
| 341 | + r = requests.get(url,headers=headers, timeout=120, verify=False, stream=True) |
| 342 | + f = r.raw |
309 | 343 |
|
310 | 344 | if not f: |
311 | 345 | logger.error(key) |
312 | 346 | abort(404) |
313 | 347 |
|
314 | | - return send_file(f, as_attachment=True, attachment_filename=os.path.basename(f)) |
315 | | - |
| 348 | + return send_file(f, as_attachment=True, attachment_filename=os.path.basename(filename)) |
316 | 349 |
|
317 | 350 | @ns.route('/<project_id>/jobs/<job_id>/archive') |
318 | 351 | class Archive(Resource): |
|
0 commit comments