/
ixf.py
2198 lines (1707 loc) · 68.6 KB
/
ixf.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
"""
IX-F importer implementation.
Handles import of ix-f feeds, creation of suggestions for networks and exchanges
to follow.
Handles notifications of networks and exchanges as part of that process.
A substantial part of the import logic is handled through models.py::IXFMemberData
"""
import datetime
import ipaddress
import json
from smtplib import SMTPException
import requests
import reversion
from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.mail.message import EmailMultiAlternatives
from django.db import transaction
from django.template import loader
from django.utils.html import strip_tags
from django.utils.translation import ugettext_lazy as _
import peeringdb_server.deskpro as deskpro
from peeringdb_server.models import (
DataChangeNotificationQueue,
DeskProTicket,
IXFImportEmail,
IXFMemberData,
IXLanIXFMemberImportAttempt,
IXLanIXFMemberImportLog,
IXLanIXFMemberImportLogEntry,
Network,
NetworkIXLan,
NetworkProtocolsDisabled,
User,
ValidationErrorEncoder,
)
REASON_ENTRY_GONE_FROM_REMOTE = _(
"The entry for (asn and IPv4 and IPv6) does not exist "
"in the exchange's IX-F data as a singular member connection"
)
REASON_NEW_ENTRY = _(
"The entry for (asn and IPv4 and IPv6) does not exist "
"in PeeringDB as a singular network -> ix connection"
)
REASON_VALUES_CHANGED = _(
"Data differences between PeeringDB and the exchange's IX-F data"
)
class MultipleVlansInPrefix(ValueError):
"""
This error is raised when an ix-f export contains
multiple vlan ids for the prefixes defined in the processed ixlan.
Since peeringdb treats each vlan as it's own exchange this currently
is not a compatible setup for import (see #889).
"""
def __init__(self, importer, *args, **kwargs):
importer.ixlan.ixf_ixp_member_list_url
importer.ixlan.ix.name
support_email = settings.DEFAULT_FROM_EMAIL
super().__init__(
_(
f"We found that your IX-F output "
f"contained multiple VLANs for the prefixes defined in the PeeringDB entry for your exchange."
"\n"
f"This setup is not compatible as PeeringDB regards each VLAN as its own exchange."
"\n"
f"Please contact {support_email} if you need assistance with resolving this issue."
)
)
class Importer:
allowed_states = [
"",
None,
"active",
"inactive",
"connected",
"operational",
]
@property
def ticket_user(self):
"""
Return the User instance for the user
to create DeskPRO tickets.
"""
if not hasattr(self, "_ticket_user"):
self._ticket_user = User.objects.get(username="ixf_importer")
return self._ticket_user
@property
def deskpro_client(self):
if not hasattr(self, "_deskpro_client"):
if settings.IXF_SEND_TICKETS:
cls = deskpro.APIClient
else:
cls = deskpro.MockAPIClient
self._deskpro_client = cls(settings.DESKPRO_URL, settings.DESKPRO_KEY)
return self._deskpro_client
@property
def tickets_enabled(self):
"""
Return whether deskpr ticket creation for ix-f
conflicts are enabled or not.
This can be controlled by the IXF_TICKET_ON_CONFLICT
setting.
"""
return getattr(settings, "IXF_TICKET_ON_CONFLICT", True)
@property
def notify_ix_enabled(self):
"""
Return whether notifications to the exchange
are enabled or not.
This can be controlled by the IXF_NOTIFY_IX_ON_CONFLICT
setting.
"""
return getattr(settings, "IXF_NOTIFY_IX_ON_CONFLICT", False)
@property
def notify_net_enabled(self):
"""
Return whether notifications to the network
are enabled or not.
This can be controlled by the IXF_NOTIFY_NET_ON_CONFLICT
setting.
"""
return getattr(settings, "IXF_NOTIFY_NET_ON_CONFLICT", False)
def __init__(self):
self.cache_only = False
self.skip_import = False
self.reset()
def reset(self, ixlan=None, save=False, asn=None):
self.reset_log()
self.ixf_ids = []
self.actions_taken = {
"add": [],
"delete": [],
"modify": [],
"noop": [],
}
self.pending_save = []
self.deletions = {}
self.asns = []
self.ixlan = ixlan
self.vlan = None
self.save = save
self.asn = asn
self.now = datetime.datetime.now(datetime.timezone.utc)
self.invalid_ip_errors = []
self.notifications = []
self.protocol_conflict = 0
self.emails = 0
def fetch(self, url, timeout=5):
"""
Retrieve ixf member export data from the url.
Will do a quick sanity check on the data.
Return dict containing the parsed data.
Arguments:
- url <str>
Keyword arguments:
- timeout <float>: max time to spend on request
"""
if not url:
return {"pdb_error": _("IX-F import url not specified")}
try:
result = requests.get(url, timeout=timeout)
except Exception as exc:
return {"pdb_error": exc}
if result.status_code != 200:
return {"pdb_error": f"Got HTTP status {result.status_code}"}
try:
data = result.json()
except Exception:
data = {"pdb_error": _("No JSON could be parsed")}
return data
data = self.sanitize(data)
# locally cache result
if data and not data.get("pdb_error"):
cache.set(self.cache_key(url), data, timeout=None)
return data
def cache_key(self, url):
"""
Return the django cache key to use for caching ix-f data.
Argument:
url <str>
"""
return f"IXF-CACHE-{url}"
def fetch_cached(self, url):
"""
Return locally cached IX-F data.
Arguments:
url <str>
"""
if not url:
return {"pdb_error": _("IX-F import url not specified")}
data = cache.get(self.cache_key(url))
if data is None:
return {
"pdb_error": _("IX-F data not locally cached for this resource yet.")
}
return data
def find_vlan_needing_pair(self, connection):
vlans_needing_pair = []
vlan_list = connection.get("vlan_list", [])
for vlan in vlan_list:
if vlan.get("ipv4") and not vlan.get("ipv6"):
vlans_needing_pair.append(vlan)
elif vlan.get("ipv6") and not vlan.get("ipv4"):
vlans_needing_pair.append(vlan)
if len(vlans_needing_pair) == 0:
return None
return vlans_needing_pair
def get_if_speed_list(self, connection):
if_speed_list = []
for if_entry in connection.get("if_list", []):
if if_entry.get("if_speed"):
if_speed_list.append(if_entry.get("if_speed"))
if_speed_list.sort()
return if_speed_list
def connections_match(self, connection1, connection2):
# Check that both connections have a 'state' set
state_match = connection1.get("state", "undefined") == connection2.get(
"state", "undefined"
)
if_list_1 = self.get_if_speed_list(connection1)
if_list_2 = self.get_if_speed_list(connection2)
if_list_match = if_list_1 == if_list_2
return state_match and if_list_match
def find_connections_that_match(self, connection, connection_list):
cxns_that_match = []
for connection2 in connection_list:
if self.connections_match(connection, connection2):
cxns_that_match.append(connection2)
if len(cxns_that_match) == 0:
return None
return cxns_that_match
def match_vlans_across_connections(self, connection_list):
modified_connection_list = []
for i, connection in enumerate(connection_list):
"""
If there aren't any vlans in the connection at
all, skip it. (This might happen in the course
of matching vlans).
"""
if len(connection.get("vlan_list", [])) == 0:
continue
remaining_connections = connection_list[i + 1 :]
vlans_needing_pair = self.find_vlan_needing_pair(connection)
# If there aren't any vlans that need to be paired,
# we're done looking at this connection
if vlans_needing_pair is None:
modified_connection_list.append(connection)
continue
cxns_that_match = self.find_connections_that_match(
connection, remaining_connections
)
# If there aren't any connections we could match up,
# we're done looking at this connection
if cxns_that_match is None:
modified_connection_list.append(connection)
continue
# If we have vlans we want to match, and
# at least one connection we can look for
# start looking
for lone_vlan in vlans_needing_pair:
matching_vlan = self.find_matching_vlan(lone_vlan, cxns_that_match)
# if we found one we need to transfer it
if matching_vlan is not None:
# matching vlan goes into connection vlan_list
connection["vlan_list"].append(matching_vlan)
modified_connection_list.append(connection)
return modified_connection_list
def find_matching_vlan(self, lone_vlan, connections_that_match):
for connection in connections_that_match:
for j, potential_vlan in enumerate(connection["vlan_list"]):
if self.vlan_matches(lone_vlan, potential_vlan):
# Matching vlan gets deleted from other connection
return connection["vlan_list"].pop(j)
return None
def vlan_matches(self, vlan1, vlan2):
vlan_ids_match = vlan1.get("vlan_id", 0) == vlan2.get("vlan_id", 0)
if vlan_ids_match is False:
return False
if vlan1.get("ipv4") and vlan2.get("ipv4"):
return False
if vlan1.get("ipv6") and vlan2.get("ipv6"):
return False
return True
def sanitize_vlans(self, vlans):
"""
Sanitize vlan lists where ip 4 and 6 addresses
for the same vlan (determined by vlan id) exist
in separate entries by combining those
list entries to one.
"""
_vlans = {}
sanitized = []
for vlan in vlans:
# if the vlan_id is not specified we want
# to default to 0 so we can still group based
# on that
id = vlan.get("vlan_id", 0)
# the ix-f schema allows setting ipv4 and ipv6 to
# null, in which case remove the property
if "ipv4" in vlan and not vlan.get("ipv4"):
del vlan["ipv4"]
if "ipv6" in vlan and not vlan.get("ipv6"):
del vlan["ipv6"]
# neither ipv4 nor ipv6 is specified, there is
# nothing to sanitize here, so skip
if "ipv4" not in vlan and "ipv6" not in vlan:
continue
if id not in _vlans:
# first occurance of vlan id gets appended
# as is
_vlans[id] = [vlan]
else:
# additional occurances of vlan id get checked
# on whether or not they will fill in a missing
# ipv4 or ipv6 address, and if so will update
# the existing vlan entry.
#
# otherwise append as a new entry for that vlan id
current = _vlans[id][-1]
update = None
if "ipv4" in vlan and "ipv4" not in current:
update = "ipv4"
elif "ipv6" in vlan and "ipv6" not in current:
update = "ipv6"
if update:
current[update] = vlan[update]
else:
_vlans[id].append(vlan)
for vlan_id, entries in _vlans.items():
sanitized.extend(entries)
return sanitized
def sanitize(self, data):
"""
Take ixf data dict and run sanitization on it.
"""
invalid = None
ipv4_addresses = {}
ipv6_addresses = {}
# dedupe identical entries in member list
member_list = [json.dumps(m) for m in data.get("member_list", [])]
member_list = [json.loads(m) for m in set(member_list)]
# This fixes instances where ixps provide two separate entries for
# vlans in vlan_list for ipv4 and ipv6 (AMS-IX for example)
for member in member_list:
asn = member.get("asnum")
connection_list = self.match_vlans_across_connections(
member.get("connection_list", [])
)
for conn in connection_list:
conn["vlan_list"] = self.sanitize_vlans(conn.get("vlan_list", []))
vlans = conn["vlan_list"]
if not vlans:
continue
# de-dupe reoccurring ipv4 / ipv6 addresses
ipv4 = vlans[0].get("ipv4", {}).get("address")
ipv6 = vlans[0].get("ipv6", {}).get("address")
ixf_id = (asn, ipv4, ipv6)
if ipv4 and ipv4 in ipv4_addresses:
invalid = _(
"Address {} assigned to more than one distinct connection"
).format(ipv4)
break
ipv4_addresses[ipv4] = ixf_id
if ipv6 and ipv6 in ipv6_addresses:
invalid = _(
"Address {} assigned to more than one distinct connection"
).format(ipv6)
break
ipv6_addresses[ipv6] = ixf_id
data["pdb_error"] = invalid
# set member_list to the sanitized copy
data["member_list"] = member_list
return data
def update(self, ixlan, save=True, data=None, timeout=5, asn=None):
"""
Sync netixlans under this ixlan from ixf member export json data (specs
can be found at https://github.com/euro-ix/json-schemas).
Arguments:
- ixlan (IXLan): ixlan object to update from ixf
Keyword Arguments:
- save (bool): commit changes to db
- asn (int): only process changes for this ASN
Returns:
- Tuple(success<bool>, netixlans<list>, log<list>)
"""
self.reset(ixlan=ixlan, save=save, asn=asn)
# if data is not provided, retrieve it either from cache or
# from the remote resource
if data is None:
if self.cache_only:
data = self.fetch_cached(ixlan.ixf_ixp_member_list_url)
else:
data = self.fetch(ixlan.ixf_ixp_member_list_url, timeout=timeout)
# bail if there has been any errors during sanitize() or fetch()
if data.get("pdb_error"):
self.notify_error(data.get("pdb_error"))
self.log_error(data.get("pdb_error"), save=save)
return False
# bail if there are no active prefixes on the ixlan
if ixlan.ixpfx_set_active.count() == 0:
self.log_error(_("No prefixes defined on ixlan"), save=save)
return False
if self.skip_import:
return True
try:
# parse the ixf data
self.parse(data)
except MultipleVlansInPrefix as exc:
# multiple vlans found for prefixes specified on the ixlan
# we fail the import and notify the ix
#
# since the import hard fails here we want to remove all
# other queued notifications
#
# transactions are atomic and will be rolled back
self.notify_error(f"{exc}")
self.log_error(f"{exc}", save=save)
self.notifications = []
return False
except KeyError as exc:
# any key erros mean that the data is invalid, log the error and
# bail (transactions are atomic and will be rolled back)
self.log_error(f"Internal Error 'KeyError': {exc}", save=save)
return False
# null ix-f error note on ixlan if it had error'd before
if self.ixlan.ixf_ixp_import_error:
with transaction.atomic():
with reversion.create_revision():
reversion.set_user(self.ticket_user)
self.ixlan.ixf_ixp_import_error = None
self.ixlan.ixf_ixp_import_error_notified = None
self.ixlan.save()
with transaction.atomic():
# process any netixlans that need to be deleted
self.process_deletions()
# process creation of new netixlans and updates
# of existing netixlans. This needs to happen
# after process_deletions in order to avoid potential
# ip conflicts
self.process_saves()
self.cleanup_ixf_member_data()
# create tickets for unresolved proposals
# This function is currently disabled as per issue #860
self.ticket_aged_proposals()
# archive the import so we can roll it back later if needed
self.archive()
if self.invalid_ip_errors:
self.notify_error("\n".join(self.invalid_ip_errors))
if save:
# update exchange's ixf fields
self.update_ix()
if (
not self.protocol_conflict
and self.ixlan.ixf_ixp_import_protocol_conflict
):
self.ixlan.ixf_ixp_import_protocol_conflict = 0
self.ixlan.save()
self.save_log()
return True
def update_ix(self):
"""
Determine if any data was changed during this import
and update the exchange's ixf_last_import timestamp
if so.
Set the ixf_net_count value if it has changed
from before.
"""
ix = self.ixlan.ix
# ixf_member_data_changed = IXFMemberData.objects.filter(
# updated__gte=self.now, ixlan=self.ixlan
# ).exists()
# netixlan_data_changed = NetworkIXLan.objects.filter(
# updated__gte=self.now, ixlan=self.ixlan
# ).exists()
ix.ixf_last_import = self.now
ixf_net_count = len(self.pending_save)
if ixf_net_count != ix.ixf_net_count:
ix.ixf_net_count = ixf_net_count
# we do not want these updates to affect the
# exchanges `updated` timestamp as per #812
# so we temporarily disable auto_now
ix._meta.get_field("updated").auto_now = False
try:
with transaction.atomic():
with reversion.create_revision():
reversion.set_user(self.ticket_user)
ix.save()
finally:
# always turn auto_now back on afterwards
ix._meta.get_field("updated").auto_now = True
def fix_consolidated_modify(self, ixf_member_data):
"""
Fix consolidated modify (#770) to retain value
for speed and is_rs_peer (#793).
"""
for other in self.pending_save:
if other.asn == ixf_member_data.asn:
if (
other.init_ipaddr4
and other.init_ipaddr4 == ixf_member_data.init_ipaddr4
) or (
other.init_ipaddr6
and other.init_ipaddr6 == ixf_member_data.init_ipaddr6
):
if not other.modify_speed:
other.speed = ixf_member_data.speed
if not other.modify_is_rs_peer:
other.is_rs_peer = ixf_member_data.is_rs_peer
break
@reversion.create_revision()
@transaction.atomic()
def process_saves(self):
reversion.set_user(self.ticket_user)
for ixf_member in self.pending_save:
self.apply_add_or_update(ixf_member)
@reversion.create_revision()
@transaction.atomic()
def process_deletions(self):
"""
Cycle all netixlans on the ixlan targeted by the importer and
remove any that are no longer found in the ixf data by
their ip addresses.
In order for a netixlan to be removed, both its ipv4 and ipv6 address
or its asn need to be gone from the ixf data after validation.
"""
reversion.set_user(self.ticket_user)
netixlan_qset = self.ixlan.netixlan_set_active
# if we are only processing a specific asn ignore
# all that don't match
if self.asn:
netixlan_qset = netixlan_qset.filter(asn=self.asn)
for netixlan in netixlan_qset:
if netixlan.ixf_id not in self.ixf_ids:
ixf_member_data = IXFMemberData.instantiate(
netixlan.asn,
netixlan.ipaddr4,
netixlan.ipaddr6,
netixlan.ixlan,
speed=netixlan.speed,
operational=netixlan.operational,
is_rs_peer=netixlan.is_rs_peer,
delete=True,
data={},
)
# fix consolidated modify (#770) to retain values
# for speed and is_rs_peer (#793)
self.fix_consolidated_modify(ixf_member_data)
self.deletions[ixf_member_data.ixf_id] = ixf_member_data
if netixlan.network.allow_ixp_update:
self.log_apply(
ixf_member_data.apply(save=self.save),
reason=REASON_ENTRY_GONE_FROM_REMOTE,
)
else:
notify = ixf_member_data.set_remove(
save=self.save, reason=REASON_ENTRY_GONE_FROM_REMOTE
)
if notify:
self.queue_notification(ixf_member_data, "remove")
self.log_ixf_member_data(ixf_member_data)
def cleanup_ixf_member_data(self):
if not self.save:
"""
Do not run a cleanup process in some cases.
For example, when the importer runs in preview mode
triggered by a network admin.
"""
return
qset = IXFMemberData.objects.filter(ixlan=self.ixlan)
if self.asn:
# if we are only processing for a specified asn
# we only clean up member data for that asn
qset = qset.filter(asn=self.asn)
# clean up old ix-f memeber data objects
for ixf_member in qset:
# proposed deletion got fulfilled
if ixf_member.action == "delete":
if ixf_member.netixlan.status == "deleted":
if ixf_member.set_resolved(save=self.save):
self.queue_notification(ixf_member, "resolved")
# noop means the ask has been fulfilled but the
# ixf member data entry has not been set to resolved yet
elif ixf_member.action == "noop":
if (
ixf_member.set_resolved(save=self.save)
and not ixf_member.requirement_of_id
):
self.queue_notification(ixf_member, "resolved")
# proposed change / addition is now gone from
# ix-f data
elif not self.skip_import and ixf_member.ixf_id not in self.ixf_ids:
if ixf_member.action in ["add", "modify"]:
if ixf_member.set_resolved(save=self.save):
self.queue_notification(ixf_member, "resolved")
@transaction.atomic()
def archive(self):
"""
Create the IXLanIXFMemberImportLog for this import.
"""
if not self.save:
return
persist_log = IXLanIXFMemberImportLog.objects.create(ixlan=self.ixlan)
for action in ["delete", "modify", "add"]:
for info in self.actions_taken[action]:
netixlan = info["netixlan"]
version_before = info["version"]
versions = reversion.models.Version.objects.get_for_object(netixlan)
if version_before:
versions = versions.filter(id__gt=version_before.id)
version_after = versions.last()
else:
version_after = versions.first()
if not version_after:
continue
# push for data change notification (#403)
DataChangeNotificationQueue.push(
"ixf", action, netixlan, version_before, version_after, **info
)
persist_log.entries.create(
netixlan=netixlan,
version_before=version_before,
action=action,
reason=info.get("reason"),
version_after=version_after,
)
def parse(self, data):
"""
Parse ixf data.
Arguments:
- data <dict>: result from fetch()
"""
with transaction.atomic():
self.parse_members(data.get("member_list", []))
def parse_members(self, member_list):
"""
Parse the `member_list` section of the ixf schema.
Arguments:
- member_list <list>
"""
for member in member_list:
asn = member["asnum"]
# if we are only processing a specific asn, ignore all
# that don't match
if self.asn and asn != self.asn:
continue
# keep track of asns we find in the ix-f data
if asn not in self.asns:
self.asns.append(asn)
if Network.objects.filter(asn=asn).exists():
network = Network.objects.get(asn=asn)
if network.status != "ok":
self.log_peer(
asn,
"ignore",
_("Network status is '{}'").format(network.status),
)
continue
self.parse_connections(
member.get("connection_list", []), network, member
)
else:
self.log_peer(asn, "ignore", _("Network does not exist in peeringdb"))
def parse_connections(self, connection_list, network, member):
"""
Parse the 'connection_list' section of the ixf schema.
Arguments:
- connection_list <list>
- network <Network>: pdb network instance
- member <dict>: row from ixf member_list
"""
asn = member["asnum"]
for connection in connection_list:
self.connection_errors = {}
state = connection.get("state", "active").lower()
if state in self.allowed_states:
speed = self.parse_speed(connection.get("if_list", []))
self.parse_vlans(
connection.get("vlan_list", []), network, member, connection, speed
)
else:
self.log_peer(
asn, "ignore", _("Invalid connection state: {}").format(state)
)
def parse_vlans(self, vlan_list, network, member, connection, speed):
"""
Parse the 'vlan_list' section of the ixf_schema.
Arguments:
- vlan_list <list>
- network <Network>: pdb network instance
- member <dict>: row from ixf member_list
- connection <dict>: row from ixf connection_list
- speed <int>: interface speed
"""
asn = member["asnum"]
for lan in vlan_list:
ipv4 = lan.get("ipv4", {})
ipv6 = lan.get("ipv6", {})
# vlan entry has no ipaddresses set, log and ignore
if not ipv4 and not ipv6:
self.log_error(
_(
"Could not find ipv4 or 6 address in "
"vlan_list entry for vlan_id {} (AS{})"
).format(lan.get("vlan_id"), asn)
)
continue
ipv4_addr = ipv4.get("address")
ipv6_addr = ipv6.get("address")
ipv4_support = network.ipv4_support
ipv6_support = network.ipv6_support
# parse and validate the ipaddresses attached to the vlan
# append a unqiue ixf identifier to self.ixf_ids
#
# identifier is a tuple of (asn, ip4, ip6)
#
# we will later check them to see which netixlans need to be
# dropped during `process_deletions`
try:
ixf_id = [asn]
if ipv4_addr:
ipv4_addr = ipaddress.ip_address(f"{ipv4_addr}")
ixf_id.append(ipv4_addr)
else:
ixf_id.append(None)
if ipv6_addr:
ipv6_addr = ipaddress.ip_address(f"{ipv6_addr}")
ixf_id.append(ipv6_addr)
else:
ixf_id.append(None)
ixf_id = tuple(ixf_id)
except (ipaddress.AddressValueError, ValueError) as exc:
self.invalid_ip_errors.append(f"{exc}")
self.log_error(
_("Ip address error '{}' in vlan_list entry for vlan_id {}").format(
exc, lan.get("vlan_id")
)
)
continue
ipv4_valid_for_ixlan = self.ixlan.test_ipv4_address(ipv4_addr)
ipv6_valid_for_ixlan = self.ixlan.test_ipv6_address(ipv6_addr)
if (
ipv4_addr
and not ipv4_valid_for_ixlan
and ipv6_addr
and not ipv6_valid_for_ixlan
):
# neither ipaddress falls into address space
# for this ixlan, ignore
continue
elif not ipv4_valid_for_ixlan and not ipv6_addr:
# ipv4 address does not fall into address space
# and ipv6 is not provided, ignore
continue
elif not ipv6_valid_for_ixlan and not ipv4_addr:
# ipv6 address does not fall into address space
# and ipv4 is not provided, ignore
continue
vlan = lan.get("vlan_id")
if self.vlan is not None and vlan != self.vlan:
# prefixes spread over multiple vlans and
# cannot be represented properly at one ixlan
# fail the import
raise MultipleVlansInPrefix(self)
self.vlan = vlan
protocol_conflict = 0
# keep track of conflicts between ix/net in terms of ip
# protocols supported.
if ipv4_addr and not ipv4_support:
protocol_conflict = 4
elif ipv6_addr and not ipv6_support:
protocol_conflict = 6