/
usecase.py
367 lines (291 loc) · 14.3 KB
/
usecase.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
# Copyright Swiss Data Science Center (SDSC). A partnership between
# École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Template use cases."""
import json
import os
import tempfile
from pathlib import Path
from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Union
import click
from pydantic import validate_arguments
from renku.command.command_builder.command import inject
from renku.command.view_model.template import TemplateChangeViewModel, TemplateViewModel
from renku.core import errors
from renku.core.interface.project_gateway import IProjectGateway
from renku.core.template.template import (
FileAction,
RepositoryTemplates,
TemplateAction,
copy_template_to_project,
fetch_templates_source,
get_file_actions,
has_template_checksum,
read_template_checksum,
set_template_parameters,
write_template_checksum,
)
from renku.core.util import communication
from renku.core.util.metadata import is_renku_project, replace_renku_version_in_dockerfile
from renku.core.util.tabulate import tabulate
from renku.domain_model.project import Project
from renku.domain_model.project_context import project_context
from renku.domain_model.template import (
RenderedTemplate,
Template,
TemplateMetadata,
TemplatesSource,
calculate_dockerfile_checksum,
)
from renku.infrastructure.repository import DiffLineChangeType, Repository
def update_dockerfile_checksum(new_checksum: str):
"""Update ``Dockerfile`` template checksum if possible."""
if not project_context.dockerfile_path.exists():
raise errors.DockerfileUpdateError("Project doesn't have a Dockerfile")
if is_dockerfile_updated_by_user():
raise errors.DockerfileUpdateError("Cannot update Dockerfile checksum because it was updated by the user")
checksums = read_template_checksum()
checksums["Dockerfile"] = new_checksum
write_template_checksum(checksums)
def does_dockerfile_contain_only_version_change() -> bool:
"""Return True if Dockerfile only contains Renku version changes."""
commits = list(project_context.repository.iterate_commits(project_context.dockerfile_path))
# NOTE: Don't include the first commit that added the Dockerfile
for commit in commits[:-1]:
changes = commit.get_changes(project_context.dockerfile_path, patch=True)
if not changes:
continue
diff = changes[0].diff
# NOTE: Check the Dockerfile change only includes adding and removing a Renku version line
if (
len(diff) != 2
or {c.change_type for c in diff} != {DiffLineChangeType.ADDED, DiffLineChangeType.DELETED}
or any("ARG RENKU_VERSION=" not in c.text for c in diff)
):
return False
return True
def is_dockerfile_updated_by_user() -> bool:
"""Return if user modified the ``Dockerfile``."""
dockerfile = project_context.dockerfile_path
if not has_template_checksum() or not dockerfile.exists():
return False
original_checksum = read_template_checksum().get("Dockerfile")
current_checksum = calculate_dockerfile_checksum(dockerfile=dockerfile)
if original_checksum == current_checksum: # Dockerfile was never updated
return False
# NOTE: Check if original Dockerfile has the same checksum as the time when the template was set/updated
metadata = json.loads(project_context.project.template_metadata.metadata)
original_renku_version = metadata.get("__renku_version__")
original_dockerfile_content = replace_renku_version_in_dockerfile(dockerfile.read_text(), original_renku_version)
original_calculated_checksum = calculate_dockerfile_checksum(dockerfile_content=original_dockerfile_content)
if original_checksum == original_calculated_checksum:
return False
return False if does_dockerfile_contain_only_version_change() else True
@validate_arguments(config=dict(arbitrary_types_allowed=True))
def list_templates(source: Optional[str], reference: Optional[str]) -> List[TemplateViewModel]:
"""Return available templates from a source."""
templates_source = fetch_templates_source(source=source, reference=reference)
return [TemplateViewModel.from_template(t) for t in templates_source.templates]
@validate_arguments(config=dict(arbitrary_types_allowed=True))
def show_template(source: Optional[str], reference: Optional[str], id: Optional[str]) -> TemplateViewModel:
"""Show template details."""
if source or id:
templates_source = fetch_templates_source(source=source, reference=reference)
template = templates_source.get_template(id=id, reference=None)
elif is_renku_project():
metadata = TemplateMetadata.from_project(project=project_context.project)
templates_source = fetch_templates_source(source=metadata.source, reference=metadata.reference)
id = metadata.id
template = templates_source.get_template(id=id, reference=None)
else:
raise errors.ParameterError("No Renku project found")
if template is None:
raise errors.TemplateNotFoundError(f"The template with id '{id}' is not available")
return TemplateViewModel.from_template(template)
def check_for_template_update(project: Optional[Project]) -> Tuple[bool, bool, Optional[str], Optional[str]]:
"""Check if the project can be updated to a newer version of the project template."""
metadata = TemplateMetadata.from_project(project=project)
templates_source = fetch_templates_source(source=metadata.source, reference=metadata.reference)
update_available, latest_reference = templates_source.is_update_available(
id=metadata.id, reference=metadata.reference, version=metadata.version
)
return update_available, metadata.allow_update, metadata.reference, latest_reference
@validate_arguments(config=dict(arbitrary_types_allowed=True))
def set_template(
source: Optional[str],
reference: Optional[str],
id: Optional[str],
force: bool,
interactive: bool,
input_parameters: Optional[Dict[str, str]],
dry_run: bool,
) -> TemplateChangeViewModel:
"""Set template for a project."""
project = project_context.project
if project.template_metadata.template_source and not force:
raise errors.TemplateUpdateError("Project already has a template: To set a template use '-f/--force' flag")
templates_source = fetch_templates_source(source=source, reference=reference)
template = select_template(templates_source, id=id)
if template is None:
raise errors.TemplateNotFoundError(f"The template with id '{id}' is not available")
rendered_template, actions = _set_or_update_project_from_template(
templates_source=templates_source,
reference=template.reference,
id=template.id,
interactive=interactive,
dry_run=dry_run,
template_action=TemplateAction.SET,
input_parameters=input_parameters,
)
return TemplateChangeViewModel.from_template(template=rendered_template, actions=actions)
@validate_arguments(config=dict(arbitrary_types_allowed=True))
def update_template(force: bool, interactive: bool, dry_run: bool) -> Optional[TemplateChangeViewModel]:
"""Update project's template if possible. Return corresponding viewmodel if updated."""
template_metadata = TemplateMetadata.from_project(project=project_context.project)
if not template_metadata.source:
raise errors.TemplateUpdateError("Project doesn't have a template: Use 'renku template set'")
if not has_template_checksum() and not interactive:
raise errors.TemplateUpdateError("Required template metadata doesn't exist: Use '-i/--interactive' flag")
if not template_metadata.allow_update and not force:
raise errors.TemplateUpdateError(
"Update is not allowed for this template. You can still update it using '-f/--force' flag but it might "
"break your project"
)
try:
templates_source = fetch_templates_source(
source=template_metadata.source, reference=template_metadata.reference
)
except errors.TemplateMissingReferenceError as e:
message = f"{str(e)}; You can still manually update the template and set a difference reference."
raise errors.TemplateUpdateError(message)
except errors.InvalidTemplateError:
raise errors.TemplateUpdateError("Template cannot be fetched.")
update_available, latest_reference = templates_source.is_update_available(
id=template_metadata.id, reference=template_metadata.reference, version=template_metadata.version
)
if not update_available:
return None
rendered_template, actions = _set_or_update_project_from_template(
templates_source=templates_source,
reference=latest_reference,
id=template_metadata.id,
interactive=interactive,
dry_run=dry_run,
template_action=TemplateAction.UPDATE,
input_parameters=None,
)
return TemplateChangeViewModel.from_template(
template=rendered_template, actions=actions, old_id=template_metadata.id
)
@inject.autoparams("project_gateway")
def _set_or_update_project_from_template(
templates_source: TemplatesSource,
reference: str,
id: str,
interactive,
dry_run: bool,
template_action: TemplateAction,
input_parameters,
project_gateway: IProjectGateway,
) -> Tuple[RenderedTemplate, Dict[str, FileAction]]:
"""Update project files and metadata from a template."""
if interactive and not communication.has_prompt():
raise errors.ParameterError("Cannot use interactive mode with no prompt")
input_parameters = input_parameters or {}
project = project_gateway.get_project()
template = templates_source.get_template(id=id, reference=reference)
if template is None:
raise errors.TemplateNotFoundError(f"The template with id '{id}' is not available")
template_metadata = TemplateMetadata.from_project(project=project_context.project)
template_metadata.update(template=template)
if not dry_run:
set_template_parameters(
template=template,
template_metadata=template_metadata,
input_parameters=input_parameters,
interactive=interactive,
)
rendered_template = template.render(metadata=template_metadata)
actions = get_file_actions(
rendered_template=rendered_template, template_action=template_action, interactive=interactive and not dry_run
)
if not dry_run:
copy_template_to_project(rendered_template=rendered_template, project=project, actions=actions)
project_gateway.update_project(project)
return rendered_template, actions
def select_template(templates_source: TemplatesSource, id: Optional[str] = None) -> Optional[Template]:
"""Select a template from a template source."""
def prompt_to_select_template():
if not communication.has_prompt():
raise errors.InvalidTemplateError("Cannot select a template")
class Selection(NamedTuple):
number: int
id: str
templates = [Selection(number=i, id=t.id) for i, t in enumerate(templates_source.templates, start=1)]
tables = tabulate(templates, headers=["number", "id"])
message = f"{tables}\nPlease choose a template by typing its number"
template_index = communication.prompt(
msg=message, type=click.IntRange(1, len(templates_source.templates)), show_default=False, show_choices=False
)
return templates_source.templates[template_index - 1]
if id:
try:
return templates_source.get_template(id=id, reference=None)
except errors.TemplateNotFoundError:
raise errors.TemplateNotFoundError(f"The template with id '{id}' is not available")
elif len(templates_source.templates) == 1:
return templates_source.templates[0]
return prompt_to_select_template()
@validate_arguments(config=dict(arbitrary_types_allowed=True))
def validate_templates(
source: Optional[str] = None, reference: Optional[str] = None
) -> Dict[str, Union[str, Dict[str, List[str]]]]:
"""Validate a template repository.
Args:
source(str, optional): Remote repository URL to clone and check (Default value = None).
reference(str, optional): Git commit/branch/tag to check (Default value = None).
Returns:
Dict[str, Union[str, Dict[str, List[str]]]]: Dictionary containing errors and warnings for manifest and
templates, along with a ``valid`` field telling if all checks passed.
"""
if source is not None:
path = Path(tempfile.mkdtemp())
repo = Repository.clone_from(path=path, url=source)
repo.checkout(reference=reference)
else:
path = Path(os.getcwd())
repo = Repository(path=path)
if reference is not None:
path = Path(tempfile.mkdtemp())
repo.create_worktree(path, reference=reference)
repo = Repository(path=path)
version = repo.head.commit.hexsha
result: Dict[str, Any] = {"manifest": None, "templates": {}, "warnings": [], "valid": True}
try:
template_source = RepositoryTemplates(
path=path, source=path, reference="", version=version, repository=repo, skip_validation=True
)
result["warnings"] = template_source.manifest.validate(manifest_only=True)
except errors.InvalidTemplateError as e:
result["manifest"] = e.args[0] if e.args else str(e)
result["valid"] = False
return result
for template in template_source.manifest.templates:
template.templates_source = template_source
issues = template.validate(skip_files=False, raise_errors=False)
if issues:
result["templates"][template.id] = issues
result["valid"] = False
return result