]> git.proxmox.com Git - ceph.git/blob - ceph/src/python-common/ceph/deployment/drive_group.py
7ac9759523dd8bb9f1b321d4a46915a9de97b858
[ceph.git] / ceph / src / python-common / ceph / deployment / drive_group.py
1 import enum
2 import yaml
3
4 from ceph.deployment.inventory import Device
5 from ceph.deployment.service_spec import ServiceSpec, PlacementSpec, CustomConfig
6 from ceph.deployment.hostspec import SpecValidationError
7
8 try:
9 from typing import Optional, List, Dict, Any, Union
10 except ImportError:
11 pass
12
13
14 class OSDMethod(str, enum.Enum):
15 raw = 'raw'
16 lvm = 'lvm'
17
18 def to_json(self) -> str:
19 return self.value
20
21
22 class DeviceSelection(object):
23 """
24 Used within :class:`ceph.deployment.drive_group.DriveGroupSpec` to specify the devices
25 used by the Drive Group.
26
27 Any attributes (even none) can be included in the device
28 specification structure.
29 """
30
31 _supported_filters = [
32 "actuators", "paths", "size", "vendor", "model", "rotational", "limit", "all"
33 ]
34
35 def __init__(self,
36 actuators=None, # type: Optional[int]
37 paths=None, # type: Optional[List[Dict[str, str]]]
38 model=None, # type: Optional[str]
39 size=None, # type: Optional[str]
40 rotational=None, # type: Optional[bool]
41 limit=None, # type: Optional[int]
42 vendor=None, # type: Optional[str]
43 all=False, # type: bool
44 ):
45 """
46 ephemeral drive group device specification
47 """
48 self.actuators = actuators
49
50 #: List of Device objects for devices paths.
51
52 self.paths = []
53
54 if paths is not None:
55 for device in paths:
56 if isinstance(device, dict):
57 path: str = device.get("path", '')
58 self.paths.append(Device(path, crush_device_class=device.get("crush_device_class", None))) # noqa E501
59 else:
60 self.paths.append(Device(str(device)))
61
62 #: A wildcard string. e.g: "SDD*" or "SanDisk SD8SN8U5"
63 self.model = model
64
65 #: Match on the VENDOR property of the drive
66 self.vendor = vendor
67
68 #: Size specification of format LOW:HIGH.
69 #: Can also take the form :HIGH, LOW:
70 #: or an exact value (as ceph-volume inventory reports)
71 self.size: Optional[str] = size
72
73 #: is the drive rotating or not
74 self.rotational = rotational
75
76 #: Limit the number of devices added to this Drive Group. Devices
77 #: are used from top to bottom in the output of ``ceph-volume inventory``
78 self.limit = limit
79
80 #: Matches all devices. Can only be used for data devices
81 self.all = all
82
83 def validate(self, name: str) -> None:
84 props = [self.actuators, self.model, self.vendor, self.size,
85 self.rotational] # type: List[Any]
86 if self.paths and any(p is not None for p in props):
87 raise DriveGroupValidationError(
88 name,
89 'device selection: `paths` and other parameters are mutually exclusive')
90 is_empty = not any(p is not None and p != [] for p in [self.paths] + props)
91 if not self.all and is_empty:
92 raise DriveGroupValidationError(name, 'device selection cannot be empty')
93
94 if self.all and not is_empty:
95 raise DriveGroupValidationError(
96 name,
97 'device selection: `all` and other parameters are mutually exclusive. {}'.format(
98 repr(self)))
99
100 @classmethod
101 def from_json(cls, device_spec):
102 # type: (dict) -> Optional[DeviceSelection]
103 if not device_spec:
104 return None
105 for applied_filter in list(device_spec.keys()):
106 if applied_filter not in cls._supported_filters:
107 raise KeyError(applied_filter)
108
109 return cls(**device_spec)
110
111 def to_json(self):
112 # type: () -> Dict[str, Any]
113 ret: Dict[str, Any] = {}
114 if self.paths:
115 ret['paths'] = [p.path for p in self.paths]
116 if self.model:
117 ret['model'] = self.model
118 if self.vendor:
119 ret['vendor'] = self.vendor
120 if self.size:
121 ret['size'] = self.size
122 if self.rotational is not None:
123 ret['rotational'] = self.rotational
124 if self.limit:
125 ret['limit'] = self.limit
126 if self.all:
127 ret['all'] = self.all
128
129 return ret
130
131 def __repr__(self) -> str:
132 keys = [
133 key for key in self._supported_filters + ['limit'] if getattr(self, key) is not None
134 ]
135 if 'paths' in keys and self.paths == []:
136 keys.remove('paths')
137 return "DeviceSelection({})".format(
138 ', '.join('{}={}'.format(key, repr(getattr(self, key))) for key in keys)
139 )
140
141 def __eq__(self, other: Any) -> bool:
142 return repr(self) == repr(other)
143
144
145 class DriveGroupValidationError(SpecValidationError):
146 """
147 Defining an exception here is a bit problematic, cause you cannot properly catch it,
148 if it was raised in a different mgr module.
149 """
150
151 def __init__(self, name: Optional[str], msg: str):
152 name = name or "<unnamed>"
153 super(DriveGroupValidationError, self).__init__(
154 f'Failed to validate OSD spec "{name}": {msg}')
155
156
157 class DriveGroupSpec(ServiceSpec):
158 """
159 Describe a drive group in the same form that ceph-volume
160 understands.
161 """
162
163 _supported_features = [
164 "encrypted", "block_wal_size", "osds_per_device",
165 "db_slots", "wal_slots", "block_db_size", "placement", "service_id", "service_type",
166 "data_devices", "db_devices", "wal_devices", "journal_devices",
167 "data_directories", "osds_per_device", "objectstore", "osd_id_claims",
168 "journal_size", "unmanaged", "filter_logic", "preview_only", "extra_container_args",
169 "extra_entrypoint_args", "data_allocate_fraction", "method", "crush_device_class", "config",
170 ]
171
172 def __init__(self,
173 placement=None, # type: Optional[PlacementSpec]
174 service_id=None, # type: Optional[str]
175 data_devices=None, # type: Optional[DeviceSelection]
176 db_devices=None, # type: Optional[DeviceSelection]
177 wal_devices=None, # type: Optional[DeviceSelection]
178 journal_devices=None, # type: Optional[DeviceSelection]
179 data_directories=None, # type: Optional[List[str]]
180 osds_per_device=None, # type: Optional[int]
181 objectstore='bluestore', # type: str
182 encrypted=False, # type: bool
183 db_slots=None, # type: Optional[int]
184 wal_slots=None, # type: Optional[int]
185 osd_id_claims=None, # type: Optional[Dict[str, List[str]]]
186 block_db_size=None, # type: Union[int, str, None]
187 block_wal_size=None, # type: Union[int, str, None]
188 journal_size=None, # type: Union[int, str, None]
189 service_type=None, # type: Optional[str]
190 unmanaged=False, # type: bool
191 filter_logic='AND', # type: str
192 preview_only=False, # type: bool
193 extra_container_args=None, # type: Optional[List[str]]
194 extra_entrypoint_args: Optional[List[str]] = None,
195 data_allocate_fraction=None, # type: Optional[float]
196 method=None, # type: Optional[OSDMethod]
197 config=None, # type: Optional[Dict[str, str]]
198 custom_configs=None, # type: Optional[List[CustomConfig]]
199 crush_device_class=None, # type: Optional[str]
200 ):
201 assert service_type is None or service_type == 'osd'
202 super(DriveGroupSpec, self).__init__('osd', service_id=service_id,
203 placement=placement,
204 config=config,
205 unmanaged=unmanaged,
206 preview_only=preview_only,
207 extra_container_args=extra_container_args,
208 extra_entrypoint_args=extra_entrypoint_args,
209 custom_configs=custom_configs)
210
211 #: A :class:`ceph.deployment.drive_group.DeviceSelection`
212 self.data_devices = data_devices
213
214 #: A :class:`ceph.deployment.drive_group.DeviceSelection`
215 self.db_devices = db_devices
216
217 #: A :class:`ceph.deployment.drive_group.DeviceSelection`
218 self.wal_devices = wal_devices
219
220 #: A :class:`ceph.deployment.drive_group.DeviceSelection`
221 self.journal_devices = journal_devices
222
223 #: Set (or override) the "bluestore_block_wal_size" value, in bytes
224 self.block_wal_size: Union[int, str, None] = block_wal_size
225
226 #: Set (or override) the "bluestore_block_db_size" value, in bytes
227 self.block_db_size: Union[int, str, None] = block_db_size
228
229 #: set journal_size in bytes
230 self.journal_size: Union[int, str, None] = journal_size
231
232 #: Number of osd daemons per "DATA" device.
233 #: To fully utilize nvme devices multiple osds are required.
234 #: Can be used to split dual-actuator devices across 2 OSDs, by setting the option to 2.
235 self.osds_per_device = osds_per_device
236
237 #: A list of strings, containing paths which should back OSDs
238 self.data_directories = data_directories
239
240 #: ``filestore`` or ``bluestore``
241 self.objectstore = objectstore
242
243 #: ``true`` or ``false``
244 self.encrypted = encrypted
245
246 #: How many OSDs per DB device
247 self.db_slots = db_slots
248
249 #: How many OSDs per WAL device
250 self.wal_slots = wal_slots
251
252 #: Optional: mapping of host -> List of osd_ids that should be replaced
253 #: See :ref:`orchestrator-osd-replace`
254 self.osd_id_claims = osd_id_claims or dict()
255
256 #: The logic gate we use to match disks with filters.
257 #: defaults to 'AND'
258 self.filter_logic = filter_logic.upper()
259
260 #: If this should be treated as a 'preview' spec
261 self.preview_only = preview_only
262
263 #: Allocate a fraction of the data device (0,1.0]
264 self.data_allocate_fraction = data_allocate_fraction
265
266 self.method = method
267
268 #: Crush device class to assign to OSDs
269 self.crush_device_class = crush_device_class
270
271 @classmethod
272 def _from_json_impl(cls, json_drive_group):
273 # type: (dict) -> DriveGroupSpec
274 """
275 Initialize 'Drive group' structure
276
277 :param json_drive_group: A valid json string with a Drive Group
278 specification
279 """
280 args: Dict[str, Any] = json_drive_group.copy()
281 # legacy json (pre Octopus)
282 if 'host_pattern' in args and 'placement' not in args:
283 args['placement'] = {'host_pattern': args['host_pattern']}
284 del args['host_pattern']
285
286 s_id = args.get('service_id', '<unnamed>')
287
288 # spec: was not mandatory in octopus
289 if 'spec' in args:
290 args['spec'].update(cls._drive_group_spec_from_json(s_id, args['spec']))
291 else:
292 args.update(cls._drive_group_spec_from_json(s_id, args))
293
294 return super(DriveGroupSpec, cls)._from_json_impl(args)
295
296 @classmethod
297 def _drive_group_spec_from_json(cls, name: str, json_drive_group: dict) -> dict:
298 for applied_filter in list(json_drive_group.keys()):
299 if applied_filter not in cls._supported_features:
300 raise DriveGroupValidationError(
301 name,
302 "Feature `{}` is not supported".format(applied_filter))
303
304 try:
305 def to_selection(key: str, vals: dict) -> Optional[DeviceSelection]:
306 try:
307 return DeviceSelection.from_json(vals)
308 except KeyError as e:
309 raise DriveGroupValidationError(
310 f'{name}.{key}',
311 f"Filtering for `{e.args[0]}` is not supported")
312
313 args = {k: (to_selection(k, v) if k.endswith('_devices') else v) for k, v in
314 json_drive_group.items()}
315 if not args:
316 raise DriveGroupValidationError(name, "Didn't find drive selections")
317 return args
318 except (KeyError, TypeError) as e:
319 raise DriveGroupValidationError(name, str(e))
320
321 def validate(self):
322 # type: () -> None
323 super(DriveGroupSpec, self).validate()
324
325 if self.placement.is_empty():
326 raise DriveGroupValidationError(self.service_id, '`placement` required')
327
328 if self.data_devices is None:
329 raise DriveGroupValidationError(self.service_id, "`data_devices` element is required.")
330
331 specs_names = "data_devices db_devices wal_devices journal_devices".split()
332 specs = dict(zip(specs_names, [getattr(self, k) for k in specs_names]))
333 for k, s in [ks for ks in specs.items() if ks[1] is not None]:
334 assert s is not None
335 s.validate(f'{self.service_id}.{k}')
336 for s in filter(None, [self.db_devices, self.wal_devices, self.journal_devices]):
337 if s.all:
338 raise DriveGroupValidationError(
339 self.service_id,
340 "`all` is only allowed for data_devices")
341
342 if self.objectstore not in ('bluestore'):
343 raise DriveGroupValidationError(self.service_id,
344 f"{self.objectstore} is not supported. Must be "
345 f"one of ('bluestore')")
346
347 if self.block_wal_size is not None and type(self.block_wal_size) not in [int, str]:
348 raise DriveGroupValidationError(
349 self.service_id,
350 'block_wal_size must be of type int or string')
351 if self.block_db_size is not None and type(self.block_db_size) not in [int, str]:
352 raise DriveGroupValidationError(
353 self.service_id,
354 'block_db_size must be of type int or string')
355 if self.journal_size is not None and type(self.journal_size) not in [int, str]:
356 raise DriveGroupValidationError(
357 self.service_id,
358 'journal_size must be of type int or string')
359
360 if self.filter_logic not in ['AND', 'OR']:
361 raise DriveGroupValidationError(
362 self.service_id,
363 'filter_logic must be either <AND> or <OR>')
364
365 if self.method not in [None, 'lvm', 'raw']:
366 raise DriveGroupValidationError(
367 self.service_id,
368 'method must be one of None, lvm, raw')
369 if self.method == 'raw' and self.objectstore == 'filestore':
370 raise DriveGroupValidationError(
371 self.service_id,
372 'method raw only supports bluestore')
373
374 if self.data_devices.paths is not None:
375 for device in list(self.data_devices.paths):
376 if not device.path:
377 raise DriveGroupValidationError(self.service_id, 'Device path cannot be empty') # noqa E501
378
379
380 yaml.add_representer(DriveGroupSpec, DriveGroupSpec.yaml_representer)