-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathclient.py
More file actions
305 lines (257 loc) · 9.28 KB
/
client.py
File metadata and controls
305 lines (257 loc) · 9.28 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
# Copyright 2026 The Feast Authors
#
# 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
#
# https://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.
"""
Feast OpenLineage Client.
This module provides a wrapper around the OpenLineage client that is
specifically designed for Feast Feature Store operations.
"""
import logging
from typing import TYPE_CHECKING, Any, Dict, List, Optional
if TYPE_CHECKING:
from feast import FeatureStore
from feast.openlineage.config import OpenLineageConfig
try:
from openlineage.client import OpenLineageClient
from openlineage.client.event_v2 import (
DatasetEvent,
Job,
JobEvent,
Run,
RunEvent,
RunState,
set_producer,
)
OPENLINEAGE_AVAILABLE = True
except ImportError:
OPENLINEAGE_AVAILABLE = False
OpenLineageClient = None # type: ignore[misc,assignment]
logger = logging.getLogger(__name__)
class FeastOpenLineageClient:
"""
OpenLineage client wrapper for Feast Feature Store.
This client provides convenient methods for emitting OpenLineage events
from Feast operations like materialization, feature retrieval, and
registry changes.
Example:
from feast.openlineage import FeastOpenLineageClient, OpenLineageConfig
config = OpenLineageConfig(
transport_type="http",
transport_url="http://localhost:5000",
)
client = FeastOpenLineageClient(config)
# Emit lineage for a feature store
client.emit_registry_lineage(feature_store.registry)
"""
def __init__(
self,
config: Optional[OpenLineageConfig] = None,
feature_store: Optional["FeatureStore"] = None,
):
"""
Initialize the Feast OpenLineage client.
Args:
config: OpenLineage configuration. If not provided, will try to
load from environment variables.
feature_store: Optional FeatureStore instance for context.
"""
if not OPENLINEAGE_AVAILABLE:
logger.warning(
"OpenLineage is not installed. Lineage events will not be emitted. "
"Install with: pip install openlineage-python"
)
self._client = None
self._config = config or OpenLineageConfig(enabled=False)
self._feature_store = feature_store
return
self._config = config or OpenLineageConfig.from_env()
self._feature_store = feature_store
if not self._config.enabled:
logger.info("OpenLineage integration is disabled")
self._client = None
return
# Set producer
set_producer(self._config.producer)
# Initialize the OpenLineage client
try:
transport_config = self._config.get_transport_config()
self._client = OpenLineageClient(config={"transport": transport_config})
logger.info(
f"OpenLineage client initialized with {self._config.transport_type} transport"
)
except Exception as e:
logger.error(f"Failed to initialize OpenLineage client: {e}")
self._client = None
@property
def is_enabled(self) -> bool:
"""Check if the OpenLineage client is enabled and available."""
return self._client is not None and self._config.enabled
@property
def config(self) -> OpenLineageConfig:
"""Get the OpenLineage configuration."""
return self._config
@property
def namespace(self) -> str:
"""Get the default namespace."""
return self._config.namespace
def emit(self, event: Any) -> bool:
"""
Emit an OpenLineage event.
Args:
event: OpenLineage event (RunEvent, DatasetEvent, or JobEvent)
Returns:
True if the event was emitted successfully, False otherwise
"""
if not self.is_enabled or self._client is None:
logger.debug("OpenLineage is disabled, skipping event emission")
return False
try:
self._client.emit(event)
return True
except Exception as e:
logger.error(f"Failed to emit OpenLineage event: {e}")
return False
def emit_run_event(
self,
job_name: str,
run_id: str,
event_type: "RunState",
inputs: Optional[List[Any]] = None,
outputs: Optional[List[Any]] = None,
job_facets: Optional[Dict[str, Any]] = None,
run_facets: Optional[Dict[str, Any]] = None,
namespace: Optional[str] = None,
) -> bool:
"""
Emit a RunEvent for a Feast operation.
Args:
job_name: Name of the job
run_id: Unique run identifier (UUID)
event_type: Type of event (START, COMPLETE, FAIL, etc.)
inputs: List of input datasets
outputs: List of output datasets
job_facets: Additional job facets
run_facets: Additional run facets
namespace: Optional namespace for the job (defaults to client namespace)
Returns:
True if successful, False otherwise
"""
if not self.is_enabled:
return False
from datetime import datetime, timezone
try:
event = RunEvent(
eventTime=datetime.now(timezone.utc).isoformat(),
eventType=event_type,
run=Run(runId=run_id, facets=run_facets or {}),
job=Job(
namespace=namespace or self.namespace,
name=job_name,
facets=job_facets or {},
),
inputs=inputs or [],
outputs=outputs or [],
)
return self.emit(event)
except Exception as e:
logger.error(f"Failed to create RunEvent: {e}")
return False
def emit_dataset_event(
self,
dataset_name: str,
namespace: Optional[str] = None,
facets: Optional[Dict[str, Any]] = None,
) -> bool:
"""
Emit a DatasetEvent for a Feast dataset (data source, feature view).
Args:
dataset_name: Name of the dataset
namespace: Optional namespace (defaults to client namespace)
facets: Dataset facets
Returns:
True if successful, False otherwise
"""
if not self.is_enabled:
return False
from datetime import datetime, timezone
from openlineage.client.event_v2 import StaticDataset
try:
event = DatasetEvent(
eventTime=datetime.now(timezone.utc).isoformat(),
dataset=StaticDataset(
namespace=namespace or self.namespace,
name=dataset_name,
facets=facets or {},
),
)
return self.emit(event)
except Exception as e:
logger.error(f"Failed to create DatasetEvent: {e}")
return False
def emit_job_event(
self,
job_name: str,
inputs: Optional[List[Any]] = None,
outputs: Optional[List[Any]] = None,
job_facets: Optional[Dict[str, Any]] = None,
) -> bool:
"""
Emit a JobEvent for a Feast job definition.
Args:
job_name: Name of the job
inputs: List of input datasets
outputs: List of output datasets
job_facets: Job facets
Returns:
True if successful, False otherwise
"""
if not self.is_enabled:
return False
from datetime import datetime, timezone
try:
event = JobEvent(
eventTime=datetime.now(timezone.utc).isoformat(),
job=Job(
namespace=self.namespace,
name=job_name,
facets=job_facets or {},
),
inputs=inputs or [],
outputs=outputs or [],
)
return self.emit(event)
except Exception as e:
logger.error(f"Failed to create JobEvent: {e}")
return False
def close(self, timeout: float = 5.0) -> bool:
"""
Close the OpenLineage client and flush any pending events.
Args:
timeout: Maximum time to wait for pending events
Returns:
True if closed successfully, False otherwise
"""
if self._client is not None:
try:
return self._client.close(timeout)
except Exception as e:
logger.error(f"Error closing OpenLineage client: {e}")
return False
return True
def __enter__(self):
"""Context manager entry."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit."""
self.close()
return False