Debian Codegraph @

src/CedarBackup3/extend/sysinfo.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 save off important system recovery information.
30 #
31 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
32
33 ########################################################################
34 # Module documentation
35 ########################################################################
36
37 """
38 Provides an extension to save off important system recovery information.
39
40 This is a simple Cedar Backup extension used to save off important system
41 recovery information. It saves off three types of information:
42
43 - Currently-installed Debian packages via ``dpkg --get-selections``
44 - Disk partition information via ``fdisk -l``
45 - System-wide mounted filesystem contents, via ``ls -laR``
46
47 The saved-off information is placed into the collect directory and is
48 compressed using ``bzip2`` to save space.
49
50 This extension relies on the options and collect configurations in the standard
51 Cedar Backup configuration file, but requires no new configuration of its own.
52 No public functions other than the action are exposed since all of this is
53 pretty simple.
54
55 *Note:* If the ``dpkg`` or ``fdisk`` commands cannot be found in their normal
56 locations or executed by the current user, those steps will be skipped and a
57 note will be logged at the INFO level.
58
59 :author: Kenneth J. Pronovici <[email protected]>
60 """
61
62 ########################################################################
63 # Imported modules
64 ########################################################################
65
66 import logging
67 import os
68 from bz2 import BZ2File
69
70 from CedarBackup3.util import changeOwnership, executeCommand, pathJoin, resolveCommand
71
72 ########################################################################
73 # Module-wide constants and variables
74 ########################################################################
75
76 logger = logging.getLogger("CedarBackup3.log.extend.sysinfo")
77
78 DPKG_PATH = "/usr/bin/dpkg"
79 FDISK_PATH = "/sbin/fdisk"
80
81 DPKG_COMMAND = [DPKG_PATH, "--get-selections"]
82 FDISK_COMMAND = [FDISK_PATH, "-l"]
83 LS_COMMAND = ["ls", "-laR", "/"]
84
85
86 ########################################################################
87 # Public functions
88 ########################################################################
89
90 ###########################
91 # executeAction() function
92 ###########################
93
94
95 def executeAction(configPath, options, config): # ruff: ignore[unused-function-argument]
96 """
97 Executes the sysinfo backup action.
98
99 Args:
100 configPath (String representing a path on disk): Path to configuration file on disk
101 options (Options object): Program command-line options
102 config (Config object): Program configuration
103 Raises:
104 ValueError: Under many generic error conditions
105 IOError: If the backup process fails for some reason
106 """
107 logger.debug("Executing sysinfo extended action.")
108 if config.options is None or config.collect is None:
109 raise ValueError("Cedar Backup configuration is not properly filled in.")
110 _dumpDebianPackages(config.collect.targetDir, config.options.backupUser, config.options.backupGroup)
111 _dumpPartitionTable(config.collect.targetDir, config.options.backupUser, config.options.backupGroup)
112 _dumpFilesystemContents(config.collect.targetDir, config.options.backupUser, config.options.backupGroup)
113 logger.info("Executed the sysinfo extended action successfully.")
114
115
116 def _dumpDebianPackages(targetDir, backupUser, backupGroup, compress=True):
117 """
118 Dumps a list of currently installed Debian packages via ``dpkg``.
119 Args:
120 targetDir: Directory to write output file into
121 backupUser: User which should own the resulting file
122 backupGroup: Group which should own the resulting file
123 compress: Indicates whether to compress the output file
124 Raises:
125 IOError: If the dump fails for some reason
126 """
127 if not os.path.exists(DPKG_PATH):
128 logger.info("Not executing Debian package dump since %s doesn't seem to exist.", DPKG_PATH)
129 elif not os.access(DPKG_PATH, os.X_OK):
130 logger.info("Not executing Debian package dump since %s cannot be executed.", DPKG_PATH)
131 else:
132 (outputFile, filename) = _getOutputFile(targetDir, "dpkg-selections", compress)
133 with outputFile:
134 command = resolveCommand(DPKG_COMMAND)
135 result = executeCommand(command, [], returnOutput=False, ignoreStderr=True, doNotLog=True, outputFile=outputFile)[0]
136 if result != 0:
137 raise OSError("Error [%d] executing Debian package dump." % result)
138 if not os.path.exists(filename):
139 raise OSError("File [%s] does not seem to exist after Debian package dump finished." % filename)
140 changeOwnership(filename, backupUser, backupGroup)
141
142
143 def _dumpPartitionTable(targetDir, backupUser, backupGroup, compress=True):
144 """
145 Dumps information about the partition table via ``fdisk``.
146 Args:
147 targetDir: Directory to write output file into
148 backupUser: User which should own the resulting file
149 backupGroup: Group which should own the resulting file
150 compress: Indicates whether to compress the output file
151 Raises:
152 IOError: If the dump fails for some reason
153 """
154 if not os.path.exists(FDISK_PATH):
155 logger.info("Not executing partition table dump since %s doesn't seem to exist.", FDISK_PATH)
156 elif not os.access(FDISK_PATH, os.X_OK):
157 logger.info("Not executing partition table dump since %s cannot be executed.", FDISK_PATH)
158 else:
159 (outputFile, filename) = _getOutputFile(targetDir, "fdisk-l", compress)
160 with outputFile:
161 command = resolveCommand(FDISK_COMMAND)
162 result = executeCommand(command, [], returnOutput=False, ignoreStderr=True, outputFile=outputFile)[0]
163 if result != 0:
164 raise OSError("Error [%d] executing partition table dump." % result)
165 if not os.path.exists(filename):
166 raise OSError("File [%s] does not seem to exist after partition table dump finished." % filename)
167 changeOwnership(filename, backupUser, backupGroup)
168
169
170 def _dumpFilesystemContents(targetDir, backupUser, backupGroup, compress=True):
171 """
172 Dumps complete listing of filesystem contents via ``ls -laR``.
173 Args:
174 targetDir: Directory to write output file into
175 backupUser: User which should own the resulting file
176 backupGroup: Group which should own the resulting file
177 compress: Indicates whether to compress the output file
178 Raises:
179 IOError: If the dump fails for some reason
180 """
181 (outputFile, filename) = _getOutputFile(targetDir, "ls-laR", compress)
182 with outputFile:
183 # Note: can't count on return status from 'ls', so we don't check it.
184 command = resolveCommand(LS_COMMAND)
185 executeCommand(command, [], returnOutput=False, ignoreStderr=True, doNotLog=True, outputFile=outputFile)
186 if not os.path.exists(filename):
187 raise OSError("File [%s] does not seem to exist after filesystem contents dump finished." % filename)
188 changeOwnership(filename, backupUser, backupGroup)
189
190
191 def _getOutputFile(targetDir, name, compress=True):
192 """
193 Opens the output file used for saving a dump to the filesystem.
194
195 The filename will be ``name.txt`` (or ``name.txt.bz2`` if ``compress`` is
196 ``True``), written in the target directory.
197
198 Args:
199 targetDir: Target directory to write file in
200 name: Name of the file to create
201 compress: Indicates whether to write compressed output
202
203 Returns:
204 Tuple of (Output file object, filename), file opened in binary mode for use with executeCommand()
205 """
206 filename = pathJoin(targetDir, "%s.txt" % name)
207 if compress:
208 filename = "%s.bz2" % filename
209 logger.debug("Dump file will be [%s].", filename)
210 if compress:
211 outputFile = BZ2File(filename, "wb")
212 else:
213 outputFile = open(filename, "wb")
214 return (outputFile, filename)