-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
2906 lines (2426 loc) · 120 KB
/
Copy pathapi.py
File metadata and controls
2906 lines (2426 loc) · 120 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
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
"""
API endpoints for Multicaster application
"""
from flask import Blueprint, request, jsonify, make_response
from sqlalchemy import or_, and_, func
from datetime import datetime
from models import (
db, Branch, Switch, SwitchPort, Device, DeviceIP,
DeviceConnection, IPAllocation, UserRole, PortSpeed, DeviceType, PortGroup, BranchMulticastConfig, DeviceTemplate, SwitchPair
)
from auth import require_role
from services.ip_service import IPAllocationService
from services.port_service import PortAllocationService
import ipaddress
import csv
import io
import os
import subprocess
import tempfile
from datetime import datetime
api_bp = Blueprint('api', __name__)
# Branch Management Endpoints
@api_bp.route('/branches', methods=['GET'])
@require_role(UserRole.VIEWER)
def list_branches():
"""List all branches"""
branches = Branch.query.all()
return jsonify({
'branches': [branch.to_dict() for branch in branches]
})
@api_bp.route('/branches', methods=['POST'])
@require_role(UserRole.MANAGER)
def create_branch():
"""Create new branch"""
data = request.get_json()
if not data or not all(k in data for k in ['name', 'code']):
return jsonify({'error': 'Name and code are required'}), 400
# Check if branch code already exists
if Branch.query.filter_by(code=data['code']).first():
return jsonify({'error': 'Branch code already exists'}), 409
# Create branch with only basic fields - IP ranges will be configured later
branch = Branch(
name=data['name'],
code=data['code'],
address=data.get('address', ''),
vlan_range=data.get('vlan_range', ''),
# Initialize empty range arrays
unicast_control_ranges=[],
unicast_media_main_ranges=[],
multicast_media_main_video_ranges=[],
multicast_media_main_audio1_ranges=[],
multicast_media_main_audio2_ranges=[],
multicast_media_main_audio3_ranges=[],
multicast_media_main_audio4_ranges=[],
multicast_media_main_data_ranges=[],
unicast_media_backup_ranges=[],
multicast_media_backup_video_ranges=[],
multicast_media_backup_audio1_ranges=[],
multicast_media_backup_audio2_ranges=[],
multicast_media_backup_audio3_ranges=[],
multicast_media_backup_audio4_ranges=[],
multicast_media_backup_data_ranges=[]
)
db.session.add(branch)
db.session.commit()
return jsonify({
'message': 'Branch created successfully',
'branch': branch.to_dict()
}), 201
@api_bp.route('/branches/<int:branch_id>', methods=['GET'])
@require_role(UserRole.VIEWER)
def get_branch(branch_id):
"""Get branch details"""
branch = Branch.query.get_or_404(branch_id)
# Get additional statistics
branch_data = branch.to_dict()
branch_data['switches'] = [switch.to_dict() for switch in branch.switches]
branch_data['ip_stats'] = IPAllocationService.get_branch_ip_stats(branch_id)
return jsonify({'branch': branch_data})
@api_bp.route('/branches/<int:branch_id>', methods=['PUT'])
@require_role(UserRole.MANAGER)
def update_branch(branch_id):
"""Update branch"""
branch = Branch.query.get_or_404(branch_id)
data = request.get_json()
if 'name' in data:
branch.name = data['name']
if 'code' in data and data['code'] != branch.code:
if Branch.query.filter_by(code=data['code']).first():
return jsonify({'error': 'Branch code already exists'}), 409
branch.code = data['code']
if 'address' in data:
branch.address = data['address']
# Handle IP range updates
# Control Network
if 'unicast_control_ranges' in data:
branch.unicast_control_ranges = data['unicast_control_ranges']
# Media Main Network
if 'unicast_media_main_ranges' in data:
branch.unicast_media_main_ranges = data['unicast_media_main_ranges']
if 'multicast_media_main_video_ranges' in data:
branch.multicast_media_main_video_ranges = data['multicast_media_main_video_ranges']
if 'multicast_media_main_audio1_ranges' in data:
branch.multicast_media_main_audio1_ranges = data['multicast_media_main_audio1_ranges']
if 'multicast_media_main_audio2_ranges' in data:
branch.multicast_media_main_audio2_ranges = data['multicast_media_main_audio2_ranges']
if 'multicast_media_main_audio3_ranges' in data:
branch.multicast_media_main_audio3_ranges = data['multicast_media_main_audio3_ranges']
if 'multicast_media_main_audio4_ranges' in data:
branch.multicast_media_main_audio4_ranges = data['multicast_media_main_audio4_ranges']
if 'multicast_media_main_data_ranges' in data:
branch.multicast_media_main_data_ranges = data['multicast_media_main_data_ranges']
# Media Backup Network
if 'unicast_media_backup_ranges' in data:
branch.unicast_media_backup_ranges = data['unicast_media_backup_ranges']
if 'multicast_media_backup_video_ranges' in data:
branch.multicast_media_backup_video_ranges = data['multicast_media_backup_video_ranges']
if 'multicast_media_backup_audio1_ranges' in data:
branch.multicast_media_backup_audio1_ranges = data['multicast_media_backup_audio1_ranges']
if 'multicast_media_backup_audio2_ranges' in data:
branch.multicast_media_backup_audio2_ranges = data['multicast_media_backup_audio2_ranges']
if 'multicast_media_backup_audio3_ranges' in data:
branch.multicast_media_backup_audio3_ranges = data['multicast_media_backup_audio3_ranges']
if 'multicast_media_backup_audio4_ranges' in data:
branch.multicast_media_backup_audio4_ranges = data['multicast_media_backup_audio4_ranges']
if 'multicast_media_backup_data_ranges' in data:
branch.multicast_media_backup_data_ranges = data['multicast_media_backup_data_ranges']
if 'vlan_range' in data:
branch.vlan_range = data['vlan_range']
if 'use_subnet30_allocation' in data:
branch.use_subnet30_allocation = data['use_subnet30_allocation']
db.session.commit()
return jsonify({
'message': 'Branch updated successfully',
'branch': branch.to_dict()
})
@api_bp.route('/branches/<int:branch_id>', methods=['DELETE'])
@require_role(UserRole.ADMIN)
def delete_branch(branch_id):
"""Delete branch (admin only)"""
branch = Branch.query.get_or_404(branch_id)
db.session.delete(branch)
db.session.commit()
return jsonify({'message': 'Branch deleted successfully'})
# Switch Management Endpoints
@api_bp.route('/branches/<int:branch_id>/switches', methods=['GET'])
@require_role(UserRole.VIEWER)
def list_switches(branch_id):
"""List switches in a branch"""
branch = Branch.query.get_or_404(branch_id)
switches = Switch.query.filter_by(branch_id=branch_id).all()
return jsonify({
'switches': [switch.to_dict() for switch in switches],
'branch': branch.to_dict()
})
@api_bp.route('/switches', methods=['POST'])
@require_role(UserRole.OPERATOR)
def create_switch():
"""Create new switch"""
data = request.get_json()
if not data or not all(k in data for k in ['name', 'branch_id']):
return jsonify({'error': 'Name and branch_id are required'}), 400
# Verify branch exists
branch = Branch.query.get_or_404(data['branch_id'])
# Parse switch type
switch_type_value = data.get('switch_type', 'media')
try:
from models import SwitchType
switch_type = SwitchType(switch_type_value)
except ValueError:
return jsonify({'error': f'Invalid switch type: {switch_type_value}'}), 400
switch = Switch(
name=data['name'],
model=data.get('model'),
manufacturer=data.get('manufacturer'),
ip_address=data.get('ip_address'),
management_ip=data.get('management_ip'),
location=data.get('location'),
switch_type=switch_type,
api_endpoint=data.get('api_endpoint'),
is_managed=data.get('is_managed', False),
branch_id=data['branch_id']
)
db.session.add(switch)
db.session.commit()
# Create default ports if specified
try:
port_count = int(data.get('port_count', 48))
if port_count <= 0 or port_count > 512: # Reasonable limits
return jsonify({'error': 'Port count must be between 1 and 512'}), 400
except (ValueError, TypeError):
return jsonify({'error': 'Port count must be a valid number'}), 400
port_speed = data.get('default_port_speed', '10G')
try:
PortAllocationService.create_default_ports(switch.id, port_count, PortSpeed(port_speed))
except Exception as e:
# If port creation fails, clean up the switch
db.session.delete(switch)
db.session.commit()
return jsonify({'error': f'Failed to create switch ports: {str(e)}'}), 500
return jsonify({
'message': 'Switch created successfully',
'switch': switch.to_dict()
}), 201
@api_bp.route('/switches/<int:switch_id>', methods=['GET'])
@require_role(UserRole.VIEWER)
def get_switch(switch_id):
"""Get switch details with ports and devices"""
switch = Switch.query.get_or_404(switch_id)
switch_data = switch.to_dict()
switch_data['ports'] = [port.to_dict() for port in switch.ports]
switch_data['devices'] = [device.to_dict() for device in switch.devices]
return jsonify({'switch': switch_data})
@api_bp.route('/switches/<int:switch_id>', methods=['PUT'])
@require_role(UserRole.OPERATOR)
def update_switch(switch_id):
"""Update switch"""
switch = Switch.query.get_or_404(switch_id)
data = request.get_json()
updatable_fields = [
'name', 'model', 'manufacturer', 'ip_address',
'management_ip', 'location', 'api_endpoint', 'is_managed'
]
for field in updatable_fields:
if field in data:
setattr(switch, field, data[field])
db.session.commit()
return jsonify({
'message': 'Switch updated successfully',
'switch': switch.to_dict()
})
@api_bp.route('/switches/<int:switch_id>', methods=['DELETE'])
@require_role(UserRole.MANAGER)
def delete_switch(switch_id):
"""Delete switch"""
switch = Switch.query.get_or_404(switch_id)
db.session.delete(switch)
db.session.commit()
return jsonify({'message': 'Switch deleted successfully'})
# Port Management Endpoints
@api_bp.route('/switches/<int:switch_id>/ports', methods=['GET'])
@require_role(UserRole.VIEWER)
def list_ports(switch_id):
"""List ports for a switch, including breakout sub-ports"""
switch = Switch.query.get_or_404(switch_id)
# Get all ports for this switch, including breakout sub-ports
all_ports = SwitchPort.query.filter_by(switch_id=switch_id).order_by(SwitchPort.port_number).all()
# Organize ports: main ports first, then their sub-ports
organized_ports = []
# First pass: get all main ports (no parent)
main_ports = [p for p in all_ports if p.parent_port_id is None]
for main_port in main_ports:
organized_ports.append(main_port)
# Add sub-ports for this main port if they exist
sub_ports = [p for p in all_ports if p.parent_port_id == main_port.id]
sub_ports.sort(key=lambda x: x.port_number) # Sort sub-ports by number
organized_ports.extend(sub_ports)
return jsonify({
'ports': [port.to_dict() for port in organized_ports],
'switch': switch.to_dict(),
'total_main_ports': len(main_ports),
'total_ports': len(all_ports)
})
# Port group endpoints
@api_bp.route('/switches/<int:switch_id>/port-groups', methods=['GET'])
@require_role(UserRole.VIEWER)
def list_port_groups(switch_id):
"""List all port groups for a switch"""
switch = Switch.query.get_or_404(switch_id)
port_groups = PortGroup.query.filter_by(switch_id=switch_id).order_by(PortGroup.group_number).all()
return jsonify({
'port_groups': [pg.to_dict() for pg in port_groups],
'switch': switch.to_dict()
})
@api_bp.route('/port-groups/<int:group_id>/mode', methods=['PUT'])
@require_role(UserRole.OPERATOR)
def change_port_group_mode(group_id):
"""Change port group mode between 100G and 25G"""
data = request.get_json()
if not data or 'mode' not in data:
return jsonify({'error': 'Mode is required'}), 400
try:
new_mode = PortSpeed(data['mode'])
if new_mode not in [PortSpeed.HUNDRED_G, PortSpeed.TWENTY_FIVE_G]:
return jsonify({'error': 'Only 100G and 25G modes are supported'}), 400
except ValueError:
return jsonify({'error': 'Invalid mode specified'}), 400
success, message = PortAllocationService.change_port_group_mode(group_id, new_mode)
if not success:
return jsonify({'error': message}), 400
# Get updated port group
port_group = PortGroup.query.get(group_id)
return jsonify({
'message': message,
'port_group': port_group.to_dict() if port_group else None
})
@api_bp.route('/ports/<int:port_id>/devices', methods=['GET'])
@require_role(UserRole.VIEWER)
def get_port_devices(port_id):
"""Get devices connected to a specific port"""
port = SwitchPort.query.get_or_404(port_id)
# Get device connections for this port
connections = DeviceConnection.query.filter_by(port_id=port_id).all()
devices = [conn.device.to_dict() for conn in connections]
return jsonify({
'port': port.to_dict(),
'devices': devices
})
@api_bp.route('/ports/<int:port_id>/breakout', methods=['POST'])
@require_role(UserRole.OPERATOR)
def breakout_port(port_id):
"""Toggle port breakout (100G <-> 25G) for the port's group"""
port = SwitchPort.query.get_or_404(port_id)
if not port.port_group:
return jsonify({'error': 'Port is not part of a port group'}), 400
# Only allow breakout on odd ports (1, 3, 5, 7, etc.)
if port.port_number % 2 == 0:
return jsonify({'error': 'Port breakout can only be performed on odd ports (1, 3, 5, 7, etc.)'}), 400
# Determine the new mode (toggle between 100G and 25G)
current_mode = port.port_group.current_mode
new_mode = PortSpeed.TWENTY_FIVE_G if current_mode == PortSpeed.HUNDRED_G else PortSpeed.HUNDRED_G
# Use the port allocation service to change the mode
success, message = PortAllocationService.change_port_group_mode(port.port_group.id, new_mode)
if not success:
return jsonify({'error': message}), 400
# Refresh the port and return updated information
db.session.refresh(port)
return jsonify({
'message': message,
'port': port.to_dict(),
'port_group': port.port_group.to_dict()
})
# Device Management Endpoints
@api_bp.route('/devices', methods=['GET'])
@require_role(UserRole.VIEWER)
def list_devices():
"""List all devices with optional filtering"""
query = Device.query
# Filter by branch
branch_id = request.args.get('branch_id', type=int)
if branch_id:
query = query.join(Switch).filter(Switch.branch_id == branch_id)
# Filter by switch
switch_id = request.args.get('switch_id', type=int)
if switch_id:
query = query.filter(Device.switch_id == switch_id)
# Filter by device type
device_type = request.args.get('device_type')
if device_type:
query = query.filter(Device.device_type == DeviceType(device_type))
# Search by name
search = request.args.get('search')
if search:
query = query.filter(or_(
Device.name.ilike(f'%{search}%'),
Device.model.ilike(f'%{search}%'),
Device.manufacturer.ilike(f'%{search}%')
))
devices = query.all()
return jsonify({
'devices': [device.to_dict() for device in devices]
})
@api_bp.route('/devices/batch', methods=['POST'])
@require_role(UserRole.OPERATOR)
def create_devices_batch():
"""Create multiple devices with batch naming and smart switch assignment"""
data = request.get_json()
# Extract batch parameters
template_id = data.get('template_id')
prefix = data.get('prefix', '')
start_number = data.get('start_number', 1)
count = data.get('count', 1)
branch_id = data.get('branch_id')
# Media switches (same for all devices)
media_main_switch_id = data.get('media_main_switch_id')
media_backup_switch_id = data.get('media_backup_switch_id')
# Control switches (will shuffle between)
control_switch_ids = data.get('control_switch_ids', [])
if not template_id or not branch_id:
return jsonify({'error': 'Template ID and Branch ID are required'}), 400
if count > 50: # Reasonable limit
return jsonify({'error': 'Maximum 50 devices can be created at once'}), 400
# Get template
template = DeviceTemplate.query.get_or_404(template_id)
# Get branch
branch = Branch.query.get_or_404(branch_id)
created_devices = []
errors = []
try:
for i in range(count):
device_number = start_number + i
device_name = f"{prefix} {device_number}" if prefix else str(device_number)
# For control switches, shuffle between available switches
control_switch_id = None
if control_switch_ids:
control_switch_id = control_switch_ids[i % len(control_switch_ids)]
# Determine device type based on template capabilities
# If template has video/audio/data ports, it's likely a multicast device
device_type = DeviceType.MULTICAST if (template.video_ports > 0 or template.audio_ports > 0 or template.data_ports > 0) else DeviceType.UNICAST
# Determine device capabilities based on template
supports_multicast = bool(template.video_ports > 0 or template.audio_ports > 0 or template.data_ports > 0)
supports_unicast = True # Most devices support unicast
# Prepare device data to reuse single device creation logic
device_data = {
'name': device_name,
'manufacturer': template.manufacturer,
'model': template.model,
'serial_number': '',
'device_type': device_type, # Use enum directly
'template_id': template_id, # Include template_id for multi-port allocation
'control_switch_id': control_switch_id,
'media_main_switch_id': media_main_switch_id,
'media_backup_switch_id': media_backup_switch_id,
'video_ports': template.video_ports,
'audio_ports': template.audio_ports,
'data_ports': template.data_ports,
'supports_multicast': supports_multicast,
'supports_unicast': supports_unicast,
'required_port_speed': template.required_port_speed,
'multicast_video_port': 50100,
'multicast_audio1_port': 50104,
'multicast_audio2_port': 50104,
'multicast_audio3_port': 50104,
'multicast_audio4_port': 50104,
'multicast_data_port': 50102,
'notes': template.description,
'port_assignment_mode': 'auto',
# Enable all required checkboxes for full allocation
'needs_control': True,
'needs_video': True,
'needs_audio': True,
'needs_data': True,
'needs_control_unicast': True,
'needs_media_main_unicast': True,
'needs_media_backup_unicast': True,
'needs_media_main_video': supports_multicast,
'needs_media_main_audio1': supports_multicast,
'needs_media_main_audio2': supports_multicast,
'needs_media_main_audio3': supports_multicast,
'needs_media_main_audio4': supports_multicast,
'needs_media_main_data': supports_multicast,
'needs_media_backup_video': supports_multicast,
'needs_media_backup_audio1': supports_multicast,
'needs_media_backup_audio2': supports_multicast,
'needs_media_backup_audio3': supports_multicast,
'needs_media_backup_audio4': supports_multicast,
'needs_media_backup_data': supports_multicast,
'unicast_count': 1,
'required_connections': ['data'],
'control_port_id': '',
'media_main_port_id': '',
'media_backup_port_id': ''
}
try:
# Create device (exclude fields that aren't direct Device model fields)
device = Device(**{k: v for k, v in device_data.items() if k not in [
'control_switch_id', 'media_main_switch_id', 'media_backup_switch_id', 'port_assignment_mode',
'needs_control', 'needs_video', 'needs_audio', 'needs_data', 'needs_control_unicast',
'needs_media_main_unicast', 'needs_media_backup_unicast', 'needs_media_main_video',
'needs_media_main_audio1', 'needs_media_main_audio2', 'needs_media_main_audio3',
'needs_media_main_audio4', 'needs_media_main_data', 'needs_media_backup_video',
'needs_media_backup_audio1', 'needs_media_backup_audio2', 'needs_media_backup_audio3',
'needs_media_backup_audio4', 'needs_media_backup_data', 'unicast_count',
'required_connections', 'control_port_id', 'media_main_port_id', 'media_backup_port_id'
]})
# Set switch IDs for 3-port device structure
device.control_switch_id = control_switch_id
device.media_main_switch_id = media_main_switch_id
device.media_backup_switch_id = media_backup_switch_id
device.template_id = template_id # Ensure template_id is set
db.session.add(device)
db.session.flush() # Get device ID
# Allocate ports using the new multi-port service
port_result = PortAllocationService.allocate_multi_port_device_ports(
control_switch_id=control_switch_id,
media_main_switch_id=media_main_switch_id,
media_backup_switch_id=media_backup_switch_id,
control_ports_count=template.control_ports_count,
media_main_ports_count=template.media_main_ports_count,
media_backup_ports_count=template.media_backup_ports_count,
control_port_speed=template.control_port_speed,
media_main_port_speed=template.media_main_port_speed,
media_backup_port_speed=template.media_backup_port_speed,
port_assignment_mode='auto'
)
if port_result['success']:
# Create port connections for multiple ports per interface
# Control ports
for i, control_port in enumerate(port_result.get('control_ports', [])):
connection = DeviceConnection(
device_id=device.id,
port_id=control_port.id,
connection_type=f'control{f"_{i+1}" if i > 0 else ""}' # control, control_2, control_3, etc.
)
db.session.add(connection)
# Media main ports
for i, media_main_port in enumerate(port_result.get('media_main_ports', [])):
connection = DeviceConnection(
device_id=device.id,
port_id=media_main_port.id,
connection_type=f'media_main{f"_{i+1}" if i > 0 else ""}' # media_main, media_main_2, etc.
)
db.session.add(connection)
# Media backup ports
for i, media_backup_port in enumerate(port_result.get('media_backup_ports', [])):
connection = DeviceConnection(
device_id=device.id,
port_id=media_backup_port.id,
connection_type=f'media_backup{f"_{i+1}" if i > 0 else ""}' # media_backup, media_backup_2, etc.
)
db.session.add(connection)
# Allocate IPs
has_control = bool(control_switch_id)
has_media_main = bool(media_main_switch_id)
has_media_backup = bool(media_backup_switch_id)
# Use multi-port IP allocation to match the single device creation behavior
allocated_ip_groups = IPAllocationService.allocate_multi_port_device_ips(
branch_id=branch_id,
device_name=device.name,
control_ports_count=template.control_ports_count,
media_main_ports_count=template.media_main_ports_count,
media_backup_ports_count=template.media_backup_ports_count,
video_ports=device.video_ports if device.supports_multicast else 0,
audio_ports=device.audio_ports if device.supports_multicast else 0,
data_ports=device.data_ports if device.supports_multicast else 0
)
# Create DeviceIP records
for ip_type, ips in allocated_ip_groups.items():
for ip_addr in ips:
if 'control' in ip_type:
description = 'Control Network IP'
elif 'media_main' in ip_type:
if 'unicast' in ip_type:
description = 'Media Main Network IP'
else:
ip_service = ip_type.replace('media_main_', '').replace('_', ' ').title()
description = f'Media Main {ip_service} Multicast'
elif 'media_backup' in ip_type:
if 'unicast' in ip_type:
description = 'Media Backup Network IP'
else:
ip_service = ip_type.replace('media_backup_', '').replace('_', ' ').title()
description = f'Media Backup {ip_service} Multicast'
else:
description = f'{ip_type.replace("_", " ").title()} IP'
device_ip = DeviceIP(
ip_address=ip_addr,
ip_type='unicast' if 'unicast' in ip_type else 'multicast',
device_id=device.id,
is_primary=('control' in ip_type),
description=description
)
db.session.add(device_ip)
created_devices.append({
'name': device.name,
'id': device.id,
'status': 'created'
})
except Exception as e:
errors.append(f"Device '{device_name}': {str(e)}")
db.session.rollback()
# Continue with next device
if created_devices:
db.session.commit()
return jsonify({
'message': f'Batch creation completed. {len(created_devices)} devices created, {len(errors)} errors.',
'created_devices': created_devices,
'errors': errors,
'total_requested': count,
'total_created': len(created_devices)
})
except Exception as e:
db.session.rollback()
return jsonify({'error': f'Batch creation failed: {str(e)}'}), 500
@api_bp.route('/devices', methods=['POST'])
@require_role(UserRole.OPERATOR)
def create_device():
"""Create new device with automatic IP and port allocation"""
data = request.get_json()
print(f"DEBUG API: Full request data: {data}")
# For 3-port devices, we need either legacy switch_id OR the new 3-port switches
required_fields = ['name', 'device_type']
if not data or not all(k in data for k in required_fields):
return jsonify({'error': 'Name and device_type are required'}), 400
# Check 3-port device configuration - at least one switch must be specified
has_3port_switches = data.get('control_switch_id') or data.get('media_main_switch_id') or data.get('media_backup_switch_id')
if not has_3port_switches:
return jsonify({'error': 'At least one switch must be specified (control, media main, or media backup)'}), 400
# Get switch to determine branch (all switches should be in same branch)
switch_id = data.get('control_switch_id') or data.get('media_main_switch_id') or data.get('media_backup_switch_id')
switch = Switch.query.get_or_404(switch_id)
branch_id = switch.branch_id
# Create device
device = Device(
name=data['name'],
model=data.get('model'),
manufacturer=data.get('manufacturer'),
device_type=DeviceType(data['device_type']),
serial_number=data.get('serial_number'),
video_ports=data.get('video_ports', 0),
audio_ports=data.get('audio_ports', 0),
data_ports=data.get('data_ports', 1),
supports_multicast=data.get('supports_multicast', False),
supports_unicast=data.get('supports_unicast', True),
required_port_speed=data.get('required_port_speed', '10G'),
template_id=data.get('template_id'), # Store template reference
notes=data.get('notes'),
# Legacy switch (set to one of the 3-port switches for backward compatibility)
switch_id=switch.id,
# New 3-port device switches
control_switch_id=data.get('control_switch_id'),
media_main_switch_id=data.get('media_main_switch_id'),
media_backup_switch_id=data.get('media_backup_switch_id')
)
db.session.add(device)
db.session.flush() # Get device ID
# Check port compatibility and suggest actions if needed
required_port_speed = device.required_port_speed
port_warnings = []
port_actions_needed = []
# Check each switch that the device needs to connect to
switches_to_check = []
if device.control_switch_id:
switches_to_check.append(('control', device.control_switch_id))
if device.media_main_switch_id:
switches_to_check.append(('media_main', device.media_main_switch_id))
if device.media_backup_switch_id:
switches_to_check.append(('media_backup', device.media_backup_switch_id))
for connection_type, switch_id in switches_to_check:
from services.port_service import PortAllocationService
port_result = PortAllocationService.find_compatible_port(switch_id, required_port_speed, connection_type)
if port_result['status'] == 'wrong_switch_type':
# Wrong switch type - control/media segregation violation
return jsonify({
'error': 'Invalid switch type',
'message': f'Switch type mismatch for {connection_type} connection.',
'warnings': port_result['warnings'],
'alternatives': [],
'requires_confirmation': False,
'action_type': 'switch_type_error'
}), 400
elif port_result['status'] == 'needs_breakout':
# Serialize alternatives to make them JSON-safe
serialized_alternatives = []
for alt in port_result['alternatives']:
serialized_alt = {
'action': alt['action'],
'description': alt['description']
}
# Convert PortGroup to dict if present
if 'group' in alt and alt['group']:
serialized_alt['group'] = {
'id': alt['group'].id,
'group_number': alt['group'].group_number,
'start_port': alt['group'].start_port,
'end_port': alt['group'].end_port,
'current_mode': alt['group'].current_mode.value,
'is_broken_out': alt['group'].is_broken_out
}
# Convert SwitchPort to dict if present
if 'port' in alt and alt['port']:
serialized_alt['port'] = alt['port'].to_dict()
serialized_alternatives.append(serialized_alt)
# Require user confirmation for breakouts
return jsonify({
'error': 'Port breakout required',
'message': f'No {required_port_speed} ports available on {connection_type} switch. Breakout required.',
'warnings': port_result['warnings'],
'alternatives': serialized_alternatives,
'requires_confirmation': True,
'action_type': 'breakout'
}), 400
elif port_result['status'] == 'needs_change':
# Serialize alternatives to make them JSON-safe
serialized_alternatives = []
for alt in port_result['alternatives']:
serialized_alt = {
'action': alt['action'],
'description': alt['description']
}
# Convert SwitchPort to dict if present
if 'port' in alt and alt['port']:
serialized_alt['port'] = alt['port'].to_dict()
serialized_alternatives.append(serialized_alt)
# Require user confirmation for port reassignments
return jsonify({
'error': 'Port reassignment required',
'message': f'No available {required_port_speed} ports on {connection_type} switch. Port reassignment required.',
'warnings': port_result['warnings'],
'alternatives': serialized_alternatives,
'requires_confirmation': True,
'action_type': 'reassignment'
}), 400
elif port_result['status'] == 'not_available':
# No compatible ports available at all
return jsonify({
'error': 'No compatible ports available',
'message': f'No {required_port_speed} ports available on {connection_type} switch and no alternatives found.',
'switch_id': switch_id,
'connection_type': connection_type
}), 400
elif port_result['status'] == 'found':
# Port found - add any warnings to response
if port_result['warnings']:
port_warnings.extend([f"{connection_type}: {w}" for w in port_result['warnings']])
# Automatic IP allocation based on device ports and network configuration
# Determine which networks this device will use
has_control = bool(device.control_switch_id)
has_media_main = bool(device.media_main_switch_id)
has_media_backup = bool(device.media_backup_switch_id)
# Simplified IP allocation - automatically expand to detailed requirements
needs_control = data.get('needs_control', False)
needs_video = data.get('needs_video', False)
needs_audio = data.get('needs_audio', False)
needs_data = data.get('needs_data', False)
# Expand simplified requirements to detailed network-specific requirements
needs_control_unicast = needs_control
# Media Main network requirements (always include unicast if any media service is needed)
has_media_requirements = needs_video or needs_audio or needs_data
needs_media_main_unicast = has_media_requirements
needs_media_main_video = needs_video
needs_media_main_audio1 = needs_audio # All 4 audio channels if audio is selected
needs_media_main_audio2 = needs_audio
needs_media_main_audio3 = needs_audio
needs_media_main_audio4 = needs_audio
needs_media_main_data = needs_data
# Media Backup network requirements (mirror of main)
needs_media_backup_unicast = has_media_requirements
needs_media_backup_video = needs_video
needs_media_backup_audio1 = needs_audio
needs_media_backup_audio2 = needs_audio
needs_media_backup_audio3 = needs_audio
needs_media_backup_audio4 = needs_audio
needs_media_backup_data = needs_data
# Override has_control, has_media_main, has_media_backup based on actual IP needs
has_control = bool(device.control_switch_id) and needs_control_unicast
has_media_main = bool(device.media_main_switch_id) and (
needs_media_main_unicast or needs_media_main_video or
needs_media_main_audio1 or needs_media_main_audio2 or needs_media_main_audio3 or needs_media_main_audio4 or
needs_media_main_data
)
has_media_backup = bool(device.media_backup_switch_id) and (
needs_media_backup_unicast or needs_media_backup_video or
needs_media_backup_audio1 or needs_media_backup_audio2 or needs_media_backup_audio3 or needs_media_backup_audio4 or
needs_media_backup_data
)
# Use actual device port counts (only allocate if the service is enabled via checkboxes)
video_ports = device.video_ports if (needs_media_main_video or needs_media_backup_video) else 0
data_ports = device.data_ports if (needs_media_main_data or needs_media_backup_data) else 0
# Use actual device audio port count (only allocate if audio service is enabled via checkboxes)
audio_ports = device.audio_ports if (needs_media_main_audio1 or needs_media_main_audio2 or needs_media_main_audio3 or needs_media_main_audio4 or
needs_media_backup_audio1 or needs_media_backup_audio2 or needs_media_backup_audio3 or needs_media_backup_audio4) else 0
# Check if this is template-based multi-port allocation
template_id = data.get('template_id')
if template_id:
template = DeviceTemplate.query.get(template_id)
if template:
# Use multi-port IP allocation based on template
allocated_ip_groups = IPAllocationService.allocate_multi_port_device_ips(
branch_id=branch_id,
device_name=device.name,
control_ports_count=template.control_ports_count,
media_main_ports_count=template.media_main_ports_count,
media_backup_ports_count=template.media_backup_ports_count,
video_ports=video_ports,
audio_ports=audio_ports,
data_ports=data_ports
)
else:
# Fallback to single-port allocation
allocated_ip_groups = IPAllocationService.allocate_3port_device_ips(
branch_id=branch_id,
device_name=device.name,
has_control=has_control,
has_media_main=has_media_main,
has_media_backup=has_media_backup,
video_ports=video_ports,
audio_ports=audio_ports,
data_ports=data_ports
)
else:
# Standard single-port allocation for non-template devices
allocated_ip_groups = IPAllocationService.allocate_3port_device_ips(
branch_id=branch_id,
device_name=device.name,
has_control=has_control,
has_media_main=has_media_main,
has_media_backup=has_media_backup,
video_ports=video_ports,
audio_ports=audio_ports,
data_ports=data_ports
)
# Create DeviceIP records for all allocated IPs
all_allocated_ips = []
# Control Network Unicast IPs (no multicast on control network)
for ip_addr in allocated_ip_groups['control_unicast']:
device_ip = DeviceIP(
ip_address=ip_addr,
ip_type='unicast',
device_id=device.id,
is_primary=True, # Control IP is primary
description='Control Network IP'
)
db.session.add(device_ip)
all_allocated_ips.append(ip_addr)
# Media Main Network IPs
for ip_addr in allocated_ip_groups['media_main_unicast']:
device_ip = DeviceIP(
ip_address=ip_addr,
ip_type='unicast',
device_id=device.id,
is_primary=False,
description='Media Main Network IP'
)
db.session.add(device_ip)
all_allocated_ips.append(ip_addr)
# Get or create branch multicast configuration
branch_config = BranchMulticastConfig.query.filter_by(branch_id=branch_id).first()
if not branch_config:
branch_config = BranchMulticastConfig(branch_id=branch_id)
db.session.add(branch_config)
db.session.flush() # Get the ID
# Media Main Multicast IPs
for i, ip_addr in enumerate(allocated_ip_groups['media_main_multicast_video']):
device_ip = DeviceIP(
ip_address=ip_addr,
ip_type='multicast',
device_id=device.id,
is_primary=False,
description=f'Media Main Video Port {i+1}',
port=branch_config.multicast_video_port # Use branch's configured video port
)
db.session.add(device_ip)
all_allocated_ips.append(ip_addr)
# Process audio multicast IPs - they are now organized by channel
audio_ips = allocated_ip_groups['media_main_multicast_audio']
audio_ports_count = device.audio_ports
if audio_ports_count > 0 and audio_ips:
for i, ip_addr in enumerate(audio_ips):
# Calculate which channel and port within that channel
# IPs are allocated as: Ch1_Port1, Ch1_Port2, ..., Ch1_PortN, Ch2_Port1, Ch2_Port2, ...
audio_channel = (i // audio_ports_count) + 1
port_within_channel = (i % audio_ports_count) + 1
audio_port_attr = f'multicast_audio{audio_channel}_port'
audio_port = getattr(branch_config, audio_port_attr)
device_ip = DeviceIP(
ip_address=ip_addr,
ip_type='multicast',