This repository has been archived by the owner on May 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathracktables2netbox.py
1238 lines (1063 loc) · 43.7 KB
/
racktables2netbox.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = 1.00
import configparser
import json
import logging
import pprint
import pymysql
import pynetbox
import requests
import slugify
import socket
import struct
import urllib3
import re
class Migrator:
def slugify(self, text):
return slugify.slugify(text, max_length=50)
def create_tenant_group(self, name):
pass
def create_tenant(self, name, tenant_group=None):
logger.info("Creating tenant {}").format(name)
tenant = {
'name': name,
'slug': self.slugify(name)
}
if tenant_group:
tenant["tenant_group"] = netbox.tenancy.tenant_groups.all()
return netbox.tenancy.tenants.create(tenant)
def create_region(self, name, parent=None):
netbox.dcim.regions.create()
if not parent:
pass
pass
def create_site(self, name, region, status, physical_address, facility, shipping_address, contact_phone, contact_email, contact_name, tenant, time_zone):
slug = self.slugify(name)
pass
# Re-Enabled SSL verification
# urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class REST(object):
def __init__(self):
self.base_url = "{}/api".format(config['NetBox']['NETBOX_HOST'])
# Create HTTP connection pool
self.s = requests.Session()
# SSL verification
self.s.verify = True
# Define REST Headers
headers = {'Content-Type': 'application/json',
'Accept': 'application/json; indent=4',
'Authorization': 'Token {0}'.format(config['NetBox']['NETBOX_TOKEN'])}
self.s.headers.update(headers)
def uploader(self, data, url):
method = 'POST'
logger.debug("HTTP Request: {} - {} - {}".format(method, url, data))
request = requests.Request(method, url, data = json.dumps(data))
prepared_request = self.s.prepare_request(request)
r = self.s.send(prepared_request)
logger.debug(f"HTTP Response: {r.status_code!s} - {r.reason}")
r.raise_for_status()
return r.json()
def fetcher(self, url):
method = 'GET'
logger.debug("HTTP Request: {} - {}".format(method, url))
request = requests.Request(method, url)
prepared_request = self.s.prepare_request(request)
r = self.s.send(prepared_request)
logger.debug(f'HTTP Response: {r.status_code} - {r.reason}')
r.raise_for_status()
return r.text
def post_subnet(self, data):
url = self.base_url + '/ipam/prefixes/'
logger.info('Posting data to {}'.format(url))
self.uploader(data, url)
def post_ip(self, data):
url = self.base_url + '/ipam/ip-addresses/'
logger.info('Posting IP data to {}'.format(url))
self.uploader(data, url)
# def post_device(self, data):
# url = self.base_url + '/api/1.0/device/'
# logger.info('Posting device data to {}'.format(url))
# self.uploader(data, url)
# def post_location(self, data):
# url = self.base_url + '/api/1.0/location/'
# logger.info('Posting location data to {}'.format(url))
# self.uploader(data, url)
# def post_room(self, data):
# url = self.base_url + '/api/1.0/rooms/'
# logger.info('Posting room data to {}'.format(url))
# self.uploader(data, url)
# def post_rack(self, data):
# url = self.base_url + '/api/1.0/racks/'
# logger.info('Posting rack data to {}'.format(url))
# response = self.uploader(data, url)
# return response
# def post_pdu(self, data):
# url = self.base_url + '/api/1.0/pdus/'
# logger.info('Posting PDU data to {}'.format(url))
# response = self.uploader(data, url)
# return response
# def post_pdu_model(self, data):
# url = self.base_url + '/api/1.0/pdu_models/'
# logger.info('Posting PDU model to {}'.format(url))
# response = self.uploader(data, url)
# return response
# def post_pdu_to_rack(self, data, rack):
# url = self.base_url + '/api/1.0/pdus/rack/'
# logger.info('Posting PDU to rack {}'.format(rack))
# self.uploader(data, url)
# def post_hardware(self, data):
# url = self.base_url + '/api/1.0/hardwares/'
# logger.info('Adding hardware data to {}'.format(url))
# self.uploader(data, url)
# def post_device2rack(self, data):
# url = self.base_url + '/api/1.0/device/rack/'
# logger.info('Adding device to rack at {}'.format(url))
# self.uploader(data, url)
def post_building(self, data):
url = self.base_url + '/dcim/sites/'
logger.info('Uploading building data to {}'.format(url))
self.uploader(data, url)
# def post_switchport(self, data):
# url = self.base_url + '/api/1.0/switchports/'
# logger.info('Uploading switchports data to {}'.format(url))
# self.uploader(data, url)
# def post_patch_panel(self, data):
# url = self.base_url + '/api/1.0/patch_panel_models/'
# logger.info('Uploading patch panels data to {}'.format(url))
# self.uploader(data, url)
# def post_patch_panel_module_models(self, data):
# url = self.base_url + '/api/1.0/patch_panel_module_models/'
# logger.info('Uploading patch panels modules data to {}}'.format(url))
# self.uploader(data, url)
# def get_pdu_models(self):
# url = self.base_url + '/api/1.0/pdu_models/'
# logger.info('Fetching PDU models from {}'.format(url))
# self.fetcher(url)
# def get_racks(self):
# url = self.base_url + '/api/1.0/racks/'
# logger.info('Fetching racks from {}'.format(url))
# ata = self.fetcher(url)
# return data
# def get_devices(self):
# url = self.base_url + '/api/1.0/devices/'
# logger.info('Fetching devices from {}'.format(url))
# data = self.fetcher(url)
# return data
# def get_buildings(self):
# url = self.base_url + '/api/dcim/sites/'
# logger.info('Fetching buildings from {}'.format(url))
# data = self.fetcher(url)
# return data
# def get_rooms(self):
# url = self.base_url + '/api/1.0/rooms/'
# logger.info('Fetching rooms from {}'.format(url))
# data = self.fetcher(url)
# return data
class DB(object):
"""
Fetching data from Racktables and converting them to Device42 API format.
"""
def __init__(self):
self.con = None
self.tables = []
self.rack_map = []
self.vm_hosts = {}
self.chassis = {}
self.rack_id_map = {}
self.container_map = {}
self.building_room_map = {}
def connect(self):
"""
Connection to RT database
:return:
"""
self.con = pymysql.connect(
host=config['MySQL']['DB_IP'],
port=int(config['MySQL']['DB_PORT']),
db=config['MySQL']['DB_NAME'],
user=config['MySQL']['DB_USER'],
passwd=config['MySQL']['DB_PWD']
)
@staticmethod
def convert_ip(ip_raw):
"""
IP address conversion to human readable format
:param ip_raw:
:return:
"""
ip = socket.inet_ntoa(struct.pack('!I', ip_raw))
return ip
def get_ips(self):
"""
Fetch IPs from RT and send them to upload function
:return:
"""
adrese = []
if not self.con:
self.connect()
with self.con:
cur = self.con.cursor()
q = 'SELECT * FROM IPv4Address WHERE IPv4Address.name != "" or IPv4Address.comment != ""'
cur.execute(q)
ips = cur.fetchall()
if config['Log']['DEBUG']:
msg = ('IPs', str(ips))
logger.debug(msg)
for line in ips:
net = {}
ip_raw, name, comment, reserved = line
ip = self.convert_ip(ip_raw)
adrese.append(ip)
net.update({'address': ip})
msg = 'IP Address: %s' % ip
logger.info(msg)
desc = ' '.join([name, comment]).strip()
net.update({'description': desc})
msg = 'Label: %s' % desc
logger.info(msg)
rest.post_ip(net)
logger.info('Post ip {ip}')
def get_subnets(self):
"""
Fetch subnets from RT and send them to upload function
:return:
"""
subs = {}
if not self.con:
self.connect()
with self.con:
cur = self.con.cursor()
q = "SELECT * FROM IPv4Network"
cur.execute(q)
subnets = cur.fetchall()
if config['Log']['DEBUG']:
msg = ('Subnets', str(subnets))
logger.debug(msg)
for line in subnets:
sid, raw_sub, mask, name, x = line
subnet = self.convert_ip(raw_sub)
subs.update({'prefix':'/'.join([subnet, str(mask)])})
subs.update({'status':'active'})
#subs.update({'mask_bits': str(mask)})
subs.update({'description':name})
rest.post_subnet(subs)
def get_infrastructure(self):
"""
Get locations, rows and racks from RT, convert them to buildings and rooms and send to uploader.
:return:
"""
sites_map = {}
rooms_map = {}
rows_map = {}
rackgroups = []
racks = []
if not self.con:
self.connect()
# ============ BUILDINGS AND ROOMS ============
with self.con:
cur = self.con.cursor()
q = """SELECT id, name, parent_id, parent_name FROM Location"""
cur.execute(q)
raw = cur.fetchall()
for rec in raw:
location_id, location_name, parent_id, parent_name = rec
if not parent_name:
sites_map.update({location_id: location_name})
else:
rooms_map.update({location_name: parent_name})
print("Sites:")
pp.pprint(sites_map)
pp.pprint(rooms_map)
print("Rack Groups:")
for room, parent in list(rooms_map.items()):
if parent in sites_map.values():
if room in rooms_map.values():
continue
rackgroup = {}
if room not in sites_map.values():
name = parent + "-" + room
rackgroup.update({'site': rooms_map[parent]})
else:
name = room
rackgroup.update({'site': parent})
rackgroup.update({'name': name})
rackgroups.append(rackgroup)
for site_id, site_name in list(sites_map.items()):
if site_name not in rooms_map.values():
rackgroup = {}
rackgroup.update({'site': site_name})
rackgroup.update({'name': site_name})
rackgroups.append(rackgroup)
pp.pprint(rackgroups)
# upload rooms
# buildings = json.loads((rest.get_buildings()))['buildings']
# for room, parent in list(rooms_map.items()):
# roomdata = {}
# roomdata.update({'name': room})
# roomdata.update({'building': parent})
# rest.post_room(roomdata)
# # ============ ROWS AND RACKS ============
# with self.con:
# cur = self.con.cursor()
# q = """SELECT id, name ,height, row_id, row_name, location_id, location_name from Rack;"""
# cur.execute(q)
# raw = cur.fetchall()
# for rec in raw:
# rack_id, rack_name, height, row_id, row_name, location_id, location_name = rec
# rows_map.update({row_name: location_name})
# # prepare rack data. We will upload it a little bit later
# rack = {}
# rack.update({'name': rack_name})
# rack.update({'size': height})
# rack.update({'rt_id': rack_id}) # we will remove this later
# if config['Misc']['ROW_AS_ROOM']:
# rack.update({'room': row_name})
# rack.update({'building': location_name})
# else:
# row_name = row_name[:10] # there is a 10char limit for row name
# rack.update({'row': row_name})
# if location_name in rooms_map:
# rack.update({'room': location_name})
# building_name = rooms_map[location_name]
# rack.update({'building': building_name})
# else:
# rack.update({'building': location_name})
# racks.append(rack)
# # upload rows as rooms
# if config['Misc']['ROW_AS_ROOM']:
# if config['Log']['DEBUG']:
# msg = ('Rooms', str(rows_map))
# logger.debug(msg)
# for room, parent in list(rows_map.items()):
# roomdata = {}
# roomdata.update({'name': room})
# roomdata.update({'building': parent})
# rest.post_room(roomdata)
# # upload racks
# if config['Log']['DEBUG']:
# msg = ('Racks', str(racks))
# logger.debug(msg)
# for rack in racks:
# rt_rack_id = rack['rt_id']
# del rack['rt_id']
# response = rest.post_rack(rack)
# d42_rack_id = response['msg'][1]
# self.rack_id_map.update({rt_rack_id: d42_rack_id})
# self.all_ports = self.get_ports()
def get_hardware(self):
"""
Get hardware from RT and send it to uploader
:return:
"""
if not self.con:
self.connect()
with self.con:
# get hardware items (except PDU's)
cur = self.con.cursor()
q = """SELECT
Object.id,Object.name as Description, Object.label as Name,
Object.asset_no as Asset,Dictionary.dict_value as Type
FROM Object
LEFT JOIN AttributeValue ON Object.id = AttributeValue.object_id
LEFT JOIN Attribute ON AttributeValue.attr_id = Attribute.id
LEFT JOIN Dictionary ON Dictionary.dict_key = AttributeValue.uint_value
WHERE Attribute.id=2 AND Object.objtype_id != 2
"""
cur.execute(q)
data = cur.fetchall()
if config['Log']['DEBUG']:
msg = ('Hardware', str(data))
logger.debug(msg)
# create map device_id:height
# RT does not impose height for devices of the same hardware model so it might happen that -
# two or more devices based on same HW model have different size in rack
# here we try to find and set smallest U for device
hwsize_map = {}
for line in data:
line = [0 if not x else x for x in line]
data_id, description, name, asset, dtype = line
size = self.get_hardware_size(data_id)
if size:
floor, height, depth, mount = size
if data_id not in hwsize_map:
hwsize_map.update({data_id: height})
else:
h = float(hwsize_map[data_id])
if float(height) < h:
hwsize_map.update({data_id: height})
for line in data:
hwddata = {}
line = [0 if not x else x for x in line]
data_id, description, name, asset, dtype = line
if '%GPASS%' in dtype:
vendor, model = dtype.split("%GPASS%")
elif len(dtype.split()) > 1:
venmod = dtype.split()
vendor = venmod[0]
model = ' '.join(venmod[1:])
else:
vendor = dtype
model = dtype
size = self.get_hardware_size(data_id)
if size:
floor, height, depth, mount = size
# patching height
height = hwsize_map[data_id]
hwddata.update({'notes': description})
hwddata.update({'type': 1})
hwddata.update({'size': height})
hwddata.update({'depth': depth})
hwddata.update({'name': model[:48]})
hwddata.update({'manufacturer': vendor})
# rest.post_hardware(hwddata)
def get_hardware_size(self, data_id):
"""
Calculate hardware size.
:param data_id: hw id
:return:
floor - starting U location for the device in the rack
height - height of the device
depth - depth of the device (full, half)
mount - orientation of the device in the rack. Can be front or back
"""
if not self.con:
self.connect()
with self.con:
# get hardware items
cur = self.con.cursor()
q = """SELECT unit_no,atom FROM RackSpace WHERE object_id = %s""" % data_id
cur.execute(q)
data = cur.fetchall()
if data != ():
front = 0
interior = 0
rear = 0
floor = 0
depth = 1 # 1 for full depth (default) and 2 for half depth
mount = 'front' # can be [front | rear]
i = 1
for line in data:
flr, tag = line
if i == 1:
floor = int(flr) - 1 # '-1' since RT rack starts at 1 and Device42 starts at 0.
else:
if int(flr) < floor:
floor = int(flr) - 1
i += 1
if tag == 'front':
front += 1
elif tag == 'interior':
interior += 1
elif tag == 'rear':
rear += 1
if front and interior and rear: # full depth
height = front
return floor, height, depth, mount
elif front and interior and not rear: # half depth, front mounted
height = front
depth = 2
return floor, height, depth, mount
elif interior and rear and not front: # half depth, rear mounted
height = rear
depth = 2
mount = 'rear'
return floor, height, depth, mount
# for devices that look like less than half depth:
elif front and not interior and not rear:
height = front
depth = 2
return floor, height, depth, mount
elif rear and not interior and not front:
height = rear
depth = 2
return floor, height, depth, mount
else:
return None, None, None, None
else:
return None, None, None, None
@staticmethod
def add_hardware(height, depth, name):
"""
:rtype : object
"""
hwddata = {}
hwddata.update({'type': 1})
if height:
hwddata.update({'size': height})
if depth:
hwddata.update({'depth': depth})
if name:
hwddata.update({'name': name[:48]})
# rest.post_hardware(hwddata)
def get_vmhosts(self):
if not self.con:
self.connect()
with self.con:
cur = self.con.cursor()
q = """SELECT id, name FROM Object WHERE objtype_id='1505'"""
cur.execute(q)
raw = cur.fetchall()
dev = {}
for rec in raw:
host_id = int(rec[0])
try:
name = rec[1].strip()
except AttributeError:
continue
self.vm_hosts.update({host_id: name})
dev.update({'name': name})
dev.update({'is_it_virtual_host': 'yes'})
# rest.post_device(dev)
def get_chassis(self):
if not self.con:
self.connect()
with self.con:
cur = self.con.cursor()
q = """SELECT id, name FROM Object WHERE objtype_id='1502'"""
cur.execute(q)
raw = cur.fetchall()
dev = {}
for rec in raw:
host_id = int(rec[0])
try:
name = rec[1].strip()
except AttributeError:
continue
self.chassis.update({host_id: name})
dev.update({'name': name})
dev.update({'is_it_blade_host': 'yes'})
# rest.post_device(dev)
def get_container_map(self):
"""
Which VM goes into which VM host?
Which Blade goes into which Chassis ?
:return:
"""
if not self.con:
self.connect()
with self.con:
cur = self.con.cursor()
q = """SELECT parent_entity_id AS container_id, child_entity_id AS object_id
FROM EntityLink WHERE child_entity_type='object' AND parent_entity_type = 'object'"""
cur.execute(q)
raw = cur.fetchall()
for rec in raw:
container_id, object_id = rec
self.container_map.update({object_id: container_id})
def get_devices(self):
if not self.con:
self.connect()
with self.con:
cur = self.con.cursor()
# get object IDs
q = 'SELECT id FROM Object'
cur.execute(q)
idsx = cur.fetchall()
ids = [x[0] for x in idsx]
with self.con:
for dev_id in ids:
q = """Select
Object.objtype_id,
Object.name as Description,
Object.label as Name,
Object.asset_no as Asset,
Attribute.name as Name,
Dictionary.dict_value as Type,
Object.comment as Comment,
RackSpace.rack_id as RackID,
Rack.name as rack_name,
Rack.row_name,
Rack.location_id,
Rack.location_name,
Location.parent_name
FROM Object
LEFT JOIN AttributeValue ON Object.id = AttributeValue.object_id
LEFT JOIN Attribute ON AttributeValue.attr_id = Attribute.id
LEFT JOIN RackSpace ON Object.id = RackSpace.object_id
LEFT JOIN Dictionary ON Dictionary.dict_key = AttributeValue.uint_value
LEFT JOIN Rack ON RackSpace.rack_id = Rack.id
LEFT JOIN Location ON Rack.location_id = Location.id
WHERE Object.id = %s
AND Object.objtype_id not in (2,9,1505,1560,1561,1562,50275)""" % dev_id
cur.execute(q)
data = cur.fetchall()
if data: # RT objects that do not have data are locations, racks, rows etc...
self.process_data(data, dev_id)
def process_data(self, data, dev_id):
devicedata = {}
device2rack = {}
name = None
opsys = None
hardware = None
note = None
rrack_id = None
floor = None
dev_type = 0
for x in data:
dev_type, rdesc, rname, rasset, rattr_name, rtype, \
rcomment, rrack_id, rrack_name, rrow_name, \
rlocation_id, rlocation_name, rparent_name = x
name = x[1]
note = x[-7]
if 'Operating System' in x:
opsys = x[-8]
if '%GSKIP%' in opsys:
opsys = opsys.replace('%GSKIP%', ' ')
if '%GPASS%' in opsys:
opsys = opsys.replace('%GPASS%', ' ')
if 'SW type' in x:
opsys = x[-8]
if '%GSKIP%' in opsys:
opsys = opsys.replace('%GSKIP%', ' ')
if '%GPASS%' in opsys:
opsys = opsys.replace('%GPASS%', ' ')
if 'Server Hardware' in x:
hardware = x[-8]
if '%GSKIP%' in hardware:
hardware = hardware.replace('%GSKIP%', ' ')
if '%GPASS%' in hardware:
hardware = hardware.replace('%GPASS%', ' ')
if '\t' in hardware:
hardware = hardware.replace('\t', ' ')
if 'HW type' in x:
hardware = x[-8]
if '%GSKIP%' in hardware:
hardware = hardware.replace('%GSKIP%', ' ')
if '%GPASS%' in hardware:
hardware = hardware.replace('%GPASS%', ' ')
if '\t' in hardware:
hardware = hardware.replace('\t', ' ')
if note:
note = note.replace('\n', ' ')
if '<' in note:
note = note.replace('<', '')
if '>' in note:
note = note.replace('>', '')
if name:
# set device data
devicedata.update({'name': name})
if hardware:
devicedata.update({'hardware': hardware[:48]})
if opsys:
devicedata.update({'os': opsys})
if note:
devicedata.update({'notes': note})
if dev_id in self.vm_hosts:
devicedata.update({'is_it_virtual_host': 'yes'})
if dev_type == 8:
devicedata.update({'is_it_switch': 'yes'})
elif dev_type == 1502:
devicedata.update({'is_it_blade_host': 'yes'})
elif dev_type == 4:
try:
blade_host_id = self.container_map[dev_id]
blade_host_name = self.chassis[blade_host_id]
devicedata.update({'type': 'blade'})
devicedata.update({'blade_host': blade_host_name})
except KeyError:
pass
elif dev_type == 1504:
devicedata.update({'type': 'virtual'})
devicedata.pop('hardware', None)
try:
vm_host_id = self.container_map[dev_id]
vm_host_name = self.vm_hosts[vm_host_id]
devicedata.update({'virtual_host': vm_host_name})
except KeyError:
pass
d42_rack_id = None
# except VMs
if dev_type != 1504:
if rrack_id:
d42_rack_id = self.rack_id_map[rrack_id]
# if the device is mounted in RT, we will try to add it to D42 hardwares.
floor, height, depth, mount = self.get_hardware_size(dev_id)
if floor is not None:
floor = int(floor) + 1
else:
floor = 'auto'
if not hardware:
hardware = 'generic' + str(height) + 'U'
self.add_hardware(height, depth, hardware)
# upload device
if devicedata:
if hardware and dev_type != 1504:
devicedata.update({'hardware': hardware[:48]})
# set default type for racked devices
if 'type' not in devicedata and d42_rack_id and floor:
devicedata.update({'type': 'physical'})
rest.post_device(devicedata)
# update ports
if dev_type == 8 or dev_type == 4 or dev_type == 445 or dev_type == 1055:
ports = self.get_ports_by_device(self.all_ports, dev_id)
if ports:
for item in ports:
switchport_data = {
'port': item[0],
'switch': name,
'label': item[1]
}
get_links = self.get_links(item[3])
if get_links:
device_name = self.get_device_by_port(get_links[0])
switchport_data.update({'device': device_name})
switchport_data.update({'remote_device': device_name})
# switchport_data.update({'remote_port': self.get_port_by_id(self.all_ports, get_links[0])})
rest.post_switchport(switchport_data)
# reverse connection
device_name = self.get_device_by_port(get_links[0])
switchport_data = {
'port': self.get_port_by_id(self.all_ports, get_links[0]),
'switch': device_name
}
switchport_data.update({'device': name})
switchport_data.update({'remote_device': name})
switchport_data.update({'remote_port': item[0]})
rest.post_switchport(switchport_data)
else:
rest.post_switchport(switchport_data)
# if there is a device, we can try to mount it to the rack
if dev_type != 1504 and d42_rack_id and floor: # rack_id is D42 rack id
device2rack.update({'device': name})
if hardware:
device2rack.update({'hw_model': hardware[:48]})
device2rack.update({'rack_id': d42_rack_id})
device2rack.update({'start_at': floor})
rest.post_device2rack(device2rack)
else:
if dev_type != 1504 and d42_rack_id is not None:
msg = '\n-----------------------------------------------------------------------\
\n[!] INFO: Cannot mount device "%s" (RT id = %d) to the rack.\
\n\tFloor returned from "get_hardware_size" function was: %s' % (name, dev_id, str(floor))
logger.info(msg)
else:
msg = '\n-----------------------------------------------------------------------\
\n[!] INFO: Device %s (RT id = %d) cannot be uploaded. Data was: %s' % (name, dev_id, str(devicedata))
logger.info(msg)
else:
# device has no name thus it cannot be migrated
msg = '\n-----------------------------------------------------------------------\
\n[!] INFO: Device with RT id=%d cannot be migrated because it has no name.' % dev_id
logger.info(msg)
def get_device_to_ip(self):
if not self.con:
self.connect()
with self.con:
# get hardware items (except PDU's)
cur = self.con.cursor()
q = """SELECT
IPv4Allocation.ip,IPv4Allocation.name,
Object.name as hostname
FROM %s.`IPv4Allocation`
LEFT JOIN Object ON Object.id = object_id""" % config['MySQL']['DB_NAME']
cur.execute(q)
data = cur.fetchall()
if config['Log']['DEBUG']:
msg = ('Device to IP', str(data))
logger.debug(msg)
for line in data:
devmap = {}
rawip, nic_name, hostname = line
ip = self.convert_ip(rawip)
devmap.update({'ipaddress': ip})
devmap.update({'device': hostname})
if nic_name:
devmap.update({'tag': nic_name})
rest.post_ip(devmap)
def get_pdus(self):
if not self.con:
self.connect()
with self.con:
cur = self.con.cursor()
q = """SELECT
Object.id,Object.name as Name, Object.asset_no as Asset,
Object.comment as Comment, Dictionary.dict_value as Type, RackSpace.atom as Position,
(SELECT Object.id FROM Object WHERE Object.id = RackSpace.rack_id) as RackID
FROM Object
LEFT JOIN AttributeValue ON Object.id = AttributeValue.object_id
LEFT JOIN Attribute ON AttributeValue.attr_id = Attribute.id
LEFT JOIN Dictionary ON Dictionary.dict_key = AttributeValue.uint_value
LEFT JOIN RackSpace ON RackSpace.object_id = Object.id
WHERE Object.objtype_id = 2
"""
cur.execute(q)
data = cur.fetchall()
if config['Log']['DEBUG']:
msg = ('PDUs', str(data))
logger.debug(msg)
rack_mounted = []
pdumap = {}
pdumodels = []
pdu_rack_models = []
for line in data:
pdumodel = {}
pdudata = {}
line = ['' if x is None else x for x in line]
pdu_id, name, asset, comment, pdu_type, position, rack_id = line
if '%GPASS%' in pdu_type:
pdu_type = pdu_type.replace('%GPASS%', ' ')
pdu_type = pdu_type[:64]
pdudata.update({'name': name})
pdudata.update({'notes': comment})
pdudata.update({'pdu_model': pdu_type})
pdumodel.update({'name': pdu_type})
pdumodel.update({'pdu_model': pdu_type})
if rack_id:
floor, height, depth, mount = self.get_hardware_size(pdu_id)
pdumodel.update({'size': height})
pdumodel.update({'depth': depth})
# post pdu models
if pdu_type and name not in pdumodels:
rest.post_pdu_model(pdumodel)
pdumodels.append(pdumodel)
elif pdu_type and rack_id:
if pdu_id not in pdu_rack_models:
rest.post_pdu_model(pdumodel)
pdu_rack_models.append(pdu_id)
# post pdus
if pdu_id not in pdumap:
response = rest.post_pdu(pdudata)
d42_pdu_id = response['msg'][1]
pdumap.update({pdu_id: d42_pdu_id})
# mount to rack
if position:
if pdu_id not in rack_mounted:
rack_mounted.append(pdu_id)
floor, height, depth, mount = self.get_hardware_size(pdu_id)
if floor is not None:
floor = int(floor) + 1
else:
floor = 'auto'
try:
d42_rack_id = self.rack_id_map[rack_id]
if floor:
rdata = {}
rdata.update({'pdu_id': pdumap[pdu_id]})
rdata.update({'rack_id': d42_rack_id})
rdata.update({'pdu_model': pdu_type})
rdata.update({'where': 'mounted'})
rdata.update({'start_at': floor})
rdata.update({'orientation': mount})
rest.post_pdu_to_rack(rdata, d42_rack_id)
except TypeError:
msg = '\n-----------------------------------------------------------------------\
\n[!] INFO: Cannot mount pdu "%s" (RT id = %d) to the rack.\
\n\tFloor returned from "get_hardware_size" function was: %s' % (name, pdu_id, str(floor))
logger.info(msg)
except KeyError:
msg = '\n-----------------------------------------------------------------------\
\n[!] INFO: Cannot mount pdu "%s" (RT id = %d) to the rack.\
\n\tWrong rack id map value: %s' % (name, pdu_id, str(rack_id))
logger.info(msg)
# It's Zero-U then
else:
rack_id = self.get_rack_id_for_zero_us(pdu_id)
if rack_id:
try:
d42_rack_id = self.rack_id_map[rack_id]
except KeyError:
msg = '\n-----------------------------------------------------------------------\
\n[!] INFO: Cannot mount pdu "%s" (RT id = %d) to the rack.\