/
s1ap_utils.py
1763 lines (1573 loc) · 63.3 KB
/
s1ap_utils.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
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
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 ctypes
import ipaddress
import logging
import os
import shlex
import threading
import time
from enum import Enum
from queue import Queue
from typing import Optional
import grpc
import subprocess
import json
import s1ap_types
from integ_tests.gateway.rpc import get_rpc_channel
from lte.protos.policydb_pb2 import (
FlowDescription,
FlowMatch,
FlowQos,
PolicyRule,
QosArp,
)
from lte.protos.mobilityd_pb2 import IPAddress
from lte.protos.session_manager_pb2 import (
DynamicRuleInstall,
PolicyReAuthRequest,
QoSInformation,
RuleSet,
RulesPerSubscriber,
SessionRules,
)
from lte.protos.abort_session_pb2 import (
AbortSessionRequest,
AbortSessionResult,
)
from lte.protos.spgw_service_pb2 import (
CreateBearerRequest,
DeleteBearerRequest,
)
from lte.protos.spgw_service_pb2_grpc import SpgwServiceStub
from magma.subscriberdb.sid import SIDUtils
from lte.protos.abort_session_pb2_grpc import AbortSessionResponderStub
from lte.protos.session_manager_pb2_grpc import (
LocalSessionManagerStub,
SessionProxyResponderStub,
)
from orc8r.protos.directoryd_pb2 import GetDirectoryFieldRequest
from orc8r.protos.directoryd_pb2_grpc import GatewayDirectoryServiceStub
from integ_tests.s1aptests.ovs.rest_api import get_datapath, get_flows
from lte.protos.ha_service_pb2_grpc import HaServiceStub
from lte.protos.ha_service_pb2 import (
StartAgwOffloadRequest,
EnbOffloadType,
)
from orc8r.protos.common_pb2 import Void
DEFAULT_GRPC_TIMEOUT = 10
class S1ApUtil(object):
"""
Helper class to wrap the initialization and API interface of S1APTester
Note that some of the values that are not that interesting are set
through config files, that this class doesn't override. Examples include
the various interface timeout params.
"""
# Extracted from TestCntlrApp/src/ueApp/ue_esm.h
CM_ESM_PDN_IPV4 = 0b01
CM_ESM_PDN_IPV6 = 0b10
CM_ESM_PDN_IPV4V6 = 0b11
PROT_CFG_CID_PCSCF_IPV6_ADDR_REQUEST = 0x0001
PROT_CFG_CID_PCSCF_IPV4_ADDR_REQUEST = 0x000C
PROT_CFG_CID_DNS_SERVER_IPV6_ADDR_REQUEST = 0x0003
PROT_CFG_PID_IPCP = 0x8021
lib_name = "libtfw.so"
_cond = threading.Condition()
_msg = Queue()
MAX_NUM_RETRIES = 5
datapath = get_datapath()
SPGW_TABLE = 0
LOCAL_PORT = "LOCAL"
class Msg(object):
def __init__(self, msg_type, msg_p, msg_len):
self.msg_type = msg_type
self.msg_p = ctypes.create_string_buffer(msg_len)
ctypes.memmove(self.msg_p, msg_p, msg_len)
self.msg_len = msg_len
def cast(self, msg_class):
return ctypes.cast(self.msg_p, ctypes.POINTER(msg_class)).contents
@staticmethod
def s1ap_callback(msg_type, msg_p, msg_len):
""" S1ap tester compatible callback"""
with S1ApUtil._cond:
S1ApUtil._msg.put(S1ApUtil.Msg(msg_type, msg_p, msg_len))
S1ApUtil._cond.notify_all()
def __init__(self):
"""
Initialize the s1aplibrary and its callbacks.
"""
self._imsi_idx = 1
self.IMSI_LEN = 15
lib_path = os.environ["S1AP_TESTER_ROOT"]
lib = os.path.join(lib_path, "bin", S1ApUtil.lib_name)
os.chdir(lib_path)
self._test_lib = ctypes.cdll.LoadLibrary(lib)
self._callback_type = ctypes.CFUNCTYPE(
None, ctypes.c_short, ctypes.c_void_p, ctypes.c_short
)
# Maintain a reference to the function object so GC doesn't release it.
self._callback_fn = self._callback_type(S1ApUtil.s1ap_callback)
self._test_lib.initTestFrameWork(self._callback_fn)
self._test_api = self._test_lib.tfwApi
self._test_api.restype = ctypes.c_int16
self._test_api.argtypes = [ctypes.c_uint16, ctypes.c_void_p]
# Mutex for state change operations
self._lock = threading.RLock()
# Maintain a map of UE IDs to IPs
self._ue_ip_map = {}
self.gtpBridgeUtil = GTPBridgeUtils()
def cleanup(self):
"""
Cleanup the dll loaded explicitly so the next run doesn't reuse the
same globals as ctypes LoadLibrary uses dlopen under the covers
Also clear out the UE ID: IP mappings
"""
# self._test_lib.dlclose(self._test_lib._handle)
self._test_lib = None
self._ue_ip_map = {}
def issue_cmd(self, cmd_type, req):
"""
Issue a command to the s1aptester and blocks until response is recvd.
Args:
cmd_type: The cmd type enum
req: The request Structure
Returns:
None
"""
c_req = None
if req:
# For non NULL requests obtain the address.
c_req = ctypes.byref(req)
with self._cond:
rc = self._test_api(cmd_type.value, c_req)
if rc:
print("Error executing command %s" % repr(cmd_type))
return rc
return 0
def get_ip(self, ue_id):
""" Returns the IP assigned to a given UE ID
Args:
ue_id: the ue_id to query
Returns an ipaddress.ip_address for the given UE ID, or None if no IP
has been observed to be assigned to this IP
"""
with self._lock:
if ue_id in self._ue_ip_map:
return self._ue_ip_map[ue_id]
return None
def get_response(self):
# Wait until callback is invoked.
return self._msg.get(True)
def populate_pco(
self, protCfgOpts_pr, pcscf_addr_type=None, dns_ipv6_addr=False,
ipcp=False
):
"""
Populates the PCO values.
Args:
protCfgOpts_pr: PCO structure
pcscf_addr_type: ipv4/ipv6/ipv4v6 flag
dns_ipv6_addr: True/False flag
ipcp: True/False flag
Returns:
None
"""
# PCO parameters
# Presence mask
protCfgOpts_pr.pres = 1
# Length
protCfgOpts_pr.len = 4
# Configuration protocol
protCfgOpts_pr.cfgProt = 0
# Extension bit for the additional parameters
protCfgOpts_pr.ext = 1
# Number of protocol IDs
protCfgOpts_pr.numProtId = 0
# Fill Number of container IDs and Container ID
idx = 0
if pcscf_addr_type == "ipv4":
protCfgOpts_pr.numContId += 1
protCfgOpts_pr.c[
idx
].cid = S1ApUtil.PROT_CFG_CID_PCSCF_IPV4_ADDR_REQUEST
idx += 1
elif pcscf_addr_type == "ipv6":
protCfgOpts_pr.numContId += 1
protCfgOpts_pr.c[
idx
].cid = S1ApUtil.PROT_CFG_CID_PCSCF_IPV6_ADDR_REQUEST
idx += 1
elif pcscf_addr_type == "ipv4v6":
protCfgOpts_pr.numContId += 2
protCfgOpts_pr.c[
idx
].cid = S1ApUtil.PROT_CFG_CID_PCSCF_IPV4_ADDR_REQUEST
idx += 1
protCfgOpts_pr.c[
idx
].cid = S1ApUtil.PROT_CFG_CID_PCSCF_IPV6_ADDR_REQUEST
idx += 1
if dns_ipv6_addr:
protCfgOpts_pr.numContId += 1
protCfgOpts_pr.c[
idx
].cid = S1ApUtil.PROT_CFG_CID_DNS_SERVER_IPV6_ADDR_REQUEST
if ipcp:
protCfgOpts_pr.numProtId += 1
protCfgOpts_pr.p[
0
].pid = S1ApUtil.PROT_CFG_PID_IPCP
protCfgOpts_pr.p[
0
].len = 0x10
# PPP IP Control Protocol packet as per rfc 1877
# 01 00 00 10 81 06 00 00 00 00 83 06 00 00 00 00
protCfgOpts_pr.p[0].val[0] = 0x01 # code = 01 - Config Request
protCfgOpts_pr.p[0].val[1] = 0x00 # Identifier : 00
protCfgOpts_pr.p[0].val[2] = 0x00 # Length : 16
protCfgOpts_pr.p[0].val[3] = 0x10
protCfgOpts_pr.p[0].val[4] = 0x81 # Options:Primary DNS IP Addr
protCfgOpts_pr.p[0].val[5] = 0x06 # len = 6
protCfgOpts_pr.p[0].val[6] = 0x00 # 00.00.00.00
protCfgOpts_pr.p[0].val[7] = 0x00
protCfgOpts_pr.p[0].val[8] = 0x00
protCfgOpts_pr.p[0].val[9] = 0x00
protCfgOpts_pr.p[0].val[10] = 0x83 # Options:Secondary DNS IP Addr
protCfgOpts_pr.p[0].val[11] = 0x06 # len = 6
protCfgOpts_pr.p[0].val[12] = 0x00 # 00.00.00.00
protCfgOpts_pr.p[0].val[13] = 0x00
protCfgOpts_pr.p[0].val[14] = 0x00
protCfgOpts_pr.p[0].val[15] = 0x00
def attach(
self,
ue_id,
attach_type,
resp_type,
resp_msg_type,
sec_ctxt=s1ap_types.TFW_CREATE_NEW_SECURITY_CONTEXT,
id_type=s1ap_types.TFW_MID_TYPE_IMSI,
eps_type=s1ap_types.TFW_EPS_ATTACH_TYPE_EPS_ATTACH,
pdn_type=1,
pcscf_addr_type=None,
dns_ipv6_addr=False,
ipcp=False,
):
"""Given a UE issue the attach request of specified type
Caches the assigned IP address, if any is assigned
Args:
ue_id: The eNB ue_id
attach_type: The type of attach e.g. UE_END_TO_END_ATTACH_REQUEST
resp_type: enum type of the expected response
resp_msg_type: Structure type of expected response message
sec_ctxt: Optional param allows for the reuse of the security
context, defaults to creating a new security context.
id_type: Optional param allows for changing up the ID type,
defaults to s1ap_types.TFW_MID_TYPE_IMSI.
eps_type: Optional param allows for variation in the EPS attach
type, defaults to s1ap_types.TFW_EPS_ATTACH_TYPE_EPS_ATTACH.
pdn_type:1 for IPv4, 2 for IPv6 and 3 for IPv4v6
pcscf_addr_type:IPv4/IPv6/IPv4v6
dns_ipv6_addr: True/False flag
Returns:
msg: Received Attach Accept message
"""
attach_req = s1ap_types.ueAttachRequest_t()
attach_req.ue_Id = ue_id
attach_req.mIdType = id_type
attach_req.epsAttachType = eps_type
attach_req.useOldSecCtxt = sec_ctxt
attach_req.pdnType_pr.pres = True
attach_req.pdnType_pr.pdn_type = pdn_type
# Populate PCO if pcscf_addr_type/dns_ipv6_addr/ipcp is set
if pcscf_addr_type or dns_ipv6_addr or ipcp:
self.populate_pco(
attach_req.protCfgOpts_pr, pcscf_addr_type, dns_ipv6_addr, ipcp
)
assert self.issue_cmd(attach_type, attach_req) == 0
response = self.get_response()
# The MME actually sends INT_CTX_SETUP_IND and UE_ATTACH_ACCEPT_IND in
# one message, but the s1aptester splits it and sends the tests 2
# messages. Usually context setup comes before attach accept, but
# it's possible it may happen the other way
if s1ap_types.tfwCmd.INT_CTX_SETUP_IND.value == response.msg_type:
response = self.get_response()
elif s1ap_types.tfwCmd.UE_ATTACH_ACCEPT_IND.value == response.msg_type:
context_setup = self.get_response()
assert (
context_setup.msg_type
== s1ap_types.tfwCmd.INT_CTX_SETUP_IND.value
)
logging.debug(
"s1ap response expected, received: %d, %d",
resp_type.value,
response.msg_type,
)
assert resp_type.value == response.msg_type
msg = response.cast(resp_msg_type)
# We only support IPv4 right now, as max PDN address in S1AP tester is
# currently 13 bytes, which is too short for IPv6 (which requires 16)
if resp_msg_type == s1ap_types.ueAttachAccept_t:
# Verify if requested and accepted EPS attach types are same
assert eps_type == msg.eps_Atch_resp
pdn_type = msg.esmInfo.pAddr.pdnType
addr = msg.esmInfo.pAddr.addrInfo
if S1ApUtil.CM_ESM_PDN_IPV4 == pdn_type:
# Cast and cache the IPv4 address
ip = ipaddress.ip_address(bytes(addr[:4]))
with self._lock:
self._ue_ip_map[ue_id] = ip
elif S1ApUtil.CM_ESM_PDN_IPV6 == pdn_type:
print("IPv6 PDN type received")
elif S1ApUtil.CM_ESM_PDN_IPV4V6 == pdn_type:
print("IPv4v6 PDN type received")
return msg
def receive_emm_info(self):
response = self.get_response()
logging.debug(
"s1ap message expected, received: %d, %d",
s1ap_types.tfwCmd.UE_EMM_INFORMATION.value,
response.msg_type,
)
assert response.msg_type == s1ap_types.tfwCmd.UE_EMM_INFORMATION.value
def detach(self, ue_id, reason_type, wait_for_s1_ctxt_release=True):
""" Given a UE issue a detach request """
detach_req = s1ap_types.uedetachReq_t()
detach_req.ue_Id = ue_id
detach_req.ueDetType = reason_type
assert (
self.issue_cmd(s1ap_types.tfwCmd.UE_DETACH_REQUEST, detach_req)
== 0
)
if reason_type == s1ap_types.ueDetachType_t.UE_NORMAL_DETACH.value:
response = self.get_response()
assert (
s1ap_types.tfwCmd.UE_DETACH_ACCEPT_IND.value
== response.msg_type
)
# Now wait for the context release response
if wait_for_s1_ctxt_release:
response = self.get_response()
assert s1ap_types.tfwCmd.UE_CTX_REL_IND.value == response.msg_type
with self._lock:
del self._ue_ip_map[ue_id]
def _verify_dl_flow(self, dl_flow_rules=None):
# try at least 5 times before failing as gateway
# might take some time to install the flows in ovs
# Verify the total number of DL flows for this UE ip address
num_dl_flows = 1
for key, value in dl_flow_rules.items():
tcp_src_port = 0
ip_proto = 0
ue_ip6_str = None
ue_ip_str = str(key)
if key.version == 6:
ue_ip6_str = ipaddress.ip_network(
(ue_ip_str + "/64"), strict=False
).with_netmask
ue_ip_addr = ue_ip6_str if key.version == 6 else ue_ip_str
dst_addr = "nw_dst" if key.version == 4 else "ipv6_dst"
key_to_be_matched = "ipv4_src" if key.version == 4 else "ipv6_src"
eth_typ = 2048 if key.version == 4 else 34525
# Set to 1 for the default bearer
total_num_dl_flows_to_be_verified = 1
for item in value:
for flow in item:
if (
flow["direction"] == FlowMatch.DOWNLINK
and key_to_be_matched in flow
):
total_num_dl_flows_to_be_verified += 1
total_dl_ovs_flows_created = get_flows(
self.datapath,
{
"table_id": self.SPGW_TABLE,
"match": {
dst_addr: ue_ip_addr,
"eth_type": eth_typ,
"in_port": self.LOCAL_PORT,
},
},
)
assert (
len(total_dl_ovs_flows_created)
== total_num_dl_flows_to_be_verified
)
# Now verify the rules for every flow
for item in value:
for flow in item:
if (
flow["direction"] == FlowMatch.DOWNLINK
and key_to_be_matched in flow
):
ip_src_addr = flow[key_to_be_matched]
ip_src = "ipv4_src" if key.version == 4 else "ipv6_src"
ip_dst = "ipv4_dst" if key.version == 4 else "ipv6_dst"
tcp_src_port = flow["tcp_src_port"]
ip_proto = flow["ip_proto"]
for i in range(self.MAX_NUM_RETRIES):
print("Get downlink flows: attempt ", i)
downlink_flows = get_flows(
self.datapath,
{
"table_id": self.SPGW_TABLE,
"match": {
ip_dst: ue_ip_addr,
"eth_type": eth_typ,
"in_port": self.LOCAL_PORT,
ip_src: ip_src_addr,
"tcp_src": tcp_src_port,
"ip_proto": ip_proto,
},
},
)
if len(downlink_flows) >= num_dl_flows:
break
time.sleep(
5
) # sleep for 5 seconds before retrying
assert (
len(downlink_flows) >= num_dl_flows
), "Downlink flow missing for UE"
assert downlink_flows[0]["match"][ip_dst] == ue_ip_addr
actions = downlink_flows[0]["instructions"][0][
"actions"
]
has_tunnel_action = any(
action
for action in actions
if action["field"] == "tunnel_id"
and action["type"] == "SET_FIELD"
)
assert bool(has_tunnel_action)
def verify_flow_rules(self, num_ul_flows, dl_flow_rules=None):
GTP_PORT = self.gtpBridgeUtil.get_gtp_port_no()
# Check if UL and DL OVS flows are created
print("************ Verifying flow rules")
# UPLINK
print("Checking for uplink flow")
# try at least 5 times before failing as gateway
# might take some time to install the flows in ovs
for i in range(self.MAX_NUM_RETRIES):
print("Get uplink flows: attempt ", i)
uplink_flows = get_flows(
self.datapath,
{
"table_id": self.SPGW_TABLE,
"match": {
"in_port": GTP_PORT,
}
},
)
if len(uplink_flows) == num_ul_flows:
break
time.sleep(5) # sleep for 5 seconds before retrying
assert len(uplink_flows) == num_ul_flows,\
"Uplink flow missing for UE: %d !=" % (len(uplink_flows), num_ul_flows)
assert uplink_flows[0]["match"]["tunnel_id"] is not None
# DOWNLINK
print("Checking for downlink flow")
self._verify_dl_flow(dl_flow_rules)
def verify_paging_flow_rules(self, ip_list):
# Check if paging flows are created
print("************ Verifying paging flow rules")
num_paging_flows_to_be_verified = 1
for ip in ip_list:
ue_ip_str = str(ip)
print("Verifying paging flow for ip", ue_ip_str)
for i in range(self.MAX_NUM_RETRIES):
print("Get paging flows: attempt ", i)
paging_flows = get_flows(
self.datapath,
{
"table_id": self.SPGW_TABLE,
"match": {
"nw_dst": ue_ip_str,
"eth_type": 2048,
"priority": 5,
},
},
)
if len(paging_flows) == num_paging_flows_to_be_verified:
break
time.sleep(5) # sleep for 5 seconds before retrying
assert (
len(paging_flows) == num_paging_flows_to_be_verified
), "Paging flow missing for UE"
# TODO - Verify that the action is to send to controller
"""controller_port = 4294967293
actions = paging_flows[0]["instructions"][0]["actions"]
has_tunnel_action = any(
action
for action in actions
if action["type"] == "OUTPUT"
and action["port"] == controller_port
)
assert bool(has_tunnel_action)"""
def generate_imsi(self, prefix=None):
"""
Generate imsi based on index offset and prefix
"""
assert (prefix is not None), "IMSI prefix is empty"
idx = str(self._imsi_idx)
# Add 0 padding
padding = self.IMSI_LEN - len(idx) - len(prefix[4:])
imsi = prefix + "0" * padding + idx
assert(len(imsi[4:]) == self.IMSI_LEN), "Invalid IMSI length"
self._imsi_idx += 1
print("Using subscriber IMSI %s" % imsi)
return imsi
class SubscriberUtil(object):
"""
Helper class to manage subscriber data for the tests.
"""
SID_PREFIX = "IMSI00101"
IMSI_LEN = 15
MAX_IMEI_LEN = 16
def __init__(self, subscriber_client):
"""
Initialize subscriber util.
Args:
subscriber_client (subscriber_db_client.SubscriberDbClient):
client interacting with our subscriber APIs
"""
self._sid_idx = 1
self._ue_id = 1
self._imei_idx = 1
self._imei_default = 3805468432113170
# Maintain references to UE configs to prevent GC
self._ue_cfgs = []
self._subscriber_client = subscriber_client
def _gen_next_sid(self):
"""
Generate the sid based on index offset and prefix
"""
idx = str(self._sid_idx)
# Find the 0 padding we need to add
padding = self.IMSI_LEN - len(idx) - len(self.SID_PREFIX[4:])
sid = self.SID_PREFIX + "0" * padding + idx
self._sid_idx += 1
print("Using subscriber IMSI %s" % sid)
return sid
def _generate_imei(self, num_ues=1):
""" Generates 16 digit IMEI which includes SVN """
imei = str(self._imei_default + self._imei_idx)
assert(len(imei) <= self.MAX_IMEI_LEN), "Invalid IMEI length"
self._imei_idx += 1
print("Using IMEI %s" % imei)
return imei
def _get_s1ap_sub(self, sid, imei):
"""
Get the subscriber data in s1aptester format.
Args:
The string representation of the subscriber id
and imei
"""
ue_cfg = s1ap_types.ueConfig_t()
ue_cfg.ue_id = self._ue_id
ue_cfg.auth_key = 1
# Some s1ap silliness, the char field is modelled as an int and then
# cast into a uint8.
for i in range(0, 15):
ue_cfg.imsi[i] = ctypes.c_ubyte(int(sid[4 + i]))
for i in range(0, len(imei)):
ue_cfg.imei[i] = ctypes.c_ubyte(int(imei[i]))
ue_cfg.imsiLen = self.IMSI_LEN
self._ue_cfgs.append(ue_cfg)
self._ue_id += 1
return ue_cfg
def add_sub(self, num_ues=1):
""" Add subscribers to the EPC, is blocking """
# Add the default IMSI used for the tests
subscribers = []
for _ in range(num_ues):
sid = self._gen_next_sid()
self._subscriber_client.add_subscriber(sid)
imei = self._generate_imei()
subscribers.append(self._get_s1ap_sub(sid, imei))
self._subscriber_client.wait_for_changes()
return subscribers
def config_apn_data(self, imsi, apn_list):
""" Add APN details """
self._subscriber_client.config_apn_details(imsi, apn_list)
def cleanup(self):
""" Cleanup added subscriber from subscriberdb """
self._subscriber_client.clean_up()
# block until changes propagate
self._subscriber_client.wait_for_changes()
class MagmadUtil(object):
stateless_cmds = Enum("stateless_cmds", "CHECK DISABLE ENABLE")
config_update_cmds = Enum("config_update_cmds", "MODIFY RESTORE")
apn_correction_cmds = Enum("apn_correction_cmds", "DISABLE ENABLE")
health_service_cmds = Enum("health_service_cmds", "DISABLE ENABLE")
ipv6_config_cmds = Enum("ipv6_config_cmds", "DISABLE ENABLE")
ha_service_cmds = Enum("ha_service_cmds", "DISABLE ENABLE")
def __init__(self, magmad_client):
"""
Init magmad util.
Args:
magmad_client: MagmadServiceClient
"""
self._magmad_client = magmad_client
self._data = {
"user": "vagrant",
"host": "192.168.60.142",
"password": "vagrant",
"command": "test",
}
self._command = (
"sshpass -p {password} ssh "
"-o UserKnownHostsFile=/dev/null "
"-o StrictHostKeyChecking=no "
"-o LogLevel=ERROR "
"{user}@{host} {command}"
)
def exec_command(self, command):
"""
Run a command remotely on magma_dev VM.
Args:
command: command (str) to be executed on remote host
e.g. 'sed -i \'s/config1/config2/g\' /etc/magma/mme.yml'
"""
data = self._data
data["command"] = '"' + command + '"'
param_list = shlex.split(self._command.format(**data))
return subprocess.call(
param_list,
shell=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def exec_command_output(self, command):
"""
Run a command remotely on magma_dev VM.
Args:
command: command (str) to be executed on remote host
e.g. 'sed -i \'s/config1/config2/g\' /etc/magma/mme.yml'
"""
data = self._data
data["command"] = '"' + command + '"'
param_list = shlex.split(self._command.format(**data))
return subprocess.check_output(
param_list,
shell=False,
).decode("utf-8")
def config_stateless(self, cmd):
"""
Configure the stateless mode on the access gateway
Args:
cmd: Specify how to configure stateless mode on AGW,
should be one of
check: Run a check whether AGW is stateless or not
enable: Enable stateless mode, do nothing if already stateless
disable: Disable stateless mode, do nothing if already stateful
"""
magtivate_cmd = "source /home/vagrant/build/python/bin/activate"
venvsudo_cmd = "sudo -E PATH=$PATH PYTHONPATH=$PYTHONPATH env"
config_stateless_script = "/usr/local/bin/config_stateless_agw.py"
ret_code = self.exec_command(
magtivate_cmd + " && " + venvsudo_cmd + " python3 " +
config_stateless_script + " " + cmd.name.lower()
)
if ret_code == 0:
print("AGW is stateless")
elif ret_code == 1:
print("AGW is stateful")
elif ret_code == 2:
print("AGW is in a mixed config, check gateway")
else:
print("Unknown command")
def corrupt_agw_state(self, key: str):
"""
Corrupts data on redis of stateless AGW
Args:
key:
"""
magtivate_cmd = "source /home/vagrant/build/python/bin/activate"
state_corrupt_cmd = "state_cli.py corrupt %s" % key.lower()
self.exec_command(magtivate_cmd + " && " + state_corrupt_cmd)
print("Corrupted %s on redis" % key)
def restart_all_services(self):
"""Restart all magma services on magma_dev VM"""
self.exec_command(
"sudo service magma@* stop ; sudo service magma@magmad start"
)
print("Waiting for all services to restart. Sleeping for 60 seconds..")
timeSlept = 0
while timeSlept < 60:
time.sleep(5)
timeSlept += 5
print("*********** Slept for " + str(timeSlept) + " seconds")
def restart_services(self, services):
"""
Restart a list of magmad services.
Args:
services: List of (str) services names
"""
self._magmad_client.restart_services(services)
def enable_service(self, service):
"""
Enables a magma service on magma_dev VM and starts it
Args:
service: (str) service to enable
"""
self.exec_command("sudo systemctl unmask magma@{}".format(service))
self.exec_command("sudo systemctl start magma@{}".format(service))
def disable_service(self, service):
"""
Disables a magma service on magma_dev VM, preventing from
starting again
Args:
service: (str) service to disable
"""
self.exec_command("sudo systemctl mask magma@{}".format(service))
self.exec_command("sudo systemctl stop magma@{}".format(service))
def is_service_active(self, service) -> bool:
"""
Checks if a magma service on magma_dev VM is active
Args:
service: (str) service to check if it's active
"""
is_active_service_cmd = "systemctl is-active magma@" + service
try:
result_str = self.exec_command_output(is_active_service_cmd)
except subprocess.CalledProcessError as e:
# if service is disabled / masked, is-enabled will return
# non-zero exit status
result_str = e.output
return result_str.strip() == "active"
def update_mme_config_for_sanity(self, cmd):
mme_config_update_script = (
"/home/vagrant/magma/lte/gateway/deploy/roles/magma/files/"
"update_mme_config_for_sanity.sh"
)
action = cmd.name.lower()
ret_code = self.exec_command(
"sudo -E " + mme_config_update_script + " " + action
)
if ret_code == 0:
print("MME configuration is updated successfully")
elif ret_code == 1:
assert False, (
"Failed to "
+ action
+ " MME configuration. Error: Invalid command"
)
elif ret_code == 2:
assert False, (
"Failed to "
+ action
+ " MME configuration. Error: MME configuration file is "
+ "missing"
)
elif ret_code == 3:
assert False, (
"Failed to "
+ action
+ " MME configuration. Error: MME configuration's backup file "
+ "is missing"
)
else:
assert False, (
"Failed to "
+ action
+ " MME configuration. Error: Unknown error"
)
def config_apn_correction(self, cmd):
"""
Configure the apn correction mode on the access gateway
Args:
cmd: Specify how to configure apn correction mode on AGW,
should be one of
enable: Enable apn correction feature, do nothing if already enabled
disable: Disable apn correction feature, do nothing if already disabled
"""
apn_correction_cmd = ""
if cmd.name == MagmadUtil.apn_correction_cmds.ENABLE.name:
apn_correction_cmd = "sed -i \'s/enable_apn_correction: false/enable_apn_correction: true/g\' /etc/magma/mme.yml"
else:
apn_correction_cmd = "sed -i \'s/enable_apn_correction: true/enable_apn_correction: false/g\' /etc/magma/mme.yml"
ret_code = self.exec_command(
"sudo " + apn_correction_cmd)
if ret_code == 0:
print("APN Correction configured")
else:
print("APN Correction failed")
def config_health_service(self, cmd: health_service_cmds):
"""
Configure magma@health service on access gateway
Args:
cmd: Enable / Disable cmd to configure service
"""
magma_health_service_name = "health"
# Update health config to increment frequency of service failures
if cmd.name == MagmadUtil.health_service_cmds.DISABLE.name:
health_config_cmd = ("sed -i 's/interval_check_mins: 1/interval_"
"check_mins: 3/g' /etc/magma/health.yml")
self.exec_command("sudo %s" % health_config_cmd)
if self.is_service_active(magma_health_service_name):
self.disable_service(magma_health_service_name)
print("Health service is disabled")
elif cmd.name == MagmadUtil.health_service_cmds.ENABLE.name:
health_config_cmd = ("sed -i 's/interval_check_mins: 3/interval_"
"check_mins: 1/g' /etc/magma/health.yml")
self.exec_command("sudo %s" % health_config_cmd)
if not self.is_service_active(magma_health_service_name):
self.enable_service("health")
print("Health service is enabled")
def config_ipv6_solicitation(self, cmd):
"""
Enable/disable the ipv6_solicitation service in pipelined configuration
Args:
cmd: Specify whether ipv6_solicitation should be enabled or not
- enable: Enable ipv6_solicitation service,
do nothing if already enabled
- disable: Disable ipv6_solicitation service,
do nothing if already disabled
Returns:
-1: Failed to configure
0: Already configured
1: Configured successfully. Need to restart the service
"""
ipv6_update_config_cmd = ""
ipv6_config_status_cmd = (
"grep 'ipv6_solicitation' /etc/magma/pipelined.yml | wc -l"
)
ret_code = self.exec_command_output(ipv6_config_status_cmd).rstrip()
if cmd.name == MagmadUtil.ipv6_config_cmds.ENABLE.name:
if ret_code != "0":
print("IPv6 solicitation service is already enabled")
return 0
else:
ipv6_update_config_cmd = (
r"sed -i \"/startup_flows/a \ \ 'ipv6_solicitation',\" "
"/etc/magma/pipelined.yml"
)
else:
if ret_code == "0":
print("IPv6 solicitation service is already disabled")
return 0
else:
ipv6_update_config_cmd = (
"sed -i '/ipv6_solicitation/d' /etc/magma/pipelined.yml"
)
ret_code = self.exec_command("sudo " + ipv6_update_config_cmd)
if ret_code == 0:
print("IPv6 solicitation service configured successfully")
return 1
print("IPv6 solicitation service configuration failed")
return -1
def config_ha_service(self, cmd):
"""
Modify the mme configuration by enabling/disabling use of Ha service
Args:
cmd: Specify whether Ha service is enabled for use or not
- enable: Enable Ha service, do nothing if already enabled
- disable: Disable Ha service, do nothing if already disabled
Returns:
-1: Failed to configure
0: Already configured
1: Configured successfully. Need to restart the service
"""
ha_config_cmd = ""
if cmd.name == MagmadUtil.ha_service_cmds.ENABLE.name:
ha_config_status_cmd = (
"grep 'use_ha: true' /etc/magma/mme.yml | wc -l"
)
ret_code = self.exec_command_output(ha_config_status_cmd).rstrip()