-
Notifications
You must be signed in to change notification settings - Fork 13
/
stas.py
1607 lines (1318 loc) · 59.6 KB
/
stas.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2021, Dell Inc. or its subsidiaries. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# See the LICENSE file for details.
#
# This file is part of NVMe STorage Appliance Services (nvme-stas).
#
# Authors: Martin Belanger <Martin.Belanger@dell.com>
#
'''Library for staf/stac'''
import os
import re
import sys
import signal
import logging
import configparser
import platform
import ipaddress
import pyudev
import systemd.daemon
import dasbus.connection
from gi.repository import Gio, GLib, GObject
from libnvme import nvme
from staslib.version import KernelVersion
from staslib import defs
try:
from pyudev.glib import MonitorObserver
except (ModuleNotFoundError, AttributeError):
from staslib.glibudev import MonitorObserver # pylint: disable=relative-beyond-top-level,ungrouped-imports
DC_KATO_DEFAULT = 30 # seconds
# ******************************************************************************
def check_if_allowed_to_continue():
'''@brief Let's perform some basic checks before going too far. There are
a few pre-requisites that need to be met before this program
is allowed to proceed:
1) The program needs to have root privileges
2) The nvme-tcp kernel module must be loaded
@return This function will only return if all conditions listed above
are met. Otherwise the program exits.
'''
# 1) Check root privileges
if os.geteuid() != 0:
sys.exit(f'Permission denied. You need root privileges to run {os.path.basename(sys.argv[0])}.')
# 2) Check that nvme-tcp kernel module is running
if not os.path.exists('/dev/nvme-fabrics'):
# There's no point going any further if the kernel module hasn't been loaded
sys.exit('Fatal error: missing nvme-tcp kernel module')
# ******************************************************************************
LOG = logging.getLogger(__name__) # Singleton
LOG.propagate = False
def get_log_handler(syslog: bool, identifier: str):
'''Instantiate and return a log handler'''
if syslog:
try:
# Try journal logger first
import systemd.journal # pylint: disable=redefined-outer-name,import-outside-toplevel
handler = systemd.journal.JournalHandler(SYSLOG_IDENTIFIER=identifier)
except ModuleNotFoundError:
# Go back to standard syslog handler
from logging.handlers import SysLogHandler # pylint: disable=import-outside-toplevel
handler = SysLogHandler(address="/dev/log")
handler.setFormatter(
logging.Formatter('{}: %(message)s'.format(identifier)) # pylint: disable=consider-using-f-string
)
else:
# Log to stdout
handler = logging.StreamHandler(stream=sys.stdout)
return handler
def log_level() -> str:
'''@brief return current log level'''
return str(logging.getLevelName(LOG.getEffectiveLevel()))
# ******************************************************************************
TRON = False # Singleton
def trace_control(tron: bool):
'''@brief Allows changing debug level in real time. Setting tron to True
enables full tracing.
'''
global TRON # pylint: disable=global-statement
TRON = tron
LOG.setLevel(logging.DEBUG if TRON else logging.INFO)
# ******************************************************************************
TOKEN_RE = re.compile(r'\s*;\s*')
OPTION_RE = re.compile(r'\s*=\s*')
def parse_controller(controller):
'''@brief Parse a "controller" entry. Controller entries are strings
composed of several configuration parameters delimited by
semi-colons. Each configuration parameter is specified as a
"key=value" pair.
@return A dictionary of key-value pairs.
'''
options = dict()
tokens = TOKEN_RE.split(controller)
for token in tokens:
if token:
try:
option, val = OPTION_RE.split(token)
options[option] = val
except ValueError:
pass
return options
# ******************************************************************************
class OrderedMultisetDict(dict):
'''This class is used to change the behavior of configparser.ConfigParser
and allow multiple configuration parameters with the same key. The
result is a list of values.
'''
def __setitem__(self, key, value):
if key in self and isinstance(value, list):
self[key].extend(value)
else:
super().__setitem__(key, value)
def __getitem__(self, key):
value = super().__getitem__(key)
if isinstance(value, str):
return value.split('\n')
return value
class Configuration:
'''Read and cache configuration file.'''
def __init__(self, conf_file='/dev/null'):
self._defaults = {
('Global', 'tron'): 'false',
('Global', 'persistent-connections'): 'true',
('Global', 'hdr-digest'): 'false',
('Global', 'data-digest'): 'false',
('Global', 'kato'): None,
('Global', 'ignore-iface'): 'false',
('Global', 'ip-family'): 'ipv4+ipv6',
('Global', 'udev-rule'): 'enabled',
('Global', 'sticky-connections'): 'disabled',
('Service Discovery', 'zeroconf'): 'enabled',
('Controllers', 'controller'): list(),
('Controllers', 'blacklist'): list(),
}
self._conf_file = conf_file
self.reload()
def reload(self):
'''@brief Reload the configuration file.'''
self._config = self.read_conf_file()
@property
def conf_file(self): # pylint: disable=missing-function-docstring
return self._conf_file
@conf_file.setter
def conf_file(self, fname): # pylint: disable=missing-function-docstring
self._conf_file = fname
self.reload()
@property
def tron(self):
'''@brief return the "tron" config parameter'''
return self.__get_bool('Global', 'tron')
@property
def hdr_digest(self):
'''@brief return the "hdr-digest" config parameter'''
return self.__get_bool('Global', 'hdr-digest')
@property
def data_digest(self):
'''@brief return the "data-digest" config parameter'''
return self.__get_bool('Global', 'data-digest')
@property
def persistent_connections(self):
'''@brief return the "persistent-connections" config parameter'''
return self.__get_bool('Global', 'persistent-connections')
@property
def ignore_iface(self):
'''@brief return the "ignore-iface" config parameter'''
return self.__get_bool('Global', 'ignore-iface')
@property
def ip_family(self):
'''@brief return the "ip-family" config parameter.
@rtype tuple
'''
family = self.__get_value('Global', 'ip-family')[0]
if family == 'ipv4':
return (4,)
if family == 'ipv6':
return (6,)
return (4, 6)
@property
def udev_rule_enabled(self):
'''@brief return the "udev-rule" config parameter'''
return self.__get_value('Global', 'udev-rule')[0] == 'enabled'
@property
def sticky_connections(self):
'''@brief return the "sticky-connections" config parameter'''
return self.__get_value('Global', 'sticky-connections')[0] == 'enabled'
@property
def kato(self):
'''@brief return the "kato" config parameter'''
kato = self.__get_value('Global', 'kato')[0]
return None if kato is None else int(kato)
def get_controllers(self):
'''@brief Return the list of controllers in the config file.
Each controller is in the form of a dictionary as follows.
Note that some of the keys are optional.
{
'transport': [TRANSPORT],
'traddr': [TRADDR],
'trsvcid': [TRSVCID],
'host-traddr': [TRADDR],
'host-iface': [IFACE],
'subsysnqn': [NQN],
}
'''
controller_list = self.__get_value('Controllers', 'controller')
controllers = [parse_controller(controller) for controller in controller_list]
for controller in controllers:
try:
# replace 'nqn' key by 'subsysnqn', if present.
controller['subsysnqn'] = controller.pop('nqn')
except KeyError:
pass
return controllers
def get_blacklist(self):
'''@brief Return the list of blacklisted controllers in the config file.
Each blacklisted controller is in the form of a dictionary
as follows. All the keys are optional.
{
'transport': [TRANSPORT],
'traddr': [TRADDR],
'trsvcid': [TRSVCID],
'host-iface': [IFACE],
'subsysnqn': [NQN],
}
'''
controller_list = self.__get_value('Controllers', 'blacklist')
blacklist = [parse_controller(controller) for controller in controller_list]
for controller in blacklist:
controller.pop('host-traddr', None) # remove host-traddr
try:
# replace 'nqn' key by 'subsysnqn', if present.
controller['subsysnqn'] = controller.pop('nqn')
except KeyError:
pass
return blacklist
def get_stypes(self):
'''@brief Get the DNS-SD/mDNS service types.'''
return ['_nvme-disc._tcp'] if self.zeroconf_enabled() else list()
def zeroconf_enabled(self): # pylint: disable=missing-function-docstring
return self.__get_value('Service Discovery', 'zeroconf')[0] == 'enabled'
def read_conf_file(self):
'''@brief Read the configuration file if the file exists.'''
config = configparser.ConfigParser(
default_section=None,
allow_no_value=True,
delimiters=('='),
interpolation=None,
strict=False,
dict_type=OrderedMultisetDict,
)
if self._conf_file and os.path.isfile(self._conf_file):
config.read(self._conf_file)
return config
def __get_bool(self, section, option):
return self.__get_value(section, option)[0] == 'true'
def __get_value(self, section, option):
try:
value = self._config.get(section=section, option=option)
except (configparser.NoSectionError, configparser.NoOptionError, KeyError):
value = self._defaults.get((section, option), [])
if not isinstance(value, list):
value = [value]
return value if value is not None else list()
CNF = Configuration() # Singleton
# ******************************************************************************
class SysConfiguration:
'''Read and cache the host configuration file.'''
def __init__(self, conf_file='/dev/null'):
self._conf_file = conf_file
self.reload()
def reload(self):
'''@brief Reload the configuration file.'''
self._config = self.read_conf_file()
@property
def conf_file(self): # pylint: disable=missing-function-docstring
return self._conf_file
@conf_file.setter
def conf_file(self, fname): # pylint: disable=missing-function-docstring
self._conf_file = fname
self.reload()
def as_dict(self): # pylint: disable=missing-function-docstring
return {
'hostnqn': self.hostnqn,
'hostid': self.hostid,
'symname': self.hostsymname,
}
@property
def hostnqn(self):
'''@brief return the host NQN
@return: Host NQN
@raise: Host NQN is mandatory. The program will terminate if a
Host NQN cannot be determined.
'''
try:
value = self.__get_value('Host', 'nqn', '/etc/nvme/hostnqn')
except FileNotFoundError as ex:
sys.exit('Error reading mandatory Host NQN (see stasadm --help): %s', ex)
if not value.startswith('nqn.'):
sys.exit('Error Host NQN "%s" should start with "nqn."', value)
return value
@property
def hostid(self):
'''@brief return the host ID
@return: Host ID
@raise: Host ID is mandatory. The program will terminate if a
Host ID cannot be determined.
'''
try:
value = self.__get_value('Host', 'id', '/etc/nvme/hostid')
except FileNotFoundError as ex:
sys.exit('Error reading mandatory Host ID (see stasadm --help): %s', ex)
return value
@property
def hostsymname(self):
'''@brief return the host symbolic name (or None)
@return: symbolic name or None
'''
try:
value = self.__get_value('Host', 'symname')
except FileNotFoundError as ex:
LOG.warning('Error reading host symbolic name (will remain undefined): %s', ex)
value = None
return value
def read_conf_file(self):
'''@brief Read the configuration file if the file exists.'''
config = configparser.ConfigParser(
default_section=None, allow_no_value=True, delimiters=('='), interpolation=None, strict=False
)
if os.path.isfile(self._conf_file):
config.read(self._conf_file)
return config
def __get_value(self, section, option, default_file=None):
'''@brief A configuration file consists of sections, each led by a
[section] header, followed by key/value entries separated
by a equal sign (=). This method retrieves the value
associated with the key @option from the section @section.
If the value starts with the string "file://", then the value
will be retrieved from that file.
@param section: Configuration section
@param option: The key to look for
@param default_file: A file that contains the default value
@return: On success, the value associated with the key. On failure,
this method will return None is a default_file is not
specified, or will raise an exception if a file is not
found.
@raise: This method will raise the FileNotFoundError exception if
the value retrieved is a file that does not exist.
'''
try:
value = self._config.get(section=section, option=option)
if not value.startswith('file://'):
return value
file = value[7:]
except (configparser.NoSectionError, configparser.NoOptionError, KeyError):
if default_file is None:
return None
file = default_file
with open(file) as f: # pylint: disable=unspecified-encoding
return f.readline().split()[0]
SYS_CNF = SysConfiguration('/etc/stas/sys.conf') # Singleton
# ******************************************************************************
KERNEL_VERSION = KernelVersion(platform.release())
class NvmeOptions: # Singleton
'''Object used to read and cache contents of file /dev/nvme-fabrics.
Note that this file was not readable prior to Linux 5.16.
'''
__instance = None
__initialized = False
def __init__(self):
if self.__initialized: # Singleton - only init once
return
self.__initialized = True
# Supported options can be determined by looking at the kernel version
# or by reading '/dev/nvme-fabrics'. The ability to read the options
# from '/dev/nvme-fabrics' was only introduced in kernel 5.17, but may
# have been backported to older kernels. In any case, if the kernel
# version meets the minimum version for that option, then we don't
# even need to read '/dev/nvme-fabrics'.
self._supported_options = {
'discovery': KERNEL_VERSION >= defs.KERNEL_TP8013_MIN_VERSION,
'host_iface': KERNEL_VERSION >= defs.KERNEL_IFACE_MIN_VERSION,
}
# If some of the options are False, we need to check wether they can be
# read from '/dev/nvme-fabrics'. This method allows us to determine that
# an older kernel actually supports a specific option because it was
# backported to that kernel.
if not all(self._supported_options.values()): # At least one option is False.
try:
with open('/dev/nvme-fabrics') as f: # pylint: disable=unspecified-encoding
options = [option.split('=')[0].strip() for option in f.readlines()[0].rstrip('\n').split(',')]
except PermissionError: # Must be root to read this file
raise
except OSError:
LOG.warning('Cannot determine which NVMe options the kernel supports')
else:
for option, supported in self._supported_options.items():
if not supported:
self._supported_options[option] = option in options
def __new__(cls):
'''This is used to make this class a singleton'''
if cls.__instance is None:
cls.__instance = super(NvmeOptions, cls).__new__(cls)
return cls.__instance
@classmethod
def destroy(cls):
'''This is used to destroy this singleton class'''
cls.__instance = None
cls.__initialized = False
def __str__(self):
return f'supported options: {self._supported_options}'
@property
def discovery_supp(self):
'''This option adds support for TP8013'''
return self._supported_options['discovery']
@property
def host_iface_supp(self):
'''This option allows forcing connections to go over
a specific interface regardless of the routing tables.
'''
return self._supported_options['host_iface']
# ******************************************************************************
class GTimer:
'''@brief Convenience class to wrap GLib timers'''
def __init__(
self, interval_sec: float = 0, user_cback=lambda: GLib.SOURCE_REMOVE, *user_data, priority=GLib.PRIORITY_DEFAULT
): # pylint: disable=keyword-arg-before-vararg
self._source = None
self._interval_sec = float(interval_sec)
self._user_cback = user_cback
self._user_data = user_data
self._priority = priority if priority is not None else GLib.PRIORITY_DEFAULT
def _release_resources(self):
self.stop()
self._user_cback = None
self._user_data = None
def kill(self):
'''@brief Used to release all resources associated with a timer.'''
self._release_resources()
def __str__(self):
if self._source is not None:
return f'{self._interval_sec}s [{self.time_remaining()}s]'
return f'{self._interval_sec}s [off]'
def _callback(self, *_):
retval = self._user_cback(*self._user_data)
if retval == GLib.SOURCE_REMOVE:
self._source = None
return retval
def stop(self):
'''@brief Stop timer'''
if self._source is not None:
self._source.destroy()
self._source = None
def start(self, new_interval_sec: float = -1.0):
'''@brief Start (or restart) timer'''
if new_interval_sec >= 0:
self._interval_sec = float(new_interval_sec)
if self._source is not None:
self._source.set_ready_time(
self._source.get_time() + (self._interval_sec * 1000000)
) # ready time is in micro-seconds (monotonic time)
else:
if self._interval_sec.is_integer():
self._source = GLib.timeout_source_new_seconds(int(self._interval_sec)) # seconds resolution
else:
self._source = GLib.timeout_source_new(self._interval_sec * 1000.0) # mili-seconds resolution
self._source.set_priority(self._priority)
self._source.set_callback(self._callback)
self._source.attach()
def clear(self):
'''@brief Make timer expire now. The callback function
will be invoked immediately by the main loop.
'''
if self._source is not None:
self._source.set_ready_time(0) # Expire now!
def set_callback(self, user_cback, *user_data):
'''@brief set the callback function to invoke when timer expires'''
self._user_cback = user_cback
self._user_data = user_data
def set_timeout(self, new_interval_sec: float):
'''@brief set the timer's duration'''
if new_interval_sec >= 0:
self._interval_sec = float(new_interval_sec)
def get_timeout(self):
'''@brief get the timer's duration'''
return self._interval_sec
def time_remaining(self) -> float:
'''@brief Get how much time remains on a timer before it fires.'''
if self._source is not None:
delta_us = self._source.get_ready_time() - self._source.get_time() # monotonic time in micro-seconds
if delta_us > 0:
return delta_us / 1000000.0
return 0
# ******************************************************************************
class Udev:
'''@brief Udev event monitor. Provide a way to register for udev events.'''
def __init__(self):
self._registry = dict()
self._context = pyudev.Context()
self._monitor = pyudev.Monitor.from_netlink(self._context)
self._monitor.filter_by(subsystem='nvme')
self._observer = MonitorObserver(self._monitor)
self._sig_id = self._observer.connect('device-event', self._device_event)
self._monitor.start()
def _release_resources(self):
if self._sig_id is not None:
self._observer.disconnect(self._sig_id)
self._sig_id = None
self._observer = None
if self._monitor is not None:
self._monitor.remove_filter()
self._monitor = None
self._context = None
self._registry = None
def clean(self):
'''Clean up all resources'''
self._release_resources()
def get_nvme_device(self, sys_name):
'''@brief Get the udev device object associated with an nvme device.
@param sys_name: The device system name (e.g. 'nvme1')
@return A pyudev.device._device.Device object
'''
device_node = os.path.join('/dev', sys_name)
try:
return pyudev.Devices.from_device_file(self._context, device_node)
except pyudev.DeviceNotFoundByFileError as ex:
LOG.error("Udev.get_nvme_device() - Error: %s", ex)
return None
def register_for_events(self, sys_name: str, user_cback):
'''@brief Register a callback function to be called when udev events
are received for a specific nvme device.
@param sys_name: The device system name (e.g. 'nvme1')
'''
if sys_name:
self._registry[sys_name] = user_cback
def unregister_for_events(self, user_cback):
'''@brief The opposite of register_for_events()'''
entries = list(self._registry.items())
for sys_name, _user_cback in entries:
if user_cback == _user_cback:
self._registry.pop(sys_name, None)
break
def get_attributes(self, sys_name: str, attr_ids) -> dict:
'''@brief Get all the attributes associated with device @sys_name'''
attrs = {attr_id: '' for attr_id in attr_ids}
if sys_name:
udev = self.get_nvme_device(sys_name)
if udev is not None:
for attr_id in attr_ids:
try:
value = udev.attributes.asstring(attr_id).strip()
attrs[attr_id] = '' if value == '(efault)' else value
except Exception: # pylint: disable=broad-except
pass
return attrs
def find_nvme_dc_device(self, tid):
'''@brief Find the nvme device associated with the specified
Discovery Controller.
@return The device if a match is found, None otherwise.
'''
for device in self._context.list_devices(
subsystem='nvme', NVME_TRADDR=tid.traddr, NVME_TRSVCID=tid.trsvcid, NVME_TRTYPE=tid.transport
):
# Note: Prior to 5.18 linux didn't expose the cntrltype through
# the sysfs. So, this may return None on older kernels.
cntrltype = device.attributes.get('cntrltype')
if cntrltype is not None and cntrltype.decode() != 'discovery':
continue
# Imply Discovery controller based on the absence of children.
# Discovery Controllers have no children devices
if len(list(device.children)) != 0:
continue
if self._get_tid(device) != tid:
continue
return device
return None
def find_nvme_ioc_device(self, tid):
'''@brief Find the nvme device associated with the specified
I/O Controller.
@return The device if a match is found, None otherwise.
'''
for device in self._context.list_devices(
subsystem='nvme', NVME_TRADDR=tid.traddr, NVME_TRSVCID=tid.trsvcid, NVME_TRTYPE=tid.transport
):
# Note: Prior to 5.18 linux didn't expose the cntrltype through
# the sysfs. So, this may return None on older kernels.
cntrltype = device.attributes.get('cntrltype')
if cntrltype is not None and cntrltype.decode() != 'io':
continue
# Imply I/O controller based on the presence of children.
# I/O Controllers have children devices
if len(list(device.children)) == 0:
continue
if self._get_tid(device) != tid:
continue
return device
return None
def _device_event(self, _observer, device):
user_cback = self._registry.get(device.sys_name, None)
if user_cback is not None:
user_cback(device)
@staticmethod
def _get_property(device, prop, default=''):
prop = device.properties.get(prop, default)
return '' if prop.lower() == 'none' else prop
@staticmethod
def _get_attribute(device, attr_id, default=''):
try:
attr = device.attributes.asstring(attr_id).strip()
except Exception: # pylint: disable=broad-except
attr = default
return '' if attr.lower() == 'none' else attr
@staticmethod
def _get_tid(device):
cid = {
'transport': Udev._get_property(device, 'NVME_TRTYPE'),
'traddr': Udev._get_property(device, 'NVME_TRADDR'),
'trsvcid': Udev._get_property(device, 'NVME_TRSVCID'),
'host-traddr': Udev._get_property(device, 'NVME_HOST_TRADDR'),
'host-iface': Udev._get_property(device, 'NVME_HOST_IFACE'),
'subsysnqn': Udev._get_attribute(device, 'subsysnqn'),
}
return TransportId(cid)
UDEV = Udev() # Singleton
# ******************************************************************************
def cid_from_dlpe(dlpe, host_traddr, host_iface):
'''@brief Take a Discovery Log Page Entry and return a Controller ID as a dict.'''
return {
'transport': dlpe['trtype'],
'traddr': dlpe['traddr'],
'trsvcid': dlpe['trsvcid'],
'host-traddr': host_traddr,
'host-iface': host_iface,
'subsysnqn': dlpe['subnqn'],
}
# ******************************************************************************
def blacklisted(blacklisted_ctrl_list, controller):
'''@brief Check if @controller is black-listed.'''
for blacklisted_ctrl in blacklisted_ctrl_list:
test_results = [val == controller.get(key, None) for key, val in blacklisted_ctrl.items()]
if all(test_results):
return True
return False
# ******************************************************************************
def remove_blacklisted(controllers: list):
'''@brief Remove black-listed controllers from the list of controllers.'''
blacklisted_ctrl_list = CNF.get_blacklist()
if blacklisted_ctrl_list:
LOG.debug('remove_blacklisted() - blacklisted_ctrl_list = %s', blacklisted_ctrl_list)
controllers = [controller for controller in controllers if not blacklisted(blacklisted_ctrl_list, controller)]
return controllers
# ******************************************************************************
def remove_invalid_addresses(controllers: list):
'''@brief Remove controllers with invalid addresses from the list of controllers.'''
valid_controllers = list()
for controller in controllers:
# First, let's make sure that traddr is
# syntactically a valid IPv4 or IPv6 address.
traddr = controller.get('traddr')
try:
ip = ipaddress.ip_address(traddr)
except ValueError:
LOG.warning('%s IP address is not valid', TransportId(controller))
continue
if ip.version not in CNF.ip_family:
LOG.debug('%s ignored because IPv%s is disabled in %s', TransportId(controller), ip.version, CNF.conf_file)
continue
valid_controllers.append(controller)
return valid_controllers
# ******************************************************************************
class TransportId:
# pylint: disable=too-many-instance-attributes
'''Transport Identifier'''
RDMA_IP_PORT = '4420'
DISC_IP_PORT = '8009'
def __init__(self, cid: dict):
'''@param cid: Controller Identifier. A dictionary with the following
contents.
{
'transport': str, # [mandatory]
'traddr': str, # [mandatory]
'subsysnqn': str, # [mandatory]
'trsvcid': str, # [optional]
'host-traddr': str, # [optional]
'host-iface': str, # [optional]
}
'''
self._transport = cid.get('transport')
self._traddr = cid.get('traddr')
trsvcid = cid.get('trsvcid')
self._trsvcid = (
trsvcid
if trsvcid
else (TransportId.RDMA_IP_PORT if self._transport == 'rdma' else TransportId.DISC_IP_PORT)
) # pylint: disable=used-before-assignment
self._host_traddr = cid.get('host-traddr', '')
self._host_iface = '' if CNF.ignore_iface else cid.get('host-iface', '')
self._subsysnqn = cid.get('subsysnqn')
self._key = (self._transport, self._traddr, self._trsvcid, self._host_traddr, self._host_iface, self._subsysnqn)
self._hash = hash(self._key)
self._id = f'({self._transport}, {self._traddr}, {self._trsvcid}{", " + self._subsysnqn if self._subsysnqn else ""}{", " + self._host_iface if self._host_iface else ""}{", " + self._host_traddr if self._host_traddr else ""})' # pylint: disable=line-too-long
@property
def key(self): # pylint: disable=missing-function-docstring
return self._key
@property
def hash(self): # pylint: disable=missing-function-docstring
return self._hash
@property
def transport(self): # pylint: disable=missing-function-docstring
return self._transport
@property
def traddr(self): # pylint: disable=missing-function-docstring
return self._traddr
@property
def trsvcid(self): # pylint: disable=missing-function-docstring
return self._trsvcid
@property
def host_traddr(self): # pylint: disable=missing-function-docstring
return self._host_traddr
@property
def host_iface(self): # pylint: disable=missing-function-docstring
return self._host_iface
@property
def subsysnqn(self): # pylint: disable=missing-function-docstring
return self._subsysnqn
def as_dict(self): # pylint: disable=missing-function-docstring
return {
'transport': self.transport,
'traddr': self.traddr,
'trsvcid': self.trsvcid,
'host-traddr': self.host_traddr,
'host-iface': self.host_iface,
'subsysnqn': self.subsysnqn,
}
def __str__(self):
return self._id
def __repr__(self):
return self._id
def __eq__(self, other):
return isinstance(other, self.__class__) and self.key == other.key
def __ne__(self, other):
return not isinstance(other, self.__class__) or self.key != other.key
def __hash__(self):
return self.hash
# ******************************************************************************
class NameResolver:
# pylint: disable=too-few-public-methods
'''@brief DNS resolver to convert host names to IP addresses.'''
def __init__(self):
self._resolver = Gio.Resolver.get_default()
def resolve_ctrl_async(self, cancellable, controllers: dict, callback):
'''@brief The traddr fields may specify a hostname instead of an IP
address. We need to resolve all the host names to addresses.
Resolving hostnames may take a while as a DNS server may need
to be contacted. For that reason, we're using async APIs with
callbacks to resolve all the hostnames.
The callback @callback will be called once all hostnames have
been resolved.
'''
pending_resolution_count = 0
def addr_resolved(resolver, result, indx):
hostname = controllers[indx]['traddr']
traddr = hostname
try:
addresses = resolver.lookup_by_name_finish(result)
if addresses:
traddr = addresses[0].to_string()
else:
LOG.error('Cannot resolve traddr: %s', hostname)
except GLib.GError:
LOG.error('Cannot resolve traddr: %s', hostname)
LOG.debug('NameResolver.resolve_ctrl_async() - resolved \'%s\' -> %s', hostname, traddr)
controllers[indx]['traddr'] = traddr
# Invoke callback after all hostnames have been resolved
nonlocal pending_resolution_count
pending_resolution_count -= 1
if pending_resolution_count == 0:
callback(controllers)
for indx, controller in enumerate(controllers):
if controller.get('transport') in ('tcp', 'rdma'):
hostname = controller.get('traddr')
if not hostname:
LOG.error('Invalid traddr: %s', controller)
else:
LOG.debug('NameResolver.resolve_ctrl_async() - resolving \'%s\'', hostname)
pending_resolution_count += 1
self._resolver.lookup_by_name_async(hostname, cancellable, addr_resolved, indx)
if pending_resolution_count == 0: # No names are pending asynchronous resolution
callback(controllers)
# ******************************************************************************
class AsyncCaller(GObject.Object):
'''@brief This class allows running methods asynchronously in a thread.'''
def __init__(self, user_function, *user_args):
'''@param user_function: function to run inside a thread
@param user_args: arguments passed to @user_function
'''
super().__init__()
self._user_function = user_function
self._user_args = user_args
def communicate(self, cancellable, cb_function, *cb_args):
'''@param cancellable: A Gio.Cancellable object that can be used to
cancel an in-flight async command.
@param cb_function: User callback function to call when the async
command has completed. The callback function
will be passed these arguments:
(async_caller_obj, result, *cb_args)
Where:
async_caller_obj: This AsyncCaller object instance
result: A GObject.Object instance that contains the result
cb_args: The cb_args arguments passed to communicate()
@param cb_args: User arguments to pass to @cb_function
'''
def in_thread_exec(task, self, task_data, cancellable): # pylint: disable=unused-argument
if task.return_error_if_cancelled():
return # Bail out if task has been cancelled