Debian Codegraph @

src/CedarBackup3/extend/mysql.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) 2005,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 : Official Cedar Backup Extensions
29 # Purpose : Provides an extension to back up MySQL databases.
30 #
31 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
32
33 ########################################################################
34 # Module documentation
35 ########################################################################
36
37 """
38 Provides an extension to back up MySQL databases.
39
40 This is a Cedar Backup extension used to back up MySQL databases via the Cedar
41 Backup command line. It requires a new configuration section <mysql> and is
42 intended to be run either immediately before or immediately after the standard
43 collect action. Aside from its own configuration, it requires the options and
44 collect configuration sections in the standard Cedar Backup configuration file.
45
46 The backup is done via the ``mysqldump`` command included with the MySQL
47 product. Output can be compressed using ``gzip`` or ``bzip2``. Administrators
48 can configure the extension either to back up all databases or to back up only
49 specific databases. Note that this code always produces a full backup. There
50 is currently no facility for making incremental backups. If/when someone has a
51 need for this and can describe how to do it, I'll update this extension or
52 provide another.
53
54 The extension assumes that all configured databases can be backed up by a
55 single user. Often, the "root" database user will be used. An alternative is
56 to create a separate MySQL "backup" user and grant that user rights to read
57 (but not write) various databases as needed. This second option is probably
58 the best choice.
59
60 The extension accepts a username and password in configuration. However, you
61 probably do not want to provide those values in Cedar Backup configuration.
62 This is because Cedar Backup will provide these values to ``mysqldump`` via the
63 command-line ``--user`` and ``--password`` switches, which will be visible to
64 other users in the process listing.
65
66 Instead, you should configure the username and password in one of MySQL's
67 configuration files. Typically, that would be done by putting a stanza like
68 this in ``/root/.my.cnf``::
69
70 [mysqldump]
71 user = root
72 password = <secret>
73
74 Regardless of whether you are using ``~/.my.cnf`` or ``/etc/cback3.conf`` to store
75 database login and password information, you should be careful about who is
76 allowed to view that information. Typically, this means locking down
77 permissions so that only the file owner can read the file contents (i.e. use
78 mode ``0600``).
79
80 :author: Kenneth J. Pronovici <[email protected]>
81 """
82
83 ########################################################################
84 # Imported modules
85 ########################################################################
86
87 import logging
88 import os
89 from bz2 import BZ2File
90 from functools import total_ordering
91 from gzip import GzipFile
92
93 from CedarBackup3.config import VALID_COMPRESS_MODES
94 from CedarBackup3.util import ObjectTypeList, changeOwnership, executeCommand, pathJoin, resolveCommand
95 from CedarBackup3.xmlutil import (
96 addBooleanNode,
97 addContainerNode,
98 addStringNode,
99 createInputDom,
100 readBoolean,
101 readFirstChild,
102 readString,
103 readStringList,
104 )
105
106 ########################################################################
107 # Module-wide constants and variables
108 ########################################################################
109
110 logger = logging.getLogger("CedarBackup3.log.extend.mysql")
111 MYSQLDUMP_COMMAND = ["mysqldump"]
112
113
114 ########################################################################
115 # MysqlConfig class definition
116 ########################################################################
117
118
119 @total_ordering
120 class MysqlConfig:
121 """
122 Class representing MySQL configuration.
123
124 The MySQL configuration information is used for backing up MySQL databases.
125
126 The following restrictions exist on data in this class:
127
128 - The compress mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
129 - The 'all' flag must be 'Y' if no databases are defined.
130 - The 'all' flag must be 'N' if any databases are defined.
131 - Any values in the databases list must be strings.
132
133 """
134
135 def __init__(self, user=None, password=None, compressMode=None, all=None, databases=None): # ruff: ignore[builtin-argument-shadowing]
136 """
137 Constructor for the ``MysqlConfig`` class.
138
139 Args:
140 user: User to execute backup as
141 password: Password associated with user
142 compressMode: Compress mode for backed-up files
143 all: Indicates whether to back up all databases
144 databases: List of databases to back up
145 """
146 self._user = None
147 self._password = None
148 self._compressMode = None
149 self._all = None
150 self._databases = None
151 self.user = user
152 self.password = password
153 self.compressMode = compressMode
154 self.all = all
155 self.databases = databases
156
157 def __repr__(self):
158 """
159 Official string representation for class instance.
160 """
161 return "MysqlConfig(%s, %s, %s, %s)" % (self.user, self.password, self.all, self.databases)
162
163 def __str__(self):
164 """
165 Informal string representation for class instance.
166 """
167 return self.__repr__()
168
169 def __eq__(self, other):
170 """Equals operator, iplemented in terms of original Python 2 compare operator."""
171 return self.__cmp__(other) == 0
172
173 def __lt__(self, other):
174 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
175 return self.__cmp__(other) < 0
176
177 def __gt__(self, other):
178 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
179 return self.__cmp__(other) > 0
180
181 def __cmp__(self, other):
182 """
183 Original Python 2 comparison operator.
184 Args:
185 other: Other object to compare to
186 Returns:
187 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
188 """
189 if other is None:
190 return 1
191 if self.user != other.user:
192 if str(self.user or "") < str(other.user or ""):
193 return -1
194 else:
195 return 1
196 if self.password != other.password:
197 if str(self.password or "") < str(other.password or ""):
198 return -1
199 else:
200 return 1
201 if self.compressMode != other.compressMode:
202 if str(self.compressMode or "") < str(other.compressMode or ""):
203 return -1
204 else:
205 return 1
206 if self.all != other.all:
207 if self.all < other.all:
208 return -1
209 else:
210 return 1
211 if self.databases != other.databases:
212 if self.databases < other.databases:
213 return -1
214 else:
215 return 1
216 return 0
217
218 def _setUser(self, value):
219 """
220 Property target used to set the user value.
221 """
222 if value is not None:
223 if len(value) < 1:
224 raise ValueError("User must be non-empty string.")
225 self._user = value
226
227 def _getUser(self):
228 """
229 Property target used to get the user value.
230 """
231 return self._user
232
233 def _setPassword(self, value):
234 """
235 Property target used to set the password value.
236 """
237 if value is not None:
238 if len(value) < 1:
239 raise ValueError("Password must be non-empty string.")
240 self._password = value
241
242 def _getPassword(self):
243 """
244 Property target used to get the password value.
245 """
246 return self._password
247
248 def _setCompressMode(self, value):
249 """
250 Property target used to set the compress mode.
251 If not ``None``, the mode must be one of the values in :any:`VALID_COMPRESS_MODES`.
252 Raises:
253 ValueError: If the value is not valid
254 """
255 if value is not None:
256 if value not in VALID_COMPRESS_MODES:
257 raise ValueError("Compress mode must be one of %s." % VALID_COMPRESS_MODES)
258 self._compressMode = value
259
260 def _getCompressMode(self):
261 """
262 Property target used to get the compress mode.
263 """
264 return self._compressMode
265
266 def _setAll(self, value):
267 """
268 Property target used to set the 'all' flag.
269 No validations, but we normalize the value to ``True`` or ``False``.
270 """
271 if value:
272 self._all = True
273 else:
274 self._all = False
275
276 def _getAll(self):
277 """
278 Property target used to get the 'all' flag.
279 """
280 return self._all
281
282 def _setDatabases(self, value):
283 """
284 Property target used to set the databases list.
285 Either the value must be ``None`` or each element must be a string.
286 Raises:
287 ValueError: If the value is not a string
288 """
289 if value is None:
290 self._databases = None
291 else:
292 for database in value:
293 if len(database) < 1:
294 raise ValueError("Each database must be a non-empty string.")
295 try:
296 saved = self._databases
297 self._databases = ObjectTypeList(str, "string")
298 self._databases.extend(value)
299 except Exception as e:
300 self._databases = saved
301 raise e
302
303 def _getDatabases(self):
304 """
305 Property target used to get the databases list.
306 """
307 return self._databases
308
309 user = property(_getUser, _setUser, None, "User to execute backup as.")
310 password = property(_getPassword, _setPassword, None, "Password associated with user.")
311 compressMode = property(_getCompressMode, _setCompressMode, None, "Compress mode to be used for backed-up files.")
312 all = property(_getAll, _setAll, None, "Indicates whether to back up all databases.")
313 databases = property(_getDatabases, _setDatabases, None, "List of databases to back up.")
314
315
316 ########################################################################
317 # LocalConfig class definition
318 ########################################################################
319
320
321 @total_ordering
322 class LocalConfig:
323 """
324 Class representing this extension's configuration document.
325
326 This is not a general-purpose configuration object like the main Cedar
327 Backup configuration object. Instead, it just knows how to parse and emit
328 MySQL-specific configuration values. Third parties who need to read and
329 write configuration related to this extension should access it through the
330 constructor, ``validate`` and ``addConfig`` methods.
331
332 *Note:* Lists within this class are "unordered" for equality comparisons.
333
334 """
335
336 def __init__(self, xmlData=None, xmlPath=None, validate=True):
337 """
338 Initializes a configuration object.
339
340 If you initialize the object without passing either ``xmlData`` or
341 ``xmlPath`` then configuration will be empty and will be invalid until it
342 is filled in properly.
343
344 No reference to the original XML data or original path is saved off by
345 this class. Once the data has been parsed (successfully or not) this
346 original information is discarded.
347
348 Unless the ``validate`` argument is ``False``, the :any:`LocalConfig.validate`
349 method will be called (with its default arguments) against configuration
350 after successfully parsing any passed-in XML. Keep in mind that even if
351 ``validate`` is ``False``, it might not be possible to parse the passed-in
352 XML document if lower-level validations fail.
353
354 *Note:* It is strongly suggested that the ``validate`` option always be set
355 to ``True`` (the default) unless there is a specific need to read in
356 invalid configuration from disk.
357
358 Args:
359 xmlData (String data): XML data representing configuration
360 xmlPath (Absolute path to a file on disk): Path to an XML file on disk
361 validate (Boolean true/false): Validate the document after parsing it
362 Raises:
363 ValueError: If both ``xmlData`` and ``xmlPath`` are passed-in
364 ValueError: If the XML data in ``xmlData`` or ``xmlPath`` cannot be parsed
365 ValueError: If the parsed configuration document is not valid
366 """
367 self._mysql = None
368 self.mysql = None
369 if xmlData is not None and xmlPath is not None:
370 raise ValueError("Use either xmlData or xmlPath, but not both.")
371 if xmlData is not None:
372 self._parseXmlData(xmlData)
373 if validate:
374 self.validate()
375 elif xmlPath is not None:
376 with open(xmlPath) as f:
377 xmlData = f.read()
378 self._parseXmlData(xmlData)
379 if validate:
380 self.validate()
381
382 def __repr__(self):
383 """
384 Official string representation for class instance.
385 """
386 return "LocalConfig(%s)" % (self.mysql)
387
388 def __str__(self):
389 """
390 Informal string representation for class instance.
391 """
392 return self.__repr__()
393
394 def __eq__(self, other):
395 """Equals operator, iplemented in terms of original Python 2 compare operator."""
396 return self.__cmp__(other) == 0
397
398 def __lt__(self, other):
399 """Less-than operator, iplemented in terms of original Python 2 compare operator."""
400 return self.__cmp__(other) < 0
401
402 def __gt__(self, other):
403 """Greater-than operator, iplemented in terms of original Python 2 compare operator."""
404 return self.__cmp__(other) > 0
405
406 def __cmp__(self, other):
407 """
408 Original Python 2 comparison operator.
409 Lists within this class are "unordered" for equality comparisons.
410 Args:
411 other: Other object to compare to
412 Returns:
413 -1/0/1 depending on whether self is ``<``, ``=`` or ``>`` other
414 """
415 if other is None:
416 return 1
417 if self.mysql != other.mysql:
418 if self.mysql < other.mysql:
419 return -1
420 else:
421 return 1
422 return 0
423
424 def _setMysql(self, value):
425 """
426 Property target used to set the mysql configuration value.
427 If not ``None``, the value must be a ``MysqlConfig`` object.
428 Raises:
429 ValueError: If the value is not a ``MysqlConfig``
430 """
431 if value is None:
432 self._mysql = None
433 else:
434 if not isinstance(value, MysqlConfig):
435 raise ValueError("Value must be a ``MysqlConfig`` object.")
436 self._mysql = value
437
438 def _getMysql(self):
439 """
440 Property target used to get the mysql configuration value.
441 """
442 return self._mysql
443
444 mysql = property(_getMysql, _setMysql, None, "Mysql configuration in terms of a ``MysqlConfig`` object.")
445
446 def validate(self):
447 """
448 Validates configuration represented by the object.
449
450 The compress mode must be filled in. Then, if the 'all' flag *is* set,
451 no databases are allowed, and if the 'all' flag is *not* set, at least
452 one database is required.
453
454 Raises:
455 ValueError: If one of the validations fails
456 """
457 if self.mysql is None:
458 raise ValueError("Mysql section is required.")
459 if self.mysql.compressMode is None:
460 raise ValueError("Compress mode value is required.")
461 if self.mysql.all:
462 if self.mysql.databases is not None and self.mysql.databases != []:
463 raise ValueError("Databases cannot be specified if 'all' flag is set.")
464 else:
465 if self.mysql.databases is None or len(self.mysql.databases) < 1:
466 raise ValueError("At least one MySQL database must be indicated if 'all' flag is not set.")
467
468 def addConfig(self, xmlDom, parentNode):
469 """
470 Adds a <mysql> configuration section as the next child of a parent.
471
472 Third parties should use this function to write configuration related to
473 this extension.
474
475 We add the following fields to the document::
476
477 user //cb_config/mysql/user
478 password //cb_config/mysql/password
479 compressMode //cb_config/mysql/compress_mode
480 all //cb_config/mysql/all
481
482 We also add groups of the following items, one list element per
483 item::
484
485 database //cb_config/mysql/database
486
487 Args:
488 xmlDom: DOM tree as from ``impl.createDocument()``
489 parentNode: Parent that the section should be appended to
490 """
491 if self.mysql is not None:
492 sectionNode = addContainerNode(xmlDom, parentNode, "mysql")
493 addStringNode(xmlDom, sectionNode, "user", self.mysql.user)
494 addStringNode(xmlDom, sectionNode, "password", self.mysql.password)
495 addStringNode(xmlDom, sectionNode, "compress_mode", self.mysql.compressMode)
496 addBooleanNode(xmlDom, sectionNode, "all", self.mysql.all)
497 if self.mysql.databases is not None:
498 for database in self.mysql.databases:
499 addStringNode(xmlDom, sectionNode, "database", database)
500
501 def _parseXmlData(self, xmlData):
502 """
503 Internal method to parse an XML string into the object.
504
505 This method parses the XML document into a DOM tree (``xmlDom``) and then
506 calls a static method to parse the mysql configuration section.
507
508 Args:
509 xmlData (String data): XML data to be parsed
510 Raises:
511 ValueError: If the XML cannot be successfully parsed
512 """
513 (_, parentNode) = createInputDom(xmlData)
514 self._mysql = LocalConfig._parseMysql(parentNode)
515
516 @staticmethod
517 def _parseMysql(parentNode):
518 """
519 Parses a mysql configuration section.
520
521 We read the following fields::
522
523 user //cb_config/mysql/user
524 password //cb_config/mysql/password
525 compressMode //cb_config/mysql/compress_mode
526 all //cb_config/mysql/all
527
528 We also read groups of the following item, one list element per
529 item::
530
531 databases //cb_config/mysql/database
532
533 Args:
534 parentNode: Parent node to search beneath
535
536 Returns:
537 ``MysqlConfig`` object or ``None`` if the section does not exist
538 Raises:
539 ValueError: If some filled-in value is invalid
540 """
541 mysql = None
542 section = readFirstChild(parentNode, "mysql")
543 if section is not None:
544 mysql = MysqlConfig()
545 mysql.user = readString(section, "user")
546 mysql.password = readString(section, "password")
547 mysql.compressMode = readString(section, "compress_mode")
548 mysql.all = readBoolean(section, "all")
549 mysql.databases = readStringList(section, "database")
550 return mysql
551
552
553 ########################################################################
554 # Public functions
555 ########################################################################
556
557 ###########################
558 # executeAction() function
559 ###########################
560
561
562 def executeAction(configPath, options, config): # ruff: ignore[unused-function-argument]
563 """
564 Executes the MySQL backup action.
565
566 Args:
567 configPath (String representing a path on disk): Path to configuration file on disk
568 options (Options object): Program command-line options
569 config (Config object): Program configuration
570 Raises:
571 ValueError: Under many generic error conditions
572 IOError: If a backup could not be written for some reason
573 """
574 logger.debug("Executing MySQL extended action.")
575 if config.options is None or config.collect is None:
576 raise ValueError("Cedar Backup configuration is not properly filled in.")
577 local = LocalConfig(xmlPath=configPath)
578 if local.mysql.all:
579 logger.info("Backing up all databases.")
580 _backupDatabase(
581 config.collect.targetDir,
582 local.mysql.compressMode,
583 local.mysql.user,
584 local.mysql.password,
585 config.options.backupUser,
586 config.options.backupGroup,
587 None,
588 )
589 else:
590 logger.debug("Backing up %d individual databases.", len(local.mysql.databases))
591 for database in local.mysql.databases:
592 logger.info("Backing up database [%s].", database)
593 _backupDatabase(
594 config.collect.targetDir,
595 local.mysql.compressMode,
596 local.mysql.user,
597 local.mysql.password,
598 config.options.backupUser,
599 config.options.backupGroup,
600 database,
601 )
602 logger.info("Executed the MySQL extended action successfully.")
603
604
605 def _backupDatabase(targetDir, compressMode, user, password, backupUser, backupGroup, database=None):
606 """
607 Backs up an individual MySQL database, or all databases.
608
609 This internal method wraps the public method and adds some functionality,
610 like figuring out a filename, etc.
611
612 Args:
613 targetDir: Directory into which backups should be written
614 compressMode: Compress mode to be used for backed-up files
615 user: User to use for connecting to the database (if any)
616 password: Password associated with user (if any)
617 backupUser: User to own resulting file
618 backupGroup: Group to own resulting file
619 database: Name of database, or ``None`` for all databases
620
621 Returns:
622 Name of the generated backup file
623
624 Raises:
625 ValueError: If some value is missing or invalid
626 IOError: If there is a problem executing the MySQL dump
627 """
628 (outputFile, filename) = _getOutputFile(targetDir, database, compressMode)
629 with outputFile:
630 backupDatabase(user, password, outputFile, database)
631 if not os.path.exists(filename):
632 raise OSError("Dump file [%s] does not seem to exist after backup completed." % filename)
633 changeOwnership(filename, backupUser, backupGroup)
634
635
636 def _getOutputFile(targetDir, database, compressMode):
637 """
638 Opens the output file used for saving the MySQL dump.
639
640 The filename is either ``"mysqldump.txt"`` or ``"mysqldump-<database>.txt"``. The
641 ``".bz2"`` extension is added if ``compress`` is ``True``.
642
643 Args:
644 targetDir: Target directory to write file in
645 database: Name of the database (if any)
646 compressMode: Compress mode to be used for backed-up files
647
648 Returns:
649 Tuple of (Output file object, filename), file opened in binary mode for use with executeCommand()
650 """
651 if database is None:
652 filename = pathJoin(targetDir, "mysqldump.txt")
653 else:
654 filename = pathJoin(targetDir, "mysqldump-%s.txt" % database)
655 if compressMode == "gzip":
656 filename = "%s.gz" % filename
657 outputFile = GzipFile(filename, "wb")
658 elif compressMode == "bzip2":
659 filename = "%s.bz2" % filename
660 outputFile = BZ2File(filename, "wb")
661 else:
662 outputFile = open(filename, "wb")
663 logger.debug("MySQL dump file will be [%s].", filename)
664 return (outputFile, filename)
665
666
667 ############################
668 # backupDatabase() function
669 ############################
670
671
672 def backupDatabase(user, password, backupFile, database=None):
673 """
674 Backs up an individual MySQL database, or all databases.
675
676 This function backs up either a named local MySQL database or all local
677 MySQL databases, using the passed-in user and password (if provided) for
678 connectivity. This function call *always* results a full backup. There is
679 no facility for incremental backups.
680
681 The backup data will be written into the passed-in backup file. Normally,
682 this would be an object as returned from ``open``, but it is possible to
683 use something like a ``GzipFile`` to write compressed output. The caller is
684 responsible for closing the passed-in backup file.
685
686 Often, the "root" database user will be used when backing up all databases.
687 An alternative is to create a separate MySQL "backup" user and grant that
688 user rights to read (but not write) all of the databases that will be backed
689 up.
690
691 This function accepts a username and password. However, you probably do not
692 want to pass those values in. This is because they will be provided to
693 ``mysqldump`` via the command-line ``--user`` and ``--password`` switches,
694 which will be visible to other users in the process listing.
695
696 Instead, you should configure the username and password in one of MySQL's
697 configuration files. Typically, this would be done by putting a stanza like
698 this in ``/root/.my.cnf``, to provide ``mysqldump`` with the root database
699 username and its password::
700
701 [mysqldump]
702 user = root
703 password = <secret>
704
705 If you are executing this function as some system user other than root, then
706 the ``.my.cnf`` file would be placed in the home directory of that user. In
707 either case, make sure to set restrictive permissions (typically, mode
708 ``0600``) on ``.my.cnf`` to make sure that other users cannot read the file.
709
710 Args:
711 user (String representing MySQL username, or ``None``): User to use for connecting to the database (if any)
712 password (String representing MySQL password, or ``None``): Password associated with user (if any)
713 backupFile (Python file object as from ``open`` or ``file``): File use for writing backup
714 database (String representing database name, or ``None`` for all databases): Name of the database to be backed up
715 Raises:
716 ValueError: If some value is missing or invalid
717 IOError: If there is a problem executing the MySQL dump
718 """
719 args = ["-all", "--flush-logs", "--opt"]
720 if user is not None:
721 logger.warning("Warning: MySQL username will be visible in process listing (consider using ~/.my.cnf).")
722 args.append("--user=%s" % user)
723 if password is not None:
724 logger.warning("Warning: MySQL password will be visible in process listing (consider using ~/.my.cnf).")
725 args.append("--password=%s" % password)
726 if database is None:
727 args.insert(0, "--all-databases")
728 else:
729 args.insert(0, "--databases")
730 args.append(database)
731 command = resolveCommand(MYSQLDUMP_COMMAND)
732 result = executeCommand(command, args, returnOutput=False, ignoreStderr=True, doNotLog=True, outputFile=backupFile)[0]
733 if result != 0:
734 if database is None:
735 raise OSError("Error [%d] executing MySQL database dump for all databases." % result)
736 else:
737 raise OSError("Error [%d] executing MySQL database dump for database [%s]." % (result, database))