-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathconnection.py
More file actions
2617 lines (2002 loc) · 102 KB
/
connection.py
File metadata and controls
2617 lines (2002 loc) · 102 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
# -*- coding: utf-8 -*-
# Copyright (c) 2020 - 2025 Ricardo Bartels. All rights reserved.
#
# netbox-sync.py
#
# This work is licensed under the terms of the MIT license.
# For a copy, see file LICENSE.txt included in this
# repository or visit: <https://opensource.org/licenses/MIT>.
import datetime
import pprint
import ssl
from ipaddress import ip_address, ip_interface
from urllib.parse import unquote
from itertools import zip_longest
import urllib3
import requests
import http
# noinspection PyUnresolvedReferences
from packaging import version
# noinspection PyUnresolvedReferences
from pyVim import connect
# noinspection PyUnresolvedReferences
from pyVmomi import vim
# noinspection PyUnresolvedReferences
from pyVmomi.VmomiSupport import VmomiJSONEncoder
from module.sources.common.source_base import SourceBase
from module.sources.vmware.config import VMWareConfig
from module.common.logging import get_logger, DEBUG3
from module.common.misc import grab, dump, get_string_or_none, plural, quoted_split
from module.common.support import normalize_mac_address
from module.netbox.inventory import NetBoxInventory
from module.netbox import *
vsphere_automation_sdk_available = True
try:
# noinspection PyUnresolvedReferences
from com.vmware.vapi.std_client import DynamicID
# noinspection PyUnresolvedReferences
from vmware.vapi.vsphere.client import create_vsphere_client
except ImportError:
vsphere_automation_sdk_available = False
log = get_logger()
# noinspection PyTypeChecker
class VMWareHandler(SourceBase):
"""
Source class to import data from a vCenter instance and add/update NetBox objects based on gathered information
"""
dependent_netbox_objects = [
NBTag,
NBManufacturer,
NBDeviceType,
NBPlatform,
NBClusterType,
NBClusterGroup,
NBDeviceRole,
NBSite,
NBSiteGroup,
NBCluster,
NBDevice,
NBVM,
NBVMInterface,
NBInterface,
NBIPAddress,
NBPrefix,
NBTenant,
NBVRF,
NBVLAN,
NBVLANGroup,
NBCustomField,
NBVirtualDisk,
NBMACAddress
]
source_type = "vmware"
recursion_level = 0
# internal vars
session = None
tag_session = None
site_name = None
def __init__(self, name=None):
if name is None:
raise ValueError(f"Invalid value for attribute 'name': '{name}'.")
self.inventory = NetBoxInventory()
self.name = name
# parse settings
settings_handler = VMWareConfig()
settings_handler.source_name = self.name
self.settings = settings_handler.parse()
self.set_source_tag()
self.site_name = f"vCenter: {name}"
if self.settings.enabled is False:
log.info(f"Source '{name}' is currently disabled. Skipping")
return
self._sdk_instance = None
self.create_sdk_session()
if self.session is None:
log.info(f"Source '{name}' is currently unavailable. Skipping")
return
self.create_api_session()
self.init_successful = True
# instantiate source specific vars
self.network_data = {
"vswitch": dict(),
"pswitch": dict(),
"host_pgroup": dict(),
"dpgroup": dict(),
"dpgroup_ports": dict()
}
self.processed_host_names = dict()
self.processed_vm_names = dict()
self.processed_vm_uuid = list()
self.object_cache = dict()
self.parsing_vms_the_first_time = True
self.objects_to_reevaluate = list()
self.parsing_objects_to_reevaluate = False
def create_sdk_session(self):
"""
Initialize SDK session with vCenter
Returns
-------
bool: if initialization was successful or not
"""
if self.session is not None:
return True
log.debug(f"Starting vCenter SDK connection to '{self.settings.host_fqdn}'")
ssl_context = ssl.create_default_context()
if self.settings.validate_tls_certs is False:
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
connection_params = dict(
host=self.settings.host_fqdn,
port=self.settings.port,
sslContext=ssl_context
)
# uses connect.SmartStubAdapter
if self.settings.proxy_host is not None and self.settings.proxy_port is not None:
connection_params.update(
httpProxyHost=self.settings.proxy_host,
httpProxyPort=self.settings.proxy_port,
)
# uses connect.SmartConnect
else:
connection_params.update(
user=self.settings.username,
pwd=self.settings.password,
)
def_exception_text = f"Unable to connect to vCenter instance " \
f"'{self.settings.host_fqdn}' on port {self.settings.port}."
try:
if self.settings.proxy_host is not None and self.settings.proxy_port is not None:
smart_stub = connect.SmartStubAdapter(**connection_params)
self._sdk_instance = vim.ServiceInstance('ServiceInstance', smart_stub)
content = self._sdk_instance.RetrieveContent()
content.sessionManager.Login(self.settings.username, self.settings.password, None)
else:
self._sdk_instance = connect.SmartConnect(**connection_params)
self.session = self._sdk_instance.RetrieveContent()
except vim.fault.InvalidLogin as e:
log.error(f"{def_exception_text} {e.msg}")
return False
except vim.fault.NoPermission as e:
log.error(f"{def_exception_text} User {self.settings.username} does not have required permission. {e.msg}")
return False
except Exception as e:
log.error(f"{def_exception_text} Reason: {e}")
return False
log.info(f"Successfully connected to vCenter SDK '{self.settings.host_fqdn}'")
return True
def create_api_session(self):
"""
Initialize API session with vCenter
Returns
-------
bool: if initialization was successful or not
"""
if self.tag_session is not None:
return True
source_tag_settings_list = [
self.settings.cluster_tag_source,
self.settings.host_tag_source,
self.settings.vm_tag_source
]
# check if vm tag syncing is configured
if source_tag_settings_list.count(None) == len(source_tag_settings_list):
return False
if vsphere_automation_sdk_available is False:
log.warning(f"Unable to import Python 'vsphere-automation-sdk'. Tag syncing will be disabled.")
return False
log.debug(f"Starting vCenter API connection to '{self.settings.host_fqdn}'")
# create a requests session to enable/disable TLS verification
session = requests.session()
session.verify = self.settings.validate_tls_certs
# disable TLS insecure warnings if user explicitly switched off validation
if self.settings.validate_tls_certs is False:
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# adds proxy to the session
if self.settings.proxy_host is not None and self.settings.proxy_port is not None:
session.proxies.update({
"http": f"http://{self.settings.proxy_host}:{self.settings.proxy_port}",
"https": f"http://{self.settings.proxy_host}:{self.settings.proxy_port}",
})
try:
self.tag_session = create_vsphere_client(
server=f"{self.settings.host_fqdn}:{self.settings.port}",
username=self.settings.username,
password=self.settings.password,
session=session)
except Exception as e:
log.warning(f"Unable to connect to vCenter API instance "
f"'{self.settings.host_fqdn}' on port {self.settings.port}: {e}")
log.warning("Tag syncing will be disabled.")
return False
log.info(f"Successfully connected to vCenter API '{self.settings.host_fqdn}'")
return True
def finish(self):
# closing tag session
if self._sdk_instance is not None:
try:
connect.Disconnect(self._sdk_instance)
except Exception as e:
log.error(f"unable to close vCenter SDK connection: {e}")
# closing SDK session
if self.tag_session is not None:
try:
del self.tag_session
except Exception as e:
log.error(f"unable to close vCenter API instance connection: {e}")
def apply(self):
"""
Main source handler method. This method is called for each source from "main" program
to retrieve data from it source and apply it to the NetBox inventory.
Every update of new/existing objects fot this source has to happen here.
"""
log.info(f"Query data from vCenter: '{self.settings.host_fqdn}'")
"""
Mapping of object type keywords to view types and handlers
iterate over all VMs twice.
To handle VMs with the same name in a cluster we first
iterate over all VMs and look only at the active ones
and sync these first.
Then we iterate a second time to catch the rest.
This has been implemented to support migration scenarios
where you create the same machines with a different setup
like a new version or something. This way NetBox will be
updated primarily with the actual active VM data.
# disabled, no useful information at this moment
"virtual switch": {
"view_type": vim.DistributedVirtualSwitch,
"view_handler": self.add_virtual_switch
},
"""
object_mapping = {
"datacenter": {
"view_type": vim.Datacenter,
"view_handler": self.add_datacenter
},
"cluster": {
"view_type": vim.ClusterComputeResource,
"view_handler": self.add_cluster
},
"single host cluster": {
"view_type": vim.ComputeResource,
"view_handler": self.add_cluster
},
"network": {
"view_type": vim.dvs.DistributedVirtualPortgroup,
"view_handler": self.add_port_group
},
"host": {
"view_type": vim.HostSystem,
"view_handler": self.add_host
},
"virtual machine": {
"view_type": vim.VirtualMachine,
"view_handler": self.add_virtual_machine
},
"offline virtual machine": {
"view_type": vim.VirtualMachine,
"view_handler": self.add_virtual_machine
}
}
# skip virtual machines which are reported offline
if self.settings.skip_offline_vms is True:
log.info("Skipping offline VMs")
del object_mapping["offline virtual machine"]
for view_name, view_details in object_mapping.items():
# test if session is still alive
try:
self.session.sessionManager.currentSession.key
except (vim.fault.NotAuthenticated, AttributeError, http.client.RemoteDisconnected):
log.info("No existing vCenter session found.")
self.session = None
self.tag_session = None
self.create_sdk_session()
self.create_api_session()
if self.session is None:
log.error("Recreating session failed")
break
view_data = {
"container": self.session.rootFolder,
"type": [view_details.get("view_type")],
"recursive": True
}
try:
container_view = self.session.viewManager.CreateContainerView(**view_data)
except Exception as e:
log.error(f"Problem creating vCenter view for '{view_name}s': {e}")
continue
view_objects = grab(container_view, "view")
if view_objects is None:
log.error(f"Creating vCenter view for '{view_name}s' failed!")
continue
if view_name != "offline virtual machine":
log.debug("vCenter returned '%d' %s%s" % (len(view_objects), view_name, plural(len(view_objects))))
else:
self.parsing_vms_the_first_time = False
log.debug("Iterating over all virtual machines a second time ")
for obj in view_objects:
if log.level == DEBUG3:
try:
dump(obj)
except Exception as e:
log.error(e)
# noinspection PyArgumentList
view_details.get("view_handler")(obj)
container_view.Destroy()
self.parsing_objects_to_reevaluate = True
log.info("Parsing objects which were marked to be reevaluated")
for obj in self.objects_to_reevaluate:
if isinstance(obj, vim.HostSystem):
self.add_host(obj)
elif isinstance(obj, vim.VirtualMachine):
self.add_virtual_machine(obj)
else:
log.error(f"Unable to handle reevaluation of {obj} (type: {type(obj)})")
self.update_basic_data()
@staticmethod
def passes_filter(name, include_filter, exclude_filter):
"""
checks if object name passes a defined object filter.
Parameters
----------
name: str
name of the object to check
include_filter: regex object
A regex object of include filter
exclude_filter: regex object
A regex object of exclude filter
Returns
-------
bool: True if all filter passed, otherwise False
"""
# first includes
if include_filter is not None and not include_filter.match(name):
log.debug(f"Object '{name}' did not match include filter '{include_filter.pattern}'. Skipping")
return False
# second excludes
if exclude_filter is not None and exclude_filter.match(name):
log.debug(f"Object '{name}' matched exclude filter '{exclude_filter.pattern}'. Skipping")
return False
return True
def get_site_name(self, object_type, object_name, cluster_name=""):
"""
Return a site name for a NBCluster or NBDevice depending on config options
host_site_relation and cluster_site_relation
Parameters
----------
object_type: (NBCluster, NBDevice)
object type to check site relation for
object_name: str
object name to check site relation for
cluster_name: str
cluster name of NBDevice to check for site name
Returns
-------
str: site name if a relation was found
"""
if object_type not in [NBCluster, NBDevice]:
raise ValueError(f"Object must be a '{NBCluster.name}' or '{NBDevice.name}'.")
log.debug2(f"Trying to find site name for {object_type.name} '{object_name}'")
# check if site was provided in config
relation_name = "host_site_relation" if object_type == NBDevice else "cluster_site_relation"
site_name = self.get_object_relation(object_name, relation_name)
if object_type == NBDevice and site_name is None:
site_name = self.get_site_name(NBCluster, cluster_name)
if site_name is not None:
log.debug2(f"Found a matching cluster site for {object_name}, using site '{site_name}'")
# set default site name
if site_name is None:
site_name = self.site_name
log.debug(f"No site relation for '{object_name}' found, using default site '{site_name}'")
# set the site for cluster to None if None-keyword ("<NONE>") is set via cluster_site_relation
if object_type == NBCluster and site_name == "<NONE>":
site_name = None
log.debug2(f"Site relation for '{object_name}' set to None")
return site_name
def get_object_based_on_macs(self, object_type, mac_list=None):
"""
Try to find a NetBox object based on list of MAC addresses.
Iterate over all interfaces of this object type and compare MAC address with list of desired MAC
addresses. If match was found store related machine object and count every correct match.
If exactly one machine with matching interfaces was found then this one will be returned.
If two or more machines with matching MACs are found compare the two machines with
the highest amount of matching interfaces. If the ration of matching interfaces
exceeds 2.0 then the top matching machine is chosen as desired object.
If the ration is below 2.0 then None will be returned. The probability is too low that
this one is the correct one.
None will also be returned if no machine was found at all.
Parameters
----------
object_type: (NBDevice, NBVM)
type of NetBox device to find in inventory
mac_list: list
a list of MAC addresses to compare against NetBox interface objects
Returns
-------
(NBDevice, NBVM, None): object instance of found device, otherwise None
"""
object_to_return = None
if object_type not in [NBDevice, NBVM]:
raise ValueError(f"Object must be a '{NBVM.name}' or '{NBDevice.name}'.")
if mac_list is None or not isinstance(mac_list, list) or len(mac_list) == 0:
return
interface_typ = NBInterface if object_type == NBDevice else NBVMInterface
objects_with_matching_macs = dict()
matching_object = None
for interface in self.inventory.get_all_items(interface_typ):
if grab(interface, "data.mac_address") in mac_list:
matching_object = grab(interface, f"data.{interface.secondary_key}")
if not isinstance(matching_object, (NBDevice, NBVM)):
continue
log.debug2("Found matching MAC '%s' on %s '%s'" %
(grab(interface, "data.mac_address"), object_type.name,
matching_object.get_display_name(including_second_key=True)))
if objects_with_matching_macs.get(matching_object) is None:
objects_with_matching_macs[matching_object] = 1
else:
objects_with_matching_macs[matching_object] += 1
# try to find object based on amount of matching MAC addresses
num_devices_witch_matching_macs = len(objects_with_matching_macs.keys())
if num_devices_witch_matching_macs == 1 and isinstance(matching_object, (NBDevice, NBVM)):
log.debug2("Found one %s '%s' based on MAC addresses and using it" %
(object_type.name, matching_object.get_display_name(including_second_key=True)))
object_to_return = list(objects_with_matching_macs.keys())[0]
elif num_devices_witch_matching_macs > 1:
log.debug2(f"Found {num_devices_witch_matching_macs} {object_type.name}s with matching MAC addresses")
# now select the two top matches
first_choice, second_choice = \
sorted(objects_with_matching_macs, key=objects_with_matching_macs.get, reverse=True)[0:2]
first_choice_matches = objects_with_matching_macs.get(first_choice)
second_choice_matches = objects_with_matching_macs.get(second_choice)
log.debug2(f"The top candidate {first_choice.get_display_name()} with {first_choice_matches} matches")
log.debug2(f"The second candidate {second_choice.get_display_name()} with {second_choice_matches} matches")
# get ratio between
matching_ration = first_choice_matches / second_choice_matches
# only pick the first one if the ration exceeds 2
if matching_ration >= 2.0:
log.debug2(f"The matching ratio of {matching_ration} is high enough "
f"to select {first_choice.get_display_name()} as desired {object_type.name}")
object_to_return = first_choice
else:
log.debug2("Both candidates have a similar amount of "
"matching interface MAC addresses. Using NONE of them!")
return object_to_return
def get_object_based_on_primary_ip(self, object_type, primary_ip4=None, primary_ip6=None):
"""
Try to find a NBDevice or NBVM based on the primary IP address. If an exact
match was found the device/vm object will be returned immediately without
checking of the other primary IP address (if defined).
Parameters
----------
object_type: (NBDevice, NBVM)
object type to look for
primary_ip4: str
primary IPv4 address of object to find
primary_ip6: str
primary IPv6 address of object to find
Returns
-------
"""
def _matches_device_primary_ip(device_primary_ip, ip_needle):
ip = None
if device_primary_ip is not None and ip_needle is not None:
if isinstance(device_primary_ip, dict):
ip = grab(device_primary_ip, "address")
elif isinstance(device_primary_ip, int):
ip = self.inventory.get_by_id(NBIPAddress, nb_id=device_primary_ip)
ip = grab(ip, "data.address")
if ip is not None and ip.split("/")[0] == ip_needle:
return True
return False
if object_type not in [NBDevice, NBVM]:
raise ValueError(f"Object must be a '{NBVM.name}' or '{NBDevice.name}'.")
if primary_ip4 is None and primary_ip6 is None:
return
if primary_ip4 is not None:
primary_ip4 = str(primary_ip4).split("/")[0]
if primary_ip6 is not None:
primary_ip6 = str(primary_ip6).split("/")[0]
for device in self.inventory.get_all_items(object_type):
if _matches_device_primary_ip(grab(device, "data.primary_ip4"), primary_ip4) is True:
log.debug2(f"Found existing host '{device.get_display_name()}' "
f"based on the primary IPv4 '{primary_ip4}'")
return device
if _matches_device_primary_ip(grab(device, "data.primary_ip6"), primary_ip6) is True:
log.debug2(f"Found existing host '{device.get_display_name()}' "
f"based on the primary IPv6 '{primary_ip6}'")
return device
def get_vmware_object_tags(self, obj):
"""
Get tags from vCenter for submitted object.
Parameters
----------
obj
pyvmomi object to retrieve tags for
Returns
-------
tag_list: list
list of NBTag objets retrieved from vCenter for this object
"""
if obj is None:
return
tag_list = list()
if self.tag_session is not None:
# noinspection PyBroadException
try:
object_tag_ids = self.tag_session.tagging.TagAssociation.list_attached_tags(
DynamicID(type=grab(obj, "_wsdlName"), id=grab(obj, "_moId")))
except Exception as e:
log.error(f"Unable to retrieve vCenter tags for '{obj.name}': {e}")
return
for tag_id in object_tag_ids:
# noinspection PyBroadException
try:
tag_name = self.tag_session.tagging.Tag.get(tag_id).name
tag_description = self.tag_session.tagging.Tag.get(tag_id).description
except Exception as e:
log.error(f"Unable to retrieve vCenter tag '{tag_id}' for '{obj.name}': {e}")
continue
if tag_name is not None:
if tag_description is not None and len(f"{tag_description}") > 0:
tag_description = f"{primary_tag_name}: {tag_description}"
else:
tag_description = primary_tag_name
tag_list.append(self.inventory.add_update_object(NBTag, data={
"name": tag_name,
"description": tag_description
}))
return tag_list
def collect_object_tags(self, obj):
"""
collect tags from object based on the config settings
Parameters
----------
obj
pyvmomi object to retrieve tags for
Returns
-------
tag_list: list
a list of NBTag objets retrieved from vCenter for this object
"""
if obj is None:
return
tag_list = list()
if isinstance(obj, (vim.ClusterComputeResource, vim.ComputeResource)):
tag_source = self.settings.cluster_tag_source
elif isinstance(obj, vim.HostSystem):
tag_source = self.settings.host_tag_source
elif isinstance(obj, vim.VirtualMachine):
tag_source = self.settings.vm_tag_source
else:
raise ValueError(f"Tags for '{grab(obj, '_wsdlName')}' are not supported")
if tag_source is None or self.tag_session is None:
return tag_list
log.debug2(f"Collecting tags for {obj.name}")
if "object" in tag_source:
tag_list.extend(self.get_vmware_object_tags(obj))
if "parent_folder_1" in tag_source or "parent_folder_2" in tag_source:
parent_folder_1 = self.get_parent_object_by_class(obj, vim.Folder)
if parent_folder_1 is not None:
if "parent_folder_1" in tag_source:
tag_list.extend(self.get_vmware_object_tags(parent_folder_1))
if "parent_folder_2" in tag_source:
parent_folder_2 = self.get_parent_object_by_class(obj, vim.Folder)
if parent_folder_2 is not None:
tag_list.extend(self.get_vmware_object_tags(parent_folder_2))
if not isinstance(obj, (vim.ClusterComputeResource, vim.ComputeResource)) and "cluster" in tag_source:
cluster = self.get_parent_object_by_class(obj, vim.ClusterComputeResource)
if cluster is not None:
tag_list.extend(self.get_vmware_object_tags(cluster))
single_cluster = self.get_parent_object_by_class(obj, vim.ComputeResource)
if single_cluster is not None:
tag_list.extend(self.get_vmware_object_tags(single_cluster))
if "datacenter" in tag_source:
datacenter = self.get_parent_object_by_class(obj, vim.Datacenter)
if datacenter is not None:
tag_list.extend(self.get_vmware_object_tags(datacenter))
return tag_list
def get_object_custom_fields(self, obj):
"""
Get custom attributes from vCenter for submitted object and as NetBox custom fields
Parameters
----------
obj
pyvmomi object to retrieve custom attributes from
Returns
-------
custom_fields: dict
dictionary with assigned custom fields
"""
return_custom_fields = dict()
custom_value = list()
if self.settings.sync_custom_attributes is True:
custom_value = grab(obj, "customValue", fallback=list())
if grab(obj, "_wsdlName") == "VirtualMachine":
object_type = "virtualization.virtualmachine"
custom_object_attributes = self.settings.vm_custom_object_attributes or list()
object_attribute_prefix = "vm"
else:
object_type = "dcim.device"
custom_object_attributes = self.settings.host_custom_object_attributes or list()
object_attribute_prefix = "host"
# add basic host data to device
if object_type == "dcim.device":
num_cpu_cores = grab(obj, "summary.hardware.numCpuCores")
cpu_model = grab(obj, "summary.hardware.cpuModel")
memory_size = grab(obj, "summary.hardware.memorySize")
if num_cpu_cores is not None:
custom_field = self.add_update_custom_field({
"name": "host_cpu_cores",
"label": "Physical CPU Cores",
"object_types": [object_type],
"type": "text",
"description": f"Reported Host CPU cores"
})
return_custom_fields[grab(custom_field, "data.name")] = f"{num_cpu_cores} {cpu_model}"
if isinstance(memory_size, int):
custom_field = self.add_update_custom_field({
"name": "host_memory",
"label": "Memory",
"object_types": [object_type],
"type": "text",
"description": f"Reported size of Memory"
})
memory_size = round(memory_size / 1024 ** 3)
memory_unit = "GB"
if memory_size >= 1024:
memory_size = memory_size / 1024
memory_unit = "TB"
return_custom_fields[grab(custom_field, "data.name")] = f"{memory_size} {memory_unit}"
field_definition = {grab(k, "key"): grab(k, "name") for k in grab(obj, "availableField", fallback=list())}
for obj_custom_field in custom_value:
key = grab(obj_custom_field, "key")
value = grab(obj_custom_field, "value")
if key is None or value is None:
continue
label = field_definition.get(key)
if label is None:
continue
label = label.strip('"')
if self.settings.custom_attribute_exclude is not None and \
label in self.settings.custom_attribute_exclude:
log.debug(f"Custom attribute '{label}' excluded from sync. Skipping")
continue
custom_field = self.add_update_custom_field({
"name": f"vcsa_{label}",
"label": label,
"object_types": [object_type],
"type": "text",
"description": f"vCenter '{self.name}' synced custom attribute '{label}'"
})
return_custom_fields[grab(custom_field, "data.name")] = value
for custom_object_attribute in custom_object_attributes:
attribute_data = grab(obj, custom_object_attribute, fallback="NOT FOUND")
if attribute_data == "NOT FOUND":
log.warning(f"This object has no attribute '{custom_object_attribute}' or attribute is undefined.")
continue
if isinstance(attribute_data, datetime.datetime):
custom_field_type = "text"
attribute_data = attribute_data.strftime("%Y-%m-%dT%H:%M:%S%z")
elif isinstance(attribute_data, bool):
custom_field_type = "boolean"
elif isinstance(attribute_data, int):
custom_field_type = "integer"
elif isinstance(attribute_data, str):
custom_field_type = "text"
else:
import json
# noinspection PyBroadException
try:
attribute_data = json.loads(json.dumps(attribute_data, cls=VmomiJSONEncoder, sort_keys=True))
except Exception:
attribute_data = json.loads(json.dumps(str(attribute_data)))
custom_field_type = "json"
custom_field = self.add_update_custom_field({
"name": f"vcsa_{object_attribute_prefix}_{custom_object_attribute}",
"label": custom_object_attribute,
"object_types": [object_type],
"type": custom_field_type,
"description": f"vCenter '{self.name}' synced object attribute '{custom_object_attribute}'"
})
return_custom_fields[grab(custom_field, "data.name")] = attribute_data
return return_custom_fields
def get_object_relation(self, name, relation, fallback=None):
"""
Parameters
----------
name: str
name of the object to find a relation for
relation: str
name of the config variable relation (i.e: vm_tag_relation)
fallback: str
fallback string if no relation matched
Returns
-------
data: str, list, None
string of matching relation or list of matching tags
"""
resolved_list = list()
for single_relation in grab(self.settings, relation, fallback=list()):
object_regex = single_relation.get("object_regex")
match_found = False
if object_regex.match(name):
resolved_name = single_relation.get("assigned_name")
log.debug2(f"Found a matching {relation} '{resolved_name}' ({object_regex.pattern}) for {name}")
resolved_list.append(resolved_name)
match_found = True
# special cluster condition
if match_found is False and grab(f"{relation}".split("_"), "0") == "cluster":
stripped_name = "/".join(name.split("/")[1:])
if object_regex.match(stripped_name):
resolved_name = single_relation.get("assigned_name")
log.debug2(f"Found a matching {relation} '{resolved_name}' ({object_regex.pattern}) "
f"for {stripped_name}")
resolved_list.append(resolved_name)
if grab(f"{relation}".split("_"), "1") == "tag":
return resolved_list
else:
resolved_name = fallback
if len(resolved_list) >= 1:
resolved_name = resolved_list[0]
if len(resolved_list) > 1:
log.debug(f"Found {len(resolved_list)} matches for {name} in {relation}."
f" Using first on: {resolved_name}")
return resolved_name
def add_device_vm_to_inventory(self, object_type, object_data, pnic_data=None, vnic_data=None,
nic_ips=None, p_ipv4=None, p_ipv6=None, vmware_object=None, disk_data=None):
"""
Add/update device/VM object in inventory based on gathered data.
Try to find object first based on the object data, interface MAC addresses and primary IPs.
1. try to find by name and cluster/site
2. try to find by mac addresses interfaces
3. try to find by serial number (1st) or asset tag (2nd) (ESXi host)
4. try to find by primary IP
IP addresses for each interface are added here as well. First they will be checked and added
if all checks pass. For each IP address a matching IP prefix will be searched for. First we
look for longest matching IP Prefix in the same site. If this failed we try to find the longest
matching global IP Prefix.
If an IP Prefix was found then we try to get the VRF and VLAN for this prefix. Now we compare
if interface VLAN and prefix VLAN match up and warn if they don't. Then we try to add data to
the IP address if not already set:
add prefix VRF if VRF for this IP is undefined
add tenant if tenant for this IP is undefined
1. try prefix tenant
2. if prefix tenant is undefined try VLAN tenant
And we also set primary IP4/6 for this object depending on the "set_primary_ip" setting.
If an IP address is set as primary IP for another device then using this IP on another
device will be rejected by NetBox.
Setting "always":
check all NBDevice and NBVM objects if this IP address is set as primary IP to any
other object then this one. If we found another object, then we unset the primary_ip*
for the found object and assign it to this object.
This setting will also reset the primary IP if it has been changed in NetBox
Setting "when-undefined":
Will set the primary IP for this object if primary_ip4/6 is undefined. Will cause a
NetBox error if IP has been assigned to a different object as well
Setting "never":
Well, the attribute primary_ip4/6 will never be touched/changed.
Parameters
----------
object_type: (NBDevice, NBVM)
NetBoxObject subclass of object to add
object_data: dict
data of object to add/update
pnic_data: dict