forked from feast-dev/feast
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoffline_server.py
More file actions
332 lines (294 loc) · 12.7 KB
/
Copy pathoffline_server.py
File metadata and controls
332 lines (294 loc) · 12.7 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
import ast
import json
import logging
import traceback
from datetime import datetime
from typing import Any, Dict, List
import pyarrow as pa
import pyarrow.flight as fl
from feast import FeatureStore, FeatureView, utils
from feast.feature_logging import FeatureServiceLoggingSource
from feast.feature_view import DUMMY_ENTITY_NAME
from feast.infra.offline_stores.offline_utils import get_offline_store_from_config
from feast.saved_dataset import SavedDatasetStorage
logger = logging.getLogger(__name__)
class OfflineServer(fl.FlightServerBase):
def __init__(self, store: FeatureStore, location: str, **kwargs):
super(OfflineServer, self).__init__(location, **kwargs)
self._location = location
# A dictionary of configured flights, e.g. API calls received and not yet served
self.flights: Dict[str, Any] = {}
self.store = store
self.offline_store = get_offline_store_from_config(store.config.offline_store)
@classmethod
def descriptor_to_key(self, descriptor: fl.FlightDescriptor):
return (
descriptor.descriptor_type.value,
descriptor.command,
tuple(descriptor.path or tuple()),
)
def _make_flight_info(self, key: Any, descriptor: fl.FlightDescriptor):
endpoints = [fl.FlightEndpoint(repr(key), [self._location])]
# TODO calculate actual schema from the given features
schema = pa.schema([])
return fl.FlightInfo(schema, descriptor, endpoints, -1, -1)
def get_flight_info(
self, context: fl.ServerCallContext, descriptor: fl.FlightDescriptor
):
key = OfflineServer.descriptor_to_key(descriptor)
if key in self.flights:
return self._make_flight_info(key, descriptor)
raise KeyError("Flight not found.")
def list_flights(self, context: fl.ServerCallContext, criteria: bytes):
for key, table in self.flights.items():
if key[1] is not None:
descriptor = fl.FlightDescriptor.for_command(key[1])
else:
descriptor = fl.FlightDescriptor.for_path(*key[2])
yield self._make_flight_info(key, descriptor)
# Expects to receive request parameters and stores them in the flights dictionary
# Indexed by the unique command
def do_put(
self,
context: fl.ServerCallContext,
descriptor: fl.FlightDescriptor,
reader: fl.MetadataRecordBatchReader,
writer: fl.FlightMetadataWriter,
):
key = OfflineServer.descriptor_to_key(descriptor)
command = json.loads(key[1])
if "api" in command:
data = reader.read_all()
logger.debug(f"do_put: command is{command}, data is {data}")
self.flights[key] = data
self._call_api(command, key)
else:
logger.warning(f"No 'api' field in command: {command}")
def _call_api(self, command: dict, key: str):
remove_data = False
try:
api = command["api"]
if api == OfflineServer.offline_write_batch.__name__:
self.offline_write_batch(command, key)
remove_data = True
elif api == OfflineServer.write_logged_features.__name__:
self.write_logged_features(command, key)
remove_data = True
elif api == OfflineServer.persist.__name__:
self.persist(command["retrieve_func"], command, key)
remove_data = True
except Exception as e:
remove_data = True
logger.exception(e)
traceback.print_exc()
raise e
finally:
if remove_data:
# Get service is consumed, so we clear the corresponding flight and data
del self.flights[key]
def get_feature_view_by_name(
self, fv_name: str, name_alias: str, project: str
) -> FeatureView:
"""
Retrieves a feature view by name, including all subclasses of FeatureView.
Args:
fv_name: Name of feature view
name_alias: Alias to be applied to the projection of the registered view
project: Feast project that this feature view belongs to
Returns:
Returns either the specified feature view, or raises an exception if
none is found
"""
try:
fv = self.store.registry.get_feature_view(name=fv_name, project=project)
if name_alias is not None:
for fs in self.store.registry.list_feature_services(project=project):
for p in fs.feature_view_projections:
if p.name_alias == name_alias:
logger.debug(
f"Found matching FeatureService {fs.name} with projection {p}"
)
fv = fv.with_projection(p)
return fv
except Exception:
try:
return self.store.registry.get_stream_feature_view(
name=fv_name, project=project
)
except Exception as e:
logger.error(
f"Cannot find any FeatureView by name {fv_name} in project {project}"
)
raise e
def list_feature_views_by_name(
self, feature_view_names: List[str], name_aliases: List[str], project: str
) -> List[FeatureView]:
return [
remove_dummies(
self.get_feature_view_by_name(
fv_name=fv_name, name_alias=name_aliases[index], project=project
)
)
for index, fv_name in enumerate(feature_view_names)
]
# Extracts the API parameters from the flights dictionary, delegates the execution to the FeatureStore instance
# and returns the stream of data
def do_get(self, context: fl.ServerCallContext, ticket: fl.Ticket):
key = ast.literal_eval(ticket.ticket.decode())
if key not in self.flights:
logger.error(f"Unknown key {key}")
return None
command = json.loads(key[1])
api = command["api"]
logger.debug(f"get command is {command}")
logger.debug(f"requested api is {api}")
try:
if api == OfflineServer.get_historical_features.__name__:
table = self.get_historical_features(command, key).to_arrow()
elif api == OfflineServer.pull_all_from_table_or_query.__name__:
table = self.pull_all_from_table_or_query(command).to_arrow()
elif api == OfflineServer.pull_latest_from_table_or_query.__name__:
table = self.pull_latest_from_table_or_query(command).to_arrow()
else:
raise NotImplementedError
except Exception as e:
logger.exception(e)
traceback.print_exc()
raise e
# Get service is consumed, so we clear the corresponding flight and data
del self.flights[key]
return fl.RecordBatchStream(table)
def offline_write_batch(self, command: dict, key: str):
feature_view_names = command["feature_view_names"]
assert (
len(feature_view_names) == 1
), "feature_view_names list should only have one item"
name_aliases = command["name_aliases"]
assert len(name_aliases) == 1, "name_aliases list should only have one item"
project = self.store.config.project
feature_views = self.list_feature_views_by_name(
feature_view_names=feature_view_names,
name_aliases=name_aliases,
project=project,
)
assert len(feature_views) == 1
table = self.flights[key]
self.offline_store.offline_write_batch(
self.store.config, feature_views[0], table, command["progress"]
)
def write_logged_features(self, command: dict, key: str):
table = self.flights[key]
feature_service = self.store.get_feature_service(
command["feature_service_name"]
)
assert feature_service.logging_config is not None
self.offline_store.write_logged_features(
config=self.store.config,
data=table,
source=FeatureServiceLoggingSource(
feature_service, self.store.config.project
),
logging_config=feature_service.logging_config,
registry=self.store.registry,
)
def pull_all_from_table_or_query(self, command: dict):
return self.offline_store.pull_all_from_table_or_query(
self.store.config,
self.store.get_data_source(command["data_source_name"]),
command["join_key_columns"],
command["feature_name_columns"],
command["timestamp_field"],
utils.make_tzaware(datetime.fromisoformat(command["start_date"])),
utils.make_tzaware(datetime.fromisoformat(command["end_date"])),
)
def pull_latest_from_table_or_query(self, command: dict):
return self.offline_store.pull_latest_from_table_or_query(
self.store.config,
self.store.get_data_source(command["data_source_name"]),
command["join_key_columns"],
command["feature_name_columns"],
command["timestamp_field"],
command["created_timestamp_column"],
utils.make_tzaware(datetime.fromisoformat(command["start_date"])),
utils.make_tzaware(datetime.fromisoformat(command["end_date"])),
)
def list_actions(self, context):
return [
(
OfflineServer.offline_write_batch.__name__,
"Writes the specified arrow table to the data source underlying the specified feature view.",
),
(
OfflineServer.write_logged_features.__name__,
"Writes logged features to a specified destination in the offline store.",
),
(
OfflineServer.persist.__name__,
"Synchronously executes the underlying query and persists the result in the same offline store at the "
"specified destination.",
),
]
def get_historical_features(self, command: dict, key: str):
# Extract parameters from the internal flights dictionary
entity_df_value = self.flights[key]
entity_df = pa.Table.to_pandas(entity_df_value)
feature_view_names = command["feature_view_names"]
name_aliases = command["name_aliases"]
feature_refs = command["feature_refs"]
project = command["project"]
full_feature_names = command["full_feature_names"]
feature_views = self.list_feature_views_by_name(
feature_view_names=feature_view_names,
name_aliases=name_aliases,
project=project,
)
retJob = self.offline_store.get_historical_features(
config=self.store.config,
feature_views=feature_views,
feature_refs=feature_refs,
entity_df=entity_df,
registry=self.store.registry,
project=project,
full_feature_names=full_feature_names,
)
return retJob
def persist(self, retrieve_func: str, command: dict, key: str):
try:
if retrieve_func == OfflineServer.get_historical_features.__name__:
ret_job = self.get_historical_features(command, key)
elif (
retrieve_func == OfflineServer.pull_latest_from_table_or_query.__name__
):
ret_job = self.pull_latest_from_table_or_query(command)
elif retrieve_func == OfflineServer.pull_all_from_table_or_query.__name__:
ret_job = self.pull_all_from_table_or_query(command)
else:
raise NotImplementedError
data_source = self.store.get_data_source(command["data_source_name"])
storage = SavedDatasetStorage.from_data_source(data_source)
ret_job.persist(storage, command["allow_overwrite"], command["timeout"])
except Exception as e:
logger.exception(e)
traceback.print_exc()
raise e
def do_action(self, context: fl.ServerCallContext, action: fl.Action):
pass
def do_drop_dataset(self, dataset):
pass
def remove_dummies(fv: FeatureView) -> FeatureView:
"""
Removes dummmy IDs from FeatureView instances created with FeatureView.from_proto
"""
if DUMMY_ENTITY_NAME in fv.entities:
fv.entities = []
fv.entity_columns = []
return fv
def start_server(
store: FeatureStore,
host: str,
port: int,
):
location = "grpc+tcp://{}:{}".format(host, port)
server = OfflineServer(store, location)
logger.info(f"Offline store server serving on {location}")
server.serve()