Debian Codegraph @

src/CedarBackup3/actions/stage.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) 2004-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 : Implements the standard 'stage' action.
30 #
31 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
32
33 ########################################################################
34 # Module documentation
35 ########################################################################
36
37 """
38 Implements the standard 'stage' action.
39 :author: Kenneth J. Pronovici <[email protected]>
40 """
41
42
43 ########################################################################
44 # Imported modules
45 ########################################################################
46
47 import logging
48 import os
49 import time
50
51 from CedarBackup3.actions.constants import DIR_TIME_FORMAT, STAGE_INDICATOR
52 from CedarBackup3.actions.util import writeIndicatorFile
53 from CedarBackup3.peer import LocalPeer, RemotePeer
54 from CedarBackup3.util import changeOwnership, getUidGid, isRunningAsRoot, isStartOfWeek, pathJoin
55
56 ########################################################################
57 # Module-wide constants and variables
58 ########################################################################
59
60 logger = logging.getLogger("CedarBackup3.log.actions.stage")
61
62
63 ########################################################################
64 # Public functions
65 ########################################################################
66
67 ##########################
68 # executeStage() function
69 ##########################
70
71
72 # noinspection PyTypeChecker
73 def executeStage(configPath, options, config): # ruff: ignore[unused-function-argument]
74 """
75 Executes the stage backup action.
76
77 *Note:* The daily directory is derived once and then we stick with it, just
78 in case a backup happens to span midnite.
79
80 *Note:* As portions of the stage action is complete, we will write various
81 indicator files so that it's obvious what actions have been completed. Each
82 peer gets a stage indicator in its collect directory, and then the master
83 gets a stage indicator in its daily staging directory. The store process
84 uses the master's stage indicator to decide whether a directory is ready to
85 be stored. Currently, nothing uses the indicator at each peer, and it
86 exists for reference only.
87
88 Args:
89 configPath (String representing a path on disk): Path to configuration file on disk
90 options (Options object): Program command-line options
91 config (Config object): Program configuration
92 Raises:
93 ValueError: Under many generic error conditions
94 IOError: If there are problems reading or writing files
95 """
96 logger.debug("Executing the 'stage' action.")
97 if config.options is None or config.stage is None:
98 raise ValueError("Stage configuration is not properly filled in.")
99 dailyDir = _getDailyDir(config)
100 localPeers = _getLocalPeers(config)
101 remotePeers = _getRemotePeers(config)
102 allPeers = localPeers + remotePeers
103 stagingDirs = _createStagingDirs(config, dailyDir, allPeers)
104 for peer in allPeers:
105 logger.info("Staging peer [%s].", peer.name)
106 ignoreFailures = _getIgnoreFailuresFlag(options, config, peer)
107 if not peer.checkCollectIndicator():
108 if not ignoreFailures:
109 logger.error("Peer [%s] was not ready to be staged.", peer.name)
110 else:
111 logger.info("Peer [%s] was not ready to be staged.", peer.name)
112 continue
113 logger.debug("Found collect indicator.")
114 targetDir = stagingDirs[peer.name]
115 if isRunningAsRoot():
116 # Since we're running as root, we can change ownership
117 ownership = getUidGid(config.options.backupUser, config.options.backupGroup)
118 logger.debug("Using target dir [%s], ownership [%d:%d].", targetDir, ownership[0], ownership[1])
119 else:
120 # Non-root cannot change ownership, so don't set it
121 ownership = None
122 logger.debug("Using target dir [%s], ownership [None].", targetDir)
123 try:
124 count = peer.stagePeer(targetDir=targetDir, ownership=ownership) # note: utilize effective user's default umask
125 logger.info("Staged %d files for peer [%s].", count, peer.name)
126 peer.writeStageIndicator()
127 except (ValueError, OSError) as e:
128 logger.error("Error staging [%s]: %s", peer.name, e)
129 writeIndicatorFile(dailyDir, STAGE_INDICATOR, config.options.backupUser, config.options.backupGroup)
130 logger.info("Executed the 'stage' action successfully.")
131
132
133 ########################################################################
134 # Private utility functions
135 ########################################################################
136
137 ################################
138 # _createStagingDirs() function
139 ################################
140
141
142 def _createStagingDirs(config, dailyDir, peers):
143 """
144 Creates staging directories as required.
145
146 The main staging directory is the passed in daily directory, something like
147 ``staging/2002/05/23``. Then, individual peers get their own directories,
148 i.e. ``staging/2002/05/23/host``.
149
150 Args:
151 config: Config object
152 dailyDir: Daily staging directory
153 peers: List of all configured peers
154
155 Returns:
156 Dictionary mapping peer name to staging directory
157 """
158 mapping = {}
159 if os.path.isdir(dailyDir):
160 logger.warning("Staging directory [%s] already existed.", dailyDir)
161 else:
162 try:
163 logger.debug("Creating staging directory [%s].", dailyDir)
164 os.makedirs(dailyDir)
165 for path in [dailyDir, pathJoin(dailyDir, ".."), pathJoin(dailyDir, "..", "..")]:
166 changeOwnership(path, config.options.backupUser, config.options.backupGroup)
167 except Exception as e:
168 raise Exception("Unable to create staging directory: %s" % e)
169 for peer in peers:
170 peerDir = pathJoin(dailyDir, peer.name)
171 mapping[peer.name] = peerDir
172 if os.path.isdir(peerDir):
173 logger.warning("Peer staging directory [%s] already existed.", peerDir)
174 else:
175 try:
176 logger.debug("Creating peer staging directory [%s].", peerDir)
177 os.makedirs(peerDir)
178 changeOwnership(peerDir, config.options.backupUser, config.options.backupGroup)
179 except Exception as e:
180 raise Exception("Unable to create staging directory: %s" % e)
181 return mapping
182
183
184 ########################################################################
185 # Private attribute "getter" functions
186 ########################################################################
187
188 ####################################
189 # _getIgnoreFailuresFlag() function
190 ####################################
191
192
193 def _getIgnoreFailuresFlag(options, config, peer):
194 """
195 Gets the ignore failures flag based on options, configuration, and peer.
196 Args:
197 options: Options object
198 config: Configuration object
199 peer: Peer to check
200 Returns:
201 Whether to ignore stage failures for this peer
202 """
203 logger.debug("Ignore failure mode for this peer: %s", peer.ignoreFailureMode)
204 if peer.ignoreFailureMode is None or peer.ignoreFailureMode == "none":
205 return False
206 elif peer.ignoreFailureMode == "all":
207 return True
208 else:
209 if options.full or isStartOfWeek(config.options.startingDay):
210 return peer.ignoreFailureMode == "weekly"
211 else:
212 return peer.ignoreFailureMode == "daily"
213
214
215 ##########################
216 # _getDailyDir() function
217 ##########################
218
219
220 def _getDailyDir(config):
221 """
222 Gets the daily staging directory.
223
224 This is just a directory in the form ``staging/YYYY/MM/DD``, i.e.
225 ``staging/2000/10/07``, except it will be an absolute path based on
226 ``config.stage.targetDir``.
227
228 Args:
229 config: Config object
230
231 Returns:
232 Path of daily staging directory
233 """
234 dailyDir = pathJoin(config.stage.targetDir, time.strftime(DIR_TIME_FORMAT))
235 logger.debug("Daily staging directory is [%s].", dailyDir)
236 return dailyDir
237
238
239 ############################
240 # _getLocalPeers() function
241 ############################
242
243
244 def _getLocalPeers(config):
245 """
246 Return a list of :any:`LocalPeer` objects based on configuration.
247 Args:
248 config: Config object
249 Returns:
250 List of :any:`LocalPeer` objects
251 """
252 localPeers = []
253 configPeers = None
254 if config.stage.hasPeers():
255 logger.debug("Using list of local peers from stage configuration.")
256 configPeers = config.stage.localPeers
257 elif config.peers is not None and config.peers.hasPeers():
258 logger.debug("Using list of local peers from peers configuration.")
259 configPeers = config.peers.localPeers
260 if configPeers is not None:
261 for peer in configPeers:
262 localPeer = LocalPeer(peer.name, peer.collectDir, peer.ignoreFailureMode)
263 localPeers.append(localPeer)
264 logger.debug("Found local peer: [%s]", localPeer.name)
265 return localPeers
266
267
268 #############################
269 # _getRemotePeers() function
270 #############################
271
272
273 def _getRemotePeers(config):
274 """
275 Return a list of :any:`RemotePeer` objects based on configuration.
276 Args:
277 config: Config object
278 Returns:
279 List of :any:`RemotePeer` objects
280 """
281 remotePeers = []
282 configPeers = None
283 if config.stage.hasPeers():
284 logger.debug("Using list of remote peers from stage configuration.")
285 configPeers = config.stage.remotePeers
286 elif config.peers is not None and config.peers.hasPeers():
287 logger.debug("Using list of remote peers from peers configuration.")
288 configPeers = config.peers.remotePeers
289 if configPeers is not None:
290 for peer in configPeers:
291 remoteUser = _getRemoteUser(config, peer)
292 localUser = _getLocalUser(config)
293 rcpCommand = _getRcpCommand(config, peer)
294 remotePeer = RemotePeer(
295 peer.name,
296 peer.collectDir,
297 config.options.workingDir,
298 remoteUser,
299 rcpCommand,
300 localUser,
301 ignoreFailureMode=peer.ignoreFailureMode,
302 )
303 remotePeers.append(remotePeer)
304 logger.debug("Found remote peer: [%s]", remotePeer.name)
305 return remotePeers
306
307
308 ############################
309 # _getRemoteUser() function
310 ############################
311
312
313 def _getRemoteUser(config, remotePeer):
314 """
315 Gets the remote user associated with a remote peer.
316 Use peer's if possible, otherwise take from options section.
317 Args:
318 config: Config object
319 remotePeer: Configuration-style remote peer object
320 Returns:
321 Name of remote user associated with remote peer
322 """
323 if remotePeer.remoteUser is None:
324 return config.options.backupUser
325 return remotePeer.remoteUser
326
327
328 ###########################
329 # _getLocalUser() function
330 ###########################
331
332
333 def _getLocalUser(config):
334 """
335 Gets the remote user associated with a remote peer.
336 Args:
337 config: Config object
338 Returns:
339 Name of local user that should be used
340 """
341 if not isRunningAsRoot():
342 return None
343 return config.options.backupUser
344
345
346 ############################
347 # _getRcpCommand() function
348 ############################
349
350
351 def _getRcpCommand(config, remotePeer):
352 """
353 Gets the RCP command associated with a remote peer.
354 Use peer's if possible, otherwise take from options section.
355 Args:
356 config: Config object
357 remotePeer: Configuration-style remote peer object
358 Returns:
359 RCP command associated with remote peer
360 """
361 if remotePeer.rcpCommand is None:
362 return config.options.rcpCommand
363 return remotePeer.rcpCommand