|
| 1 | +import os |
1 | 2 | import pydoc |
| 3 | +import zipfile |
2 | 4 |
|
| 5 | +import click |
| 6 | +import progressbar |
| 7 | +import requests |
3 | 8 | import terminaltables |
| 9 | +from requests_toolbelt.multipart import encoder |
4 | 10 |
|
5 | 11 | from paperspace import logger, constants, client, config |
| 12 | +from paperspace.commands import CommandBase |
| 13 | +from paperspace.exceptions import PresignedUrlUnreachableException, S3UploadFailedException |
6 | 14 | from paperspace.logger import log_response |
7 | 15 | from paperspace.utils import get_terminal_lines |
8 | 16 |
|
| 17 | +# from clint.textui.progress import Bar as ProgressBar |
| 18 | + |
9 | 19 | experiments_api = client.API(config.CONFIG_EXPERIMENTS_HOST, headers=client.default_headers) |
10 | 20 |
|
11 | 21 |
|
12 | | -def _log_create_experiment(response, success_msg_template, error_msg, logger_=logger): |
13 | | - if response.ok: |
14 | | - j = response.json() |
15 | | - handle = j["handle"] |
16 | | - msg = success_msg_template.format(handle) |
17 | | - logger_.log(msg) |
18 | | - else: |
19 | | - try: |
20 | | - data = response.json() |
21 | | - logger_.log_error_response(data) |
22 | | - except ValueError: |
23 | | - logger_.log(error_msg) |
| 22 | +class ExperimentCommand(CommandBase): |
| 23 | + def _log_create_experiment(self, response, success_msg_template, error_msg): |
| 24 | + if response.ok: |
| 25 | + j = response.json() |
| 26 | + handle = j["handle"] |
| 27 | + msg = success_msg_template.format(handle) |
| 28 | + self.logger.log(msg) |
| 29 | + else: |
| 30 | + try: |
| 31 | + data = response.json() |
| 32 | + self.logger.log_error_response(data) |
| 33 | + except ValueError: |
| 34 | + self.logger.log(error_msg) |
| 35 | + |
| 36 | + |
| 37 | +class CreateExperimentCommand(ExperimentCommand): |
| 38 | + def retrieve_file_paths(self, dirName): |
| 39 | + |
| 40 | + # setup file paths variable |
| 41 | + filePaths = [] |
| 42 | + exclude = ['.git'] |
| 43 | + # Read all directory, subdirectories and file lists |
| 44 | + for root, dirs, files in os.walk(dirName, topdown=True): |
| 45 | + dirs[:] = [d for d in dirs if d not in exclude] |
| 46 | + for filename in files: |
| 47 | + # Create the full filepath by using os module. |
| 48 | + filePath = os.path.join(root, filename) |
| 49 | + filePaths.append(filePath) |
| 50 | + |
| 51 | + # return all paths |
| 52 | + return filePaths |
| 53 | + |
| 54 | + def _zip_workspace(self, workspace_path): |
| 55 | + if not workspace_path: |
| 56 | + workspace_path = '.' |
| 57 | + zip_file_name = os.path.basename(os.getcwd()) + '.zip' |
| 58 | + else: |
| 59 | + zip_file_name = os.path.basename(workspace_path) + '.zip' |
| 60 | + |
| 61 | + zip_file_path = os.path.join(workspace_path, zip_file_name) |
| 62 | + |
| 63 | + if os.path.exists(zip_file_path): |
| 64 | + self.logger.log('Removing existing archive') |
| 65 | + os.remove(zip_file_path) |
| 66 | + |
| 67 | + file_paths = self.retrieve_file_paths(workspace_path) |
| 68 | + |
| 69 | + self.logger.log('Creating zip archive: %s' % zip_file_name) |
| 70 | + zip_file = zipfile.ZipFile(zip_file_path, 'w') |
| 71 | + |
| 72 | + bar = progressbar.ProgressBar(max_value=len(file_paths)) |
| 73 | + |
| 74 | + with zip_file: |
| 75 | + i = 0 |
| 76 | + for file in file_paths: |
| 77 | + i+=1 |
| 78 | + self.logger.debug('Adding %s to archive' % file) |
| 79 | + zip_file.write(file) |
| 80 | + bar.update(i) |
| 81 | + bar.finish() |
| 82 | + self.logger.log('\nFinished creating archive: %s' % zip_file_name) |
| 83 | + return zip_file_path |
| 84 | + |
| 85 | + def _create_callback(self, encoder_obj): |
| 86 | + bar = progressbar.ProgressBar(max_value=encoder_obj.len) |
| 87 | + |
| 88 | + def callback(monitor): |
| 89 | + bar.update(monitor.bytes_read) |
| 90 | + if monitor.bytes_read == monitor.len: |
| 91 | + bar.finish() |
| 92 | + return callback |
| 93 | + |
| 94 | + def _upload_workspace(self, input_data): |
| 95 | + workspace_url = input_data.get('workspaceUrl') |
| 96 | + workspace_path = input_data.get('workspacePath') |
| 97 | + workspace_archive = input_data.get('workspaceArchive') |
| 98 | + if (workspace_archive and workspace_path) or (workspace_archive and workspace_url) or ( |
| 99 | + workspace_path and workspace_url): |
| 100 | + raise click.UsageError("Use either:\n\t--workspaceUrl to point repository URL" |
| 101 | + "\n\t--workspacePath to point on project directory" |
| 102 | + "\n\t--workspaceArchive to point on project ZIP archive" |
| 103 | + "\n or neither to use current directory") |
| 104 | + |
| 105 | + if workspace_url: |
| 106 | + return # nothing to do |
| 107 | + |
| 108 | + if workspace_archive: |
| 109 | + archive_path = os.path.abspath(workspace_archive) |
| 110 | + else: |
| 111 | + archive_path = self._zip_workspace(workspace_path) |
| 112 | + |
| 113 | + s3_upload_data = self._get_upload_data(os.path.basename(archive_path)) |
| 114 | + |
| 115 | + self.logger.log('Uploading zipped workspace to S3') |
| 116 | + |
| 117 | + files = {'file': (archive_path, open(archive_path, 'rb'))} |
| 118 | + fields = s3_upload_data['fields'] |
| 119 | + fields.update(files) |
| 120 | + |
| 121 | + s3_encoder = encoder.MultipartEncoder(fields=fields) |
| 122 | + monitor = encoder.MultipartEncoderMonitor(s3_encoder, callback=self._create_callback(s3_encoder)) |
| 123 | + s3_response = requests.post(s3_upload_data['url'], data=monitor, headers={'Content-Type': monitor.content_type}) |
| 124 | + if not s3_response.ok: |
| 125 | + raise S3UploadFailedException(s3_response) |
| 126 | + |
| 127 | + self.logger.log('\nUploading completed') |
| 128 | + s3_workspace_url = s3_response.headers.get('Location') |
| 129 | + return s3_workspace_url |
| 130 | + |
| 131 | + def execute(self, json_): |
| 132 | + workspace_url = self._upload_workspace(json_) |
| 133 | + if workspace_url: |
| 134 | + json_['workspaceUrl'] = workspace_url |
24 | 135 |
|
| 136 | + response = self.api.post("/experiments/", json=json_) |
25 | 137 |
|
26 | | -def create_experiment(json_, api=experiments_api): |
27 | | - response = api.post("/experiments/", json=json_) |
| 138 | + self._log_create_experiment(response, |
| 139 | + "New experiment created with handle: {}", |
| 140 | + "Unknown error while creating the experiment") |
28 | 141 |
|
29 | | - _log_create_experiment(response, |
30 | | - "New experiment created with handle: {}", |
31 | | - "Unknown error while creating the experiment") |
| 142 | + def _get_upload_data(self, file_name): |
| 143 | + response = self.api.get("/workspace/get_presigned_url", params={'workspaceName': file_name}) |
| 144 | + if response.status_code == 404: |
| 145 | + raise PresignedUrlUnreachableException |
| 146 | + return response.json() |
32 | 147 |
|
33 | 148 |
|
34 | | -def create_and_start_experiment(json_, api=experiments_api): |
35 | | - response = api.post("/experiments/create_and_start/", json=json_) |
36 | | - _log_create_experiment(response, |
37 | | - "New experiment created and started with handle: {}", |
38 | | - "Unknown error while creating/starting the experiment") |
| 149 | +class CreateAndStartExperimentCommand(ExperimentCommand): |
| 150 | + def execute(self, json_): |
| 151 | + response = self.api.post("/experiments/create_and_start/", json=json_) |
| 152 | + self._log_create_experiment(response, |
| 153 | + "New experiment created and started with handle: {}", |
| 154 | + "Unknown error while creating/starting the experiment") |
39 | 155 |
|
40 | 156 |
|
41 | 157 | def start_experiment(experiment_handle, api=experiments_api): |
|
0 commit comments