Debian Codegraph @

src/CedarBackup3/extend/capacity.py

raw
1 # vim: set ft=python ts=4 sw=4 expandtab:
2 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
3 #
4 # C E D A R
5 # S O L U T I O N S "Software done right."
6 # S O F T W A R E
7 #
8 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
9 #
10 # Copyright (c) 2008,2010,2015 Kenneth J. Pronovici.
11 # All rights reserved.
12 #
13 # This program is free software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License,
15 # Version 2, as published by the Free Software Foundation.
16 #
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20 #
21 # Copies of the GNU General Public License are available from
22 # the Free Software Foundation website, http://www.gnu.org/.
23 #
24 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
25 #
26 # Author : Kenneth J. Pronovici <[email protected]>
27 # Language : Python 3
28 # Project : Cedar Backup, release 3
29 # Purpose : Provides an extension to check remaining media capacity.
30 #
31 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
32
33 ########################################################################
34 # Module documentation
35 ########################################################################
36
37 """
38 Provides an extension to check remaining media capacity.
39
40 Some users have asked for advance warning that their media is beginning to fill
41 up. This is an extension that checks the current capacity of the media in the
42 writer, and prints a warning if the media is more than X% full, or has fewer
43 than X bytes of capacity remaining.
44
45 :author: Kenneth J. Pronovici <[email protected]>
46 """
47
48 ########################################################################
49 # Imported modules
50 ########################################################################
51
52 import logging
53 from functools import total_ordering
54
55 from CedarBackup3.actions.util import checkMediaState, createWriter
56 from CedarBackup3.config import ByteQuantity, addByteQuantityNode, readByteQuantity
57 from CedarBackup3.util import displayBytes
58 from CedarBackup3.xmlutil import addContainerNode, addStringNode, createInputDom, readFirstChild, readString
59
60 ########################################################################
61 # Module-wide constants and variables
62 ########################################################################
63
64 logger = logging.getLogger("CedarBackup3.log.extend.capacity")
65
66
67 ########################################################################
68 # Percentage class definition
69 ########################################################################
70
71
72 @total_ordering
73 class PercentageQuantity:
74 """
75 Class representing a percentage quantity.
76
77 The percentage is maintained internally as a string so that issues of
78 precision can be avoided. It really isn't possible to store a floating
79 point number here while being able to losslessly translate back and forth
80 between XML and object representations. (Perhaps the Python 2.4 Decimal
81 class would have been an option, but I originally wanted to stay compatible
82 with Python 2.3.)
83
84 Even though the quantity is maintained as a string, the string must be in a
85 valid floating point positive number. Technically, any floating point
86 string format supported by Python is allowble. However, it does not make
87 sense to have a negative percentage in this context.
88
89 """
90
91 def __init__(self, quantity=None):
92 """
93 Constructor for the ``PercentageQuantity`` class.
94 Args:
95 quantity: Percentage quantity, as a string (i.e. "99.9" or "12")
96 Raises:
97 ValueError: If the quantity value is invaid
98 """
99 self._quantity = None
100 self.quantity = quantity
101
102 def __repr__(self):
103 """
104 Official string representation for class instance.
105 """
106 return "PercentageQuantity(%s)" % (self.quantity)
107
108 def __str__(self):
109 """
110 Informal string representation for class instance.
111 """
112 return self.__repr__()
113
114 def __eq__(self, other):
115 """Equals operator, iplemented in terms of original Python 2 compare operator."""
116 return self.__cmp__(other) == 0
117
118 def __lt__(self, other):
119 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
120 return self.__cmp__(other) < 0
121
122 def __gt__(self, other):
123 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
124 return self.__cmp__(other) > 0
125
126 def __cmp__(self, other):
127 """
128 Original Python 2 comparison operator.
129 Lists within this class are "unordered" for equality comparisons.
130 Args:
131 other: Other object to compare to
132 Returns:
133 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
134 """
135 if other is None:
136 return 1
137 if self.quantity != other.quantity:
138 if float(self.quantity or 0.0) < float(other.quantity or 0.0):
139 return -1
140 else:
141 return 1
142 return 0
143
144 def _setQuantity(self, value):
145 """
146 Property target used to set the quantity
147 The value must be a non-empty string if it is not ``None``.
148 Raises:
149 ValueError: If the value is an empty string
150 ValueError: If the value is not a valid floating point number
151 ValueError: If the value is less than zero
152 """
153 if value is not None:
154 if len(value) < 1:
155 raise ValueError("Percentage must be a non-empty string.")
156 floatValue = float(value)
157 if floatValue < 0.0 or floatValue > 100.0:
158 raise ValueError("Percentage must be a positive value from 0.0 to 100.0")
159 self._quantity = value # keep around string
160
161 def _getQuantity(self):
162 """
163 Property target used to get the quantity.
164 """
165 return self._quantity
166
167 def _getPercentage(self):
168 """
169 Property target used to get the quantity as a floating point number.
170 If there is no quantity set, then a value of 0.0 is returned.
171 """
172 if self.quantity is not None:
173 return float(self.quantity)
174 return 0.0
175
176 quantity = property(_getQuantity, _setQuantity, None, doc="Percentage value, as a string")
177 percentage = property(_getPercentage, None, None, "Percentage value, as a floating point number.")
178
179
180 ########################################################################
181 # CapacityConfig class definition
182 ########################################################################
183
184
185 @total_ordering
186 class CapacityConfig:
187 """
188 Class representing capacity configuration.
189
190 The following restrictions exist on data in this class:
191
192 - The maximum percentage utilized must be a PercentageQuantity
193 - The minimum bytes remaining must be a ByteQuantity
194
195 """
196
197 def __init__(self, maxPercentage=None, minBytes=None):
198 """
199 Constructor for the ``CapacityConfig`` class.
200
201 Args:
202 maxPercentage: Maximum percentage of the media that may be utilized
203 minBytes: Minimum number of free bytes that must be available
204 """
205 self._maxPercentage = None
206 self._minBytes = None
207 self.maxPercentage = maxPercentage
208 self.minBytes = minBytes
209
210 def __repr__(self):
211 """
212 Official string representation for class instance.
213 """
214 return "CapacityConfig(%s, %s)" % (self.maxPercentage, self.minBytes)
215
216 def __str__(self):
217 """
218 Informal string representation for class instance.
219 """
220 return self.__repr__()
221
222 def __eq__(self, other):
223 """Equals operator, iplemented in terms of original Python 2 compare operator."""
224 return self.__cmp__(other) == 0
225
226 def __lt__(self, other):
227 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
228 return self.__cmp__(other) < 0
229
230 def __gt__(self, other):
231 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
232 return self.__cmp__(other) > 0
233
234 def __cmp__(self, other):
235 """
236 Original Python 2 comparison operator.
237 Args:
238 other: Other object to compare to
239 Returns:
240 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
241 """
242 if other is None:
243 return 1
244 if self.maxPercentage != other.maxPercentage:
245 if (self.maxPercentage or PercentageQuantity()) < (other.maxPercentage or PercentageQuantity()):
246 return -1
247 else:
248 return 1
249 if self.minBytes != other.minBytes:
250 if (self.minBytes or ByteQuantity()) < (other.minBytes or ByteQuantity()):
251 return -1
252 else:
253 return 1
254 return 0
255
256 def _setMaxPercentage(self, value):
257 """
258 Property target used to set the maxPercentage value.
259 If not ``None``, the value must be a ``PercentageQuantity`` object.
260 Raises:
261 ValueError: If the value is not a ``PercentageQuantity``
262 """
263 if value is None:
264 self._maxPercentage = None
265 else:
266 if not isinstance(value, PercentageQuantity):
267 raise ValueError("Value must be a ``PercentageQuantity`` object.")
268 self._maxPercentage = value
269
270 def _getMaxPercentage(self):
271 """
272 Property target used to get the maxPercentage value
273 """
274 return self._maxPercentage
275
276 def _setMinBytes(self, value):
277 """
278 Property target used to set the bytes utilized value.
279 If not ``None``, the value must be a ``ByteQuantity`` object.
280 Raises:
281 ValueError: If the value is not a ``ByteQuantity``
282 """
283 if value is None:
284 self._minBytes = None
285 else:
286 if not isinstance(value, ByteQuantity):
287 raise ValueError("Value must be a ``ByteQuantity`` object.")
288 self._minBytes = value
289
290 def _getMinBytes(self):
291 """
292 Property target used to get the bytes remaining value.
293 """
294 return self._minBytes
295
296 maxPercentage = property(_getMaxPercentage, _setMaxPercentage, None, "Maximum percentage of the media that may be utilized.")
297 minBytes = property(_getMinBytes, _setMinBytes, None, "Minimum number of free bytes that must be available.")
298
299
300 ########################################################################
301 # LocalConfig class definition
302 ########################################################################
303
304
305 @total_ordering
306 class LocalConfig:
307 """
308 Class representing this extension's configuration document.
309
310 This is not a general-purpose configuration object like the main Cedar
311 Backup configuration object. Instead, it just knows how to parse and emit
312 specific configuration values to this extension. Third parties who need to
313 read and write configuration related to this extension should access it
314 through the constructor, ``validate`` and ``addConfig`` methods.
315
316 *Note:* Lists within this class are "unordered" for equality comparisons.
317
318 """
319
320 def __init__(self, xmlData=None, xmlPath=None, validate=True):
321 """
322 Initializes a configuration object.
323
324 If you initialize the object without passing either ``xmlData`` or
325 ``xmlPath`` then configuration will be empty and will be invalid until it
326 is filled in properly.
327
328 No reference to the original XML data or original path is saved off by
329 this class. Once the data has been parsed (successfully or not) this
330 original information is discarded.
331
332 Unless the ``validate`` argument is ``False``, the :any:`LocalConfig.validate`
333 method will be called (with its default arguments) against configuration
334 after successfully parsing any passed-in XML. Keep in mind that even if
335 ``validate`` is ``False``, it might not be possible to parse the passed-in
336 XML document if lower-level validations fail.
337
338 *Note:* It is strongly suggested that the ``validate`` option always be set
339 to ``True`` (the default) unless there is a specific need to read in
340 invalid configuration from disk.
341
342 Args:
343 xmlData (String data): XML data representing configuration
344 xmlPath (Absolute path to a file on disk): Path to an XML file on disk
345 validate (Boolean true/false): Validate the document after parsing it
346 Raises:
347 ValueError: If both ``xmlData`` and ``xmlPath`` are passed-in
348 ValueError: If the XML data in ``xmlData`` or ``xmlPath`` cannot be parsed
349 ValueError: If the parsed configuration document is not valid
350 """
351 self._capacity = None
352 self.capacity = None
353 if xmlData is not None and xmlPath is not None:
354 raise ValueError("Use either xmlData or xmlPath, but not both.")
355 if xmlData is not None:
356 self._parseXmlData(xmlData)
357 if validate:
358 self.validate()
359 elif xmlPath is not None:
360 with open(xmlPath) as f:
361 xmlData = f.read()
362 self._parseXmlData(xmlData)
363 if validate:
364 self.validate()
365
366 def __repr__(self):
367 """
368 Official string representation for class instance.
369 """
370 return "LocalConfig(%s)" % (self.capacity)
371
372 def __str__(self):
373 """
374 Informal string representation for class instance.
375 """
376 return self.__repr__()
377
378 def __eq__(self, other):
379 """Equals operator, iplemented in terms of original Python 2 compare operator."""
380 return self.__cmp__(other) == 0
381
382 def __lt__(self, other):
383 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
384 return self.__cmp__(other) < 0
385
386 def __gt__(self, other):
387 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
388 return self.__cmp__(other) > 0
389
390 def __cmp__(self, other):
391 """
392 Original Python 2 comparison operator.
393 Lists within this class are "unordered" for equality comparisons.
394 Args:
395 other: Other object to compare to
396 Returns:
397 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
398 """
399 if other is None:
400 return 1
401 if self.capacity != other.capacity:
402 if self.capacity < other.capacity:
403 return -1
404 else:
405 return 1
406 return 0
407
408 def _setCapacity(self, value):
409 """
410 Property target used to set the capacity configuration value.
411 If not ``None``, the value must be a ``CapacityConfig`` object.
412 Raises:
413 ValueError: If the value is not a ``CapacityConfig``
414 """
415 if value is None:
416 self._capacity = None
417 else:
418 if not isinstance(value, CapacityConfig):
419 raise ValueError("Value must be a ``CapacityConfig`` object.")
420 self._capacity = value
421
422 def _getCapacity(self):
423 """
424 Property target used to get the capacity configuration value.
425 """
426 return self._capacity
427
428 capacity = property(_getCapacity, _setCapacity, None, "Capacity configuration in terms of a ``CapacityConfig`` object.")
429
430 def validate(self):
431 """
432 Validates configuration represented by the object.
433 THere must be either a percentage, or a byte capacity, but not both.
434 Raises:
435 ValueError: If one of the validations fails
436 """
437 if self.capacity is None:
438 raise ValueError("Capacity section is required.")
439 if self.capacity.maxPercentage is None and self.capacity.minBytes is None:
440 raise ValueError("Must provide either max percentage or min bytes.")
441 if self.capacity.maxPercentage is not None and self.capacity.minBytes is not None:
442 raise ValueError("Must provide either max percentage or min bytes, but not both.")
443
444 def addConfig(self, xmlDom, parentNode):
445 """
446 Adds a <capacity> configuration section as the next child of a parent.
447
448 Third parties should use this function to write configuration related to
449 this extension.
450
451 We add the following fields to the document::
452
453 maxPercentage //cb_config/capacity/max_percentage
454 minBytes //cb_config/capacity/min_bytes
455
456 Args:
457 xmlDom: DOM tree as from ``impl.createDocument()``
458 parentNode: Parent that the section should be appended to
459 """
460 if self.capacity is not None:
461 sectionNode = addContainerNode(xmlDom, parentNode, "capacity")
462 LocalConfig._addPercentageQuantity(xmlDom, sectionNode, "max_percentage", self.capacity.maxPercentage)
463 if self.capacity.minBytes is not None: # because utility function fills in empty section on None
464 addByteQuantityNode(xmlDom, sectionNode, "min_bytes", self.capacity.minBytes)
465
466 def _parseXmlData(self, xmlData):
467 """
468 Internal method to parse an XML string into the object.
469
470 This method parses the XML document into a DOM tree (``xmlDom``) and then
471 calls a static method to parse the capacity configuration section.
472
473 Args:
474 xmlData (String data): XML data to be parsed
475 Raises:
476 ValueError: If the XML cannot be successfully parsed
477 """
478 (_, parentNode) = createInputDom(xmlData)
479 self._capacity = LocalConfig._parseCapacity(parentNode)
480
481 @staticmethod
482 def _parseCapacity(parentNode):
483 """
484 Parses a capacity configuration section.
485
486 We read the following fields::
487
488 maxPercentage //cb_config/capacity/max_percentage
489 minBytes //cb_config/capacity/min_bytes
490
491 Args:
492 parentNode: Parent node to search beneath
493
494 Returns:
495 ``CapacityConfig`` object or ``None`` if the section does not exist
496 Raises:
497 ValueError: If some filled-in value is invalid
498 """
499 capacity = None
500 section = readFirstChild(parentNode, "capacity")
501 if section is not None:
502 capacity = CapacityConfig()
503 capacity.maxPercentage = LocalConfig._readPercentageQuantity(section, "max_percentage")
504 capacity.minBytes = readByteQuantity(section, "min_bytes")
505 return capacity
506
507 @staticmethod
508 def _readPercentageQuantity(parent, name):
509 """
510 Read a percentage quantity value from an XML document.
511 Args:
512 parent: Parent node to search beneath
513 name: Name of node to search for
514 Returns:
515 Percentage quantity parsed from XML document
516 """
517 quantity = readString(parent, name)
518 if quantity is None:
519 return None
520 return PercentageQuantity(quantity)
521
522 @staticmethod
523 def _addPercentageQuantity(xmlDom, parentNode, nodeName, percentageQuantity):
524 """
525 Adds a text node as the next child of a parent, to contain a percentage quantity.
526
527 If the ``percentageQuantity`` is None, then no node will be created.
528
529 Args:
530 xmlDom: DOM tree as from ``impl.createDocument()``
531 parentNode: Parent node to create child for
532 nodeName: Name of the new container node
533 percentageQuantity: PercentageQuantity object to put into the XML document
534
535 Returns:
536 Reference to the newly-created node
537 """
538 if percentageQuantity is not None:
539 addStringNode(xmlDom, parentNode, nodeName, percentageQuantity.quantity)
540
541
542 ########################################################################
543 # Public functions
544 ########################################################################
545
546 ###########################
547 # executeAction() function
548 ###########################
549
550
551 def executeAction(configPath, options, config): # ruff: ignore[unused-function-argument]
552 """
553 Executes the capacity action.
554
555 Args:
556 configPath (String representing a path on disk): Path to configuration file on disk
557 options (Options object): Program command-line options
558 config (Config object): Program configuration
559 Raises:
560 ValueError: Under many generic error conditions
561 IOError: If there are I/O problems reading or writing files
562 """
563 logger.debug("Executing capacity extended action.")
564 if config.options is None or config.store is None:
565 raise ValueError("Cedar Backup configuration is not properly filled in.")
566 local = LocalConfig(xmlPath=configPath)
567 if config.store.checkMedia:
568 checkMediaState(config.store) # raises exception if media is not initialized
569 capacity = createWriter(config).retrieveCapacity()
570 logger.debug("Media capacity: %s", capacity)
571 if local.capacity.maxPercentage is not None:
572 if capacity.utilized > local.capacity.maxPercentage.percentage:
573 logger.error(
574 "Media has reached capacity limit of %s%%: %.2f%% utilized",
575 local.capacity.maxPercentage.quantity,
576 capacity.utilized,
577 )
578 else:
579 if capacity.bytesAvailable < local.capacity.minBytes:
580 logger.error(
581 "Media has reached capacity limit of %s: only %s available",
582 local.capacity.minBytes,
583 displayBytes(capacity.bytesAvailable),
584 )
585 logger.info("Executed the capacity extended action successfully.")