-
Notifications
You must be signed in to change notification settings - Fork 590
/
client.py
447 lines (387 loc) · 15.7 KB
/
client.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
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
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
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.
"""
import asyncio
import datetime
import inspect
import logging
from typing import Dict, List, NamedTuple, Optional
import grpc
from lte.protos.s6a_service_pb2 import DeleteSubscriberRequest
from lte.protos.s6a_service_pb2_grpc import S6aServiceStub
from lte.protos.subscriberdb_pb2 import (
CheckInSyncRequest,
ListSubscribersRequest,
LTESubscription,
SubscriberData,
SuciProfile,
SuciProfileList,
SyncRequest,
)
from magma.common.grpc_client_manager import GRPCClientManager
from magma.common.rpc_utils import grpc_async_wrapper
from magma.common.sdwatchdog import SDWatchdogTask
from magma.common.sentry import EXCLUDE_FROM_ERROR_MONITORING
from magma.common.service_registry import ServiceRegistry
from magma.subscriberdb.metrics import (
SUBSCRIBER_SYNC_FAILURE_TOTAL,
SUBSCRIBER_SYNC_LATENCY,
SUBSCRIBER_SYNC_SUCCESS_TOTAL,
)
from magma.subscriberdb.store.sqlite import SqliteStore
from orc8r.protos.digest_pb2 import Changeset, Digest, LeafDigest
class CloudSubscribersInfo(NamedTuple):
subscribers: List[SubscriberData]
root_digest: Optional[Digest]
leaf_digests: Optional[List[LeafDigest]]
class ProcessedChangeset(NamedTuple):
to_renew: List[SubscriberData]
deleted: List[str]
class CloudSuciProfilesInfo(NamedTuple):
suci_profiles: List[SuciProfile]
class suci_profile_data(NamedTuple):
protection_scheme: int
home_network_public_key: bytes
home_network_private_key: bytes
class SubscriberDBCloudClient(SDWatchdogTask):
"""
SubscriberDBCloudClient for requesting subscribers from Orchestrator.
SubscriberDBCloudClient calls the Orchestrator's SubscriberDBCloud service
to fetch pages of subscribers stored in Orchestrator and updates the local
subscriberdb store with the changes.
"""
SUBSCRIBERDB_REQUEST_TIMEOUT = 10
def __init__(
self,
loop: asyncio.AbstractEventLoop,
store: SqliteStore,
subscriber_page_size: int,
sync_interval: int,
suciprofile_db_dict: Dict,
grpc_client_manager: GRPCClientManager,
):
"""
Initialize subscriberdb client
Args:
loop: asyncio event loop
store: SqliteStore for subscribers
subscriber_page_size: integer for page size
sync_interval: integer for frequency of subscriber streaming
grpc_client_manager: GRPCClientManager for gRPC client mgmt
Returns: None
"""
super().__init__(
sync_interval,
loop,
)
self._loop = loop
self._subscriber_page_size = subscriber_page_size
self._store = store
self.suciprofile_db_dict = suciprofile_db_dict
# grpc_client_manager to manage grpc client recycling
self._grpc_client_manager = grpc_client_manager
async def _run(self) -> None:
suciprofiles_info = await self._list_suciprofiles()
if suciprofiles_info is None:
return
in_sync = await self._check_subscribers_in_sync()
if in_sync:
return
resync = await self._sync_subscribers()
if not resync:
return
subscribers_info = await self._get_all_subscribers()
if subscribers_info is None:
return
# failure between the calls
self._process_subscribers(subscribers_info.subscribers)
self._update_root_digest(subscribers_info.root_digest)
self._update_leaf_digests(subscribers_info.leaf_digests)
async def _check_subscribers_in_sync(self) -> bool:
"""
Check if the local subscriber data is up-to-date with the cloud by
comparing root digests
Returns:
boolean value for whether the local data is in sync
"""
subscriberdb_cloud_client = self._grpc_client_manager.get_client()
req = CheckInSyncRequest(
root_digest=Digest(
md5_base64_digest=self._store.get_current_root_digest(),
),
)
try:
res = await grpc_async_wrapper(
subscriberdb_cloud_client.CheckInSync.future(
req,
self.SUBSCRIBERDB_REQUEST_TIMEOUT,
),
self._loop,
)
except grpc.RpcError as err:
_log_grpc_error(err)
return False
return res.in_sync
async def _sync_subscribers(self) -> bool:
"""
Sync local subscriber data and digests with the cloud if didn't receive
resync signal.
Returns:
boolean value for whether a resync with cloud is needed
"""
subscriberdb_cloud_client = self._grpc_client_manager.get_client()
req = SyncRequest(
leaf_digests=self._store.get_current_leaf_digests(),
)
try:
res = await grpc_async_wrapper(
subscriberdb_cloud_client.Sync.future(
req,
self.SUBSCRIBERDB_REQUEST_TIMEOUT,
),
self._loop,
)
except grpc.RpcError as err:
_log_grpc_error(err)
return True
if not res.resync:
# TODO(hcgatewood): switch to bulk editing subscriber data rows
changeset = self._process_changeset(res.changeset)
for subscriber_data in changeset.to_renew:
self._store.upsert_subscriber(subscriber_data)
for sid in changeset.deleted:
self._store.delete_subscriber(sid)
self._detach_subscribers_by_ids(changeset.deleted)
self._update_root_digest(res.digests.root_digest)
self._update_leaf_digests(res.digests.leaf_digests)
return res.resync
async def _get_all_subscribers(self) -> Optional[CloudSubscribersInfo]:
subscriberdb_cloud_client = self._grpc_client_manager.get_client()
subscribers = []
root_digest = None
leaf_digests = None
req_page_token = "" # noqa: S105
found_empty_token = False
sync_start = datetime.datetime.now()
# Next page token empty means read all updates
while not found_empty_token: # noqa: S105
try:
req = ListSubscribersRequest(
page_size=self._subscriber_page_size,
page_token=req_page_token,
)
res = await grpc_async_wrapper(
subscriberdb_cloud_client.ListSubscribers.future(
req,
self.SUBSCRIBERDB_REQUEST_TIMEOUT,
),
self._loop,
)
subscribers.extend(res.subscribers)
# Cloud sends back digests during request for the first page
if req_page_token == "":
root_digest = res.digests.root_digest
leaf_digests = res.digests.leaf_digests
req_page_token = res.next_page_token
found_empty_token = req_page_token == ""
except grpc.RpcError as err:
_log_grpc_error(err)
time_elapsed = datetime.datetime.now() - sync_start
SUBSCRIBER_SYNC_LATENCY.observe(
time_elapsed.total_seconds() * 1000,
)
SUBSCRIBER_SYNC_FAILURE_TOTAL.inc()
return None
logging.info(
"Successfully fetched all subscriber "
"pages from the cloud!",
)
SUBSCRIBER_SYNC_SUCCESS_TOTAL.inc()
time_elapsed = datetime.datetime.now() - sync_start
SUBSCRIBER_SYNC_LATENCY.observe(
time_elapsed.total_seconds() * 1000,
)
subscribers_info = CloudSubscribersInfo(
subscribers=subscribers,
root_digest=root_digest,
leaf_digests=leaf_digests,
)
return subscribers_info
async def _list_suciprofiles(self) -> Optional[CloudSuciProfilesInfo]:
req_page_token = ""
subscriberdb_cloud_client = self._grpc_client_manager.get_client()
suciprofiles = []
try:
req = ListSubscribersRequest(
page_size=self._subscriber_page_size,
page_token=req_page_token,
)
res = await grpc_async_wrapper(
subscriberdb_cloud_client.ListSuciProfiles.future(
req,
self.SUBSCRIBERDB_REQUEST_TIMEOUT,
),
self._loop,
)
for suciProfile in res.suci_profiles:
if suciProfile.home_net_public_key_id not in self.suciprofile_db_dict.keys():
self.suciprofile_db_dict[suciProfile.home_net_public_key_id] = suci_profile_data(
suciProfile.protection_scheme, suciProfile.home_net_public_key,
suciProfile.home_net_private_key,
)
for k, v in self.suciprofile_db_dict.items():
suciprofiles.append(
SuciProfile(
home_net_public_key_id=int(k),
protection_scheme=v.protection_scheme,
home_net_public_key=v.home_network_public_key,
home_net_private_key=v.home_network_private_key,
),
)
res = SuciProfileList(suci_profiles=suciprofiles)
return res
except grpc.RpcError as err:
logging.error(
"Fetch suci profiles error! [%s] %s", err.code(),
err.details(),
)
return None
def _process_changeset(self, changeset: Optional[Changeset]) -> ProcessedChangeset:
if changeset is None:
return ProcessedChangeset(to_renew=[], deleted=[])
to_renew, deleted = [], []
if changeset.deleted is not None:
deleted = changeset.deleted
if changeset.to_renew is not None:
for any_val in changeset.to_renew:
data = SubscriberData()
ok = any_val.Unpack(data)
if not ok:
raise ValueError(
'Cannot unpack Any type into message: %s' % data,
)
to_renew.append(data)
return ProcessedChangeset(to_renew=to_renew, deleted=deleted)
def _update_root_digest(self, root_digest: Optional[Digest]) -> None:
if root_digest is None:
return
self._store.update_root_digest(root_digest.md5_base64_digest)
def _update_leaf_digests(
self,
leaf_digests: Optional[List[LeafDigest]],
) -> None:
if leaf_digests is None:
return
self._store.update_leaf_digests(leaf_digests)
def _process_subscribers(self, subscribers: List[SubscriberData]) -> None:
active_subscriber_ids = []
sids = []
for subscriber in subscribers:
sids.append(subscriber.sid.id)
if subscriber.lte.state == LTESubscription.ACTIVE:
active_subscriber_ids.append(subscriber.sid.id)
old_sub_ids = self._store.list_subscribers()
# Only compare active subscribers against the database to decide
# what to detach.
self._detach_deleted_subscribers(old_sub_ids, active_subscriber_ids)
logging.debug("Resync with subscribers: %s", ','.join(sids))
self._store.resync(subscribers)
def _detach_deleted_subscribers(self, old_sub_ids, new_sub_ids):
"""
Detach deleted subscribers from store and network.
Compares current subscriber ids and new subscriber ids list
just streamed from the cloud to figure out the deleted subscribers.
Then send grpc DeleteSubscriber request to mme to detach all the
deleted subscribers.
Args:
old_sub_ids: a list of old subscriber ids in the store
new_sub_ids: a list of new active subscriber ids
Returns:
None
"""
# THIS IS A HACK UNTIL WE FIX THIS ON CLOUD
# We accept IMSIs with or without 'IMSI' prepended on cloud, but we
# always store IMSIs on local subscriberdb with IMSI prepended. If the
# cloud streams down subscriber IDs without 'IMSI' prepended,
# subscriberdb will try to delete all of the subscribers from MME every
# time it streams from cloud because the set membership will fail
# when comparing '12345' to 'IMSI12345'.
new_sub_ids = {
'IMSI{imsiVal}'.format(imsiVal=s) if not s.startswith('IMSI')
else s
for s in new_sub_ids
}
deleted_sub_ids = [
sub_id for sub_id in old_sub_ids
if sub_id not in set(new_sub_ids)
]
if not deleted_sub_ids:
return
self._detach_subscribers_by_ids(deleted_sub_ids)
def _detach_subscribers_by_ids(self, deleted_sub_ids: List[str]):
"""
Sends grpc DeleteSubscriber request to mme to detach all subscribers
given as args.
Args:
deleted_sub_ids: a list of old subscriber ids in the store,
prefixed by subscriber type
Returns:
None
"""
# send detach request to mme for all deleted subscribers.
chan = ServiceRegistry.get_rpc_channel(
's6a_service',
ServiceRegistry.LOCAL,
)
client = S6aServiceStub(chan)
req = DeleteSubscriberRequest()
# mme expects a list of IMSIs without "IMSI" prefix
imsis_to_delete_without_prefix = [sub[4:] for sub in deleted_sub_ids]
req.imsi_list.extend(imsis_to_delete_without_prefix)
future = client.DeleteSubscriber.future(req)
future.add_done_callback(
lambda future:
self._loop.call_soon_threadsafe(
self._detach_deleted_subscribers_done,
future,
),
)
def _detach_deleted_subscribers_done(self, delete_future):
"""
Detach deleted subscribers callback to handle exceptions
Args:
delete_future: future of delete RPC call
"""
err = delete_future.exception()
if err:
logging.error(
"Detach Deleted Subscribers Error! [%s] %s",
err.code(), err.details(),
)
def _log_grpc_error(err: grpc.RpcError) -> None:
if err.code() in {grpc.StatusCode.INTERNAL, grpc.StatusCode.UNIMPLEMENTED}:
logging.error(
'Internal Error in subscriberdb-Orc8r communication. '
'If AGW and Orc8r are deployed at a commit hash, '
'upgrade AGW and Orc8r to latest commit hash.',
extra=EXCLUDE_FROM_ERROR_MONITORING,
)
elif err.code() in {grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.DEADLINE_EXCEEDED}:
logging.error(
'Internal Error in subscriberdb-Orc8r communication. '
'Cannot connect to server: [%s] %s', err.code(), err.details(),
extra=EXCLUDE_FROM_ERROR_MONITORING,
)
else:
logging.error(
# inspect.stack() indices: [1] -> frame record of penultimate caller; [3] -> function name
"%s request error! [%s] %s", inspect.stack(context=0)[1][3], err.code(),
err.details(),
)