-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathrepo_operations.py
More file actions
516 lines (438 loc) · 18.8 KB
/
repo_operations.py
File metadata and controls
516 lines (438 loc) · 18.8 KB
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
import base64
import importlib
import json
import logging
import os
import random
import re
import sys
import tempfile
from importlib.abc import Loader
from importlib.machinery import ModuleSpec
from pathlib import Path
from typing import List, Optional, Set, Union
import click
from click.exceptions import BadParameter
from feast import PushSource
from feast.batch_feature_view import BatchFeatureView
from feast.constants import FEATURE_STORE_YAML_ENV_NAME
from feast.data_source import DataSource, KafkaSource, KinesisSource
from feast.diff.registry_diff import extract_objects_for_keep_delete_update_add
from feast.entity import Entity
from feast.feature_service import FeatureService
from feast.feature_store import FeatureStore
from feast.feature_view import DUMMY_ENTITY, FeatureView
from feast.file_utils import replace_str_in_file
from feast.infra.registry.base_registry import BaseRegistry
from feast.infra.registry.registry import FEAST_OBJECT_TYPES, FeastObjectType, Registry
from feast.names import adjectives, animals
from feast.on_demand_feature_view import OnDemandFeatureView
from feast.permissions.permission import Permission
from feast.project import Project
from feast.repo_config import RepoConfig
from feast.repo_contents import RepoContents
from feast.stream_feature_view import StreamFeatureView
logger = logging.getLogger(__name__)
def py_path_to_module(path: Path) -> str:
return (
str(path.relative_to(os.getcwd()))[: -len(".py")]
.replace("./", "")
.replace("/", ".")
.replace("\\", ".")
)
def read_feastignore(repo_root: Path) -> List[str]:
"""Read .feastignore in the repo root directory (if exists) and return the list of user-defined ignore paths"""
feast_ignore = repo_root / ".feastignore"
if not feast_ignore.is_file():
return []
lines = feast_ignore.read_text().strip().split("\n")
ignore_paths = []
for line in lines:
# Remove everything after the first occurance of "#" symbol (comments)
if line.find("#") >= 0:
line = line[: line.find("#")]
# Strip leading or ending whitespaces
line = line.strip()
# Add this processed line to ignore_paths if it's not empty
if len(line) > 0:
ignore_paths.append(line)
return ignore_paths
def get_ignore_files(repo_root: Path, ignore_paths: List[str]) -> Set[Path]:
"""Get all ignore files that match any of the user-defined ignore paths"""
ignore_files = set()
for ignore_path in ignore_paths:
# ignore_path may contains matchers (* or **). Use glob() to match user-defined path to actual paths
for matched_path in repo_root.glob(ignore_path):
if matched_path.is_file():
# If the matched path is a file, add that to ignore_files set
ignore_files.add(matched_path.resolve())
else:
# Otherwise, list all Python files in that directory and add all of them to ignore_files set
ignore_files |= {
sub_path.resolve()
for sub_path in matched_path.glob("**/*.py")
if sub_path.is_file()
}
return ignore_files
def get_repo_files(repo_root: Path) -> List[Path]:
"""Get the list of all repo files, ignoring undesired files & directories specified in .feastignore"""
# Read ignore paths from .feastignore and create a set of all files that match any of these paths
ignore_paths = read_feastignore(repo_root)
ignore_files = get_ignore_files(repo_root, ignore_paths)
ignore_paths += [
".git",
".feastignore",
".venv",
".pytest_cache",
"__pycache__",
".ipynb_checkpoints",
]
# List all Python files in the root directory (recursively)
repo_files = {
p.resolve()
for p in repo_root.glob("**/*.py")
if p.is_file() and "__init__.py" != p.name
}
# Ignore all files that match any of the ignore paths in .feastignore
repo_files -= ignore_files
# Sort repo_files to read them in the same order every time
return sorted(repo_files)
def parse_repo(repo_root: Path) -> RepoContents:
"""
Collects unique Feast object definitions from the given feature repo.
Specifically, if an object foo has already been added, bar will still be added if
(bar == foo), but not if (bar is foo). This ensures that import statements will
not result in duplicates, but defining two equal objects will.
"""
res = RepoContents(
projects=[],
data_sources=[],
entities=[],
feature_views=[],
feature_services=[],
on_demand_feature_views=[],
stream_feature_views=[],
permissions=[],
)
for repo_file in get_repo_files(repo_root):
module_path = py_path_to_module(repo_file)
module = importlib.import_module(module_path)
for attr_name in dir(module):
obj = getattr(module, attr_name)
if isinstance(obj, DataSource) and not any(
(obj is ds) for ds in res.data_sources
):
res.data_sources.append(obj)
# Handle batch sources defined within stream sources.
if (
isinstance(obj, PushSource)
or isinstance(obj, KafkaSource)
or isinstance(obj, KinesisSource)
):
batch_source = obj.batch_source
if batch_source and not any(
(batch_source is ds) for ds in res.data_sources
):
res.data_sources.append(batch_source)
if (
isinstance(obj, FeatureView)
and not any((obj is fv) for fv in res.feature_views)
and not isinstance(obj, StreamFeatureView)
and not isinstance(obj, BatchFeatureView)
):
res.feature_views.append(obj)
# Handle batch sources defined with feature views.
batch_source = obj.batch_source
assert batch_source
if not any((batch_source is ds) for ds in res.data_sources):
res.data_sources.append(batch_source)
# Handle stream sources defined with feature views.
if obj.stream_source:
stream_source = obj.stream_source
if not any((stream_source is ds) for ds in res.data_sources):
res.data_sources.append(stream_source)
elif isinstance(obj, StreamFeatureView) and not any(
(obj is sfv) for sfv in res.stream_feature_views
):
res.stream_feature_views.append(obj)
# Handle batch sources defined with feature views.
batch_source = obj.batch_source
if not any((batch_source is ds) for ds in res.data_sources):
res.data_sources.append(batch_source)
# Handle stream sources defined with feature views.
assert obj.stream_source
stream_source = obj.stream_source
if not any((stream_source is ds) for ds in res.data_sources):
res.data_sources.append(stream_source)
elif isinstance(obj, BatchFeatureView) and not any(
(obj is bfv) for bfv in res.feature_views
):
res.feature_views.append(obj)
# Handle batch sources defined with feature views.
batch_source = obj.batch_source
if not any((batch_source is ds) for ds in res.data_sources):
res.data_sources.append(batch_source)
elif isinstance(obj, Entity) and not any(
(obj is entity) for entity in res.entities
):
res.entities.append(obj)
elif isinstance(obj, FeatureService) and not any(
(obj is fs) for fs in res.feature_services
):
res.feature_services.append(obj)
elif isinstance(obj, OnDemandFeatureView) and not any(
(obj is odfv) for odfv in res.on_demand_feature_views
):
res.on_demand_feature_views.append(obj)
elif isinstance(obj, Permission) and not any(
(obj is p) for p in res.permissions
):
res.permissions.append(obj)
elif isinstance(obj, Project) and not any((obj is p) for p in res.projects):
res.projects.append(obj)
res.entities.append(DUMMY_ENTITY)
return res
def plan(repo_config: RepoConfig, repo_path: Path, skip_source_validation: bool):
os.chdir(repo_path)
repo = _get_repo_contents(repo_path, repo_config.project)
for project in repo.projects:
repo_config.project = project.name
store, registry = _get_store_and_registry(repo_config)
# TODO: When we support multiple projects in a single repo, we should filter repo contents by project
if not skip_source_validation:
provider = store._get_provider()
data_sources = [t.batch_source for t in repo.feature_views]
# Make sure the data source used by this feature view is supported by Feast
for data_source in data_sources:
provider.validate_data_source(store.config, data_source)
registry_diff, infra_diff, _ = store.plan(repo)
click.echo(registry_diff.to_string())
click.echo(infra_diff.to_string())
def _get_repo_contents(repo_path, project_name: Optional[str] = None):
sys.dont_write_bytecode = True
repo = parse_repo(repo_path)
if len(repo.projects) < 1:
if project_name:
print(
f"No project found in the repository. Using project name {project_name} defined in feature_store.yaml"
)
repo.projects.append(Project(name=project_name))
else:
print(
"No project found in the repository. Either define Project in repository or define a project in feature_store.yaml"
)
sys.exit(1)
elif len(repo.projects) == 1:
if repo.projects[0].name != project_name:
print(
"Project object name should match with the project name defined in feature_store.yaml"
)
sys.exit(1)
else:
print(
"Multiple projects found in the repository. Currently no support for multiple projects"
)
sys.exit(1)
return repo
def _get_store_and_registry(repo_config):
store = FeatureStore(config=repo_config)
registry = store.registry
return store, registry
def extract_objects_for_apply_delete(project, registry, repo):
# TODO(achals): This code path should be refactored to handle added & kept entities separately.
(
_,
objs_to_delete,
objs_to_update,
objs_to_add,
) = extract_objects_for_keep_delete_update_add(registry, project, repo)
all_to_apply: List[
Union[
Entity,
FeatureView,
OnDemandFeatureView,
StreamFeatureView,
FeatureService,
]
] = []
for object_type in FEAST_OBJECT_TYPES:
to_apply = set(objs_to_add[object_type]).union(objs_to_update[object_type])
all_to_apply.extend(to_apply)
all_to_delete: List[
Union[
Entity,
FeatureView,
OnDemandFeatureView,
StreamFeatureView,
FeatureService,
]
] = []
for object_type in FEAST_OBJECT_TYPES:
all_to_delete.extend(objs_to_delete[object_type])
return (
all_to_apply,
all_to_delete,
set(objs_to_add[FeastObjectType.FEATURE_VIEW]).union(
set(objs_to_update[FeastObjectType.FEATURE_VIEW])
),
objs_to_delete[FeastObjectType.FEATURE_VIEW],
)
def apply_total_with_repo_instance(
store: FeatureStore,
project_name: str,
registry: BaseRegistry,
repo: RepoContents,
skip_source_validation: bool,
):
if not skip_source_validation:
provider = store._get_provider()
data_sources = [t.batch_source for t in repo.feature_views]
# Make sure the data source used by this feature view is supported by Feast
for data_source in data_sources:
provider.validate_data_source(store.config, data_source)
# For each object in the registry, determine whether it should be kept or deleted.
(
all_to_apply,
all_to_delete,
views_to_keep,
views_to_delete,
) = extract_objects_for_apply_delete(project_name, registry, repo)
if store._should_use_plan():
registry_diff, infra_diff, new_infra = store.plan(repo)
click.echo(registry_diff.to_string())
store._apply_diffs(registry_diff, infra_diff, new_infra)
click.echo(infra_diff.to_string())
else:
store.apply(all_to_apply, objects_to_delete=all_to_delete, partial=False)
log_infra_changes(views_to_keep, views_to_delete)
def log_infra_changes(
views_to_keep: Set[FeatureView], views_to_delete: Set[FeatureView]
):
from colorama import Fore, Style
for view in views_to_keep:
click.echo(
f"Deploying infrastructure for {Style.BRIGHT + Fore.GREEN}{view.name}{Style.RESET_ALL}"
)
for view in views_to_delete:
click.echo(
f"Removing infrastructure for {Style.BRIGHT + Fore.RED}{view.name}{Style.RESET_ALL}"
)
def create_feature_store(
ctx: click.Context,
) -> FeatureStore:
repo = ctx.obj["CHDIR"]
# If we received a base64 encoded version of feature_store.yaml, use that
config_base64 = os.getenv(FEATURE_STORE_YAML_ENV_NAME)
if config_base64:
print("Received base64 encoded feature_store.yaml")
config_bytes = base64.b64decode(config_base64)
# Create a new unique directory for writing feature_store.yaml
repo_path = Path(tempfile.mkdtemp())
with open(repo_path / "feature_store.yaml", "wb") as f:
f.write(config_bytes)
return FeatureStore(repo_path=str(repo_path.resolve()))
else:
fs_yaml_file = ctx.obj["FS_YAML_FILE"]
cli_check_repo(repo, fs_yaml_file)
return FeatureStore(repo_path=str(repo), fs_yaml_file=fs_yaml_file)
def apply_total(repo_config: RepoConfig, repo_path: Path, skip_source_validation: bool):
os.chdir(repo_path)
repo = _get_repo_contents(repo_path, repo_config.project)
for project in repo.projects:
repo_config.project = project.name
store, registry = _get_store_and_registry(repo_config)
if not is_valid_name(project.name):
print(
f"{project.name} is not valid. Project name should only have "
f"alphanumerical values and underscores but not start with an underscore."
)
sys.exit(1)
# TODO: When we support multiple projects in a single repo, we should filter repo contents by project. Currently there is no way to associate Feast objects to project.
print(f"Applying changes for project {project.name}")
apply_total_with_repo_instance(
store, project.name, registry, repo, skip_source_validation
)
def teardown(repo_config: RepoConfig, repo_path: Optional[str]):
# Cannot pass in both repo_path and repo_config to FeatureStore.
feature_store = FeatureStore(repo_path=repo_path, config=repo_config)
feature_store.teardown()
def registry_dump(repo_config: RepoConfig, repo_path: Path) -> str:
"""For debugging only: output contents of the metadata registry"""
registry_config = repo_config.registry
project = repo_config.project
registry = Registry(
project,
registry_config=registry_config,
repo_path=repo_path,
auth_config=repo_config.auth_config,
)
registry_dict = registry.to_dict(project=project)
return json.dumps(registry_dict, indent=2, sort_keys=True)
def cli_check_repo(repo_path: Path, fs_yaml_file: Path):
sys.path.append(str(repo_path))
if not fs_yaml_file.exists():
print(
f"Can't find feature repo configuration file at {fs_yaml_file}. "
"Make sure you're running feast from an initialized feast repository."
)
sys.exit(1)
def init_repo(repo_name: str, template: str):
import os
from pathlib import Path
from shutil import copytree
from colorama import Fore, Style
if not is_valid_name(repo_name):
raise BadParameter(
message="Name should be alphanumeric values and underscores but not start with an underscore",
param_hint="PROJECT_DIRECTORY",
)
repo_path = Path(os.path.join(Path.cwd(), repo_name))
repo_path.mkdir(exist_ok=True)
repo_config_path = repo_path / "feature_store.yaml"
if repo_config_path.exists():
new_directory = os.path.relpath(repo_path, os.getcwd())
print(
f"The directory {Style.BRIGHT + Fore.GREEN}{new_directory}{Style.RESET_ALL} contains an existing feature "
f"store repository that may cause a conflict"
)
print()
sys.exit(1)
# Copy template directory
template_path = str(Path(Path(__file__).parent / "templates" / template).absolute())
if not os.path.exists(template_path):
raise IOError(f"Could not find template {template}")
copytree(template_path, str(repo_path), dirs_exist_ok=True)
# Rename gitignore files back to .gitignore
for gitignore_path in repo_path.rglob("gitignore"):
gitignore_path.rename(gitignore_path.with_name(".gitignore"))
# Seed the repository
bootstrap_path = repo_path / "bootstrap.py"
if os.path.exists(bootstrap_path):
import importlib.util
spec = importlib.util.spec_from_file_location("bootstrap", str(bootstrap_path))
assert isinstance(spec, ModuleSpec)
bootstrap = importlib.util.module_from_spec(spec)
assert isinstance(spec.loader, Loader)
spec.loader.exec_module(bootstrap)
bootstrap.bootstrap() # type: ignore
os.remove(bootstrap_path)
# Template the feature_store.yaml file
feature_store_yaml_path = repo_path / "feature_repo" / "feature_store.yaml"
replace_str_in_file(
feature_store_yaml_path, "project: my_project", f"project: {repo_name}"
)
# Remove the __pycache__ folder if it exists
import shutil
shutil.rmtree(repo_path / "__pycache__", ignore_errors=True)
import click
click.echo()
click.echo(
f"Creating a new Feast repository in {Style.BRIGHT + Fore.GREEN}{repo_path}{Style.RESET_ALL}."
)
click.echo()
def is_valid_name(name: str) -> bool:
"""A name should be alphanumeric values and underscores but not start with an underscore"""
return not name.startswith("_") and re.compile(r"\W+").search(name) is None
def generate_project_name() -> str:
"""Generates a unique project name"""
return f"{random.choice(adjectives)}_{random.choice(animals)}"