| 1 |
# Bacula(R) - The Network Backup Solution |
| 2 |
# |
| 3 |
# Copyright (C) 2000-2022 Kern Sibbald |
| 4 |
# |
| 5 |
# The original author of Bacula is Kern Sibbald, with contributions |
| 6 |
# from many others, a complete list can be found in the file AUTHORS. |
| 7 |
# |
| 8 |
# You may use this file and others of this release according to the |
| 9 |
# license defined in the LICENSE file, which includes the Affero General |
| 10 |
# Public License, v3.0 ("AGPLv3") and some additional permissions and |
| 11 |
# terms pursuant to its AGPLv3 Section 7. |
| 12 |
# |
| 13 |
# This notice must be preserved when any source code is |
| 14 |
# conveyed and/or propagated. |
| 15 |
# |
| 16 |
# Bacula(R) is a registered trademark of Kern Sibbald. |
| 17 |
|
| 18 |
import logging |
| 19 |
import time |
| 20 |
|
| 21 |
from baculak8s.entities.file_info import DIRECTORY |
| 22 |
from baculak8s.entities.plugin_object import PluginObject |
| 23 |
from baculak8s.io.packet_definitions import FILE_DATA_START |
| 24 |
from baculak8s.jobs.estimation_job import PVCDATA_GET_ERROR, EstimationJob |
| 25 |
from baculak8s.jobs.job_pod_bacula import DEFAULTRECVBUFFERSIZE |
| 26 |
from baculak8s.plugins.k8sbackend.baculaannotations import ( |
| 27 |
BaculaAnnotationsClass, BaculaBackupMode, annotated_pvc_backup_mode) |
| 28 |
from baculak8s.plugins.k8sbackend.baculabackup import BACULABACKUPPODNAME |
| 29 |
from baculak8s.plugins.k8sbackend.podexec import ExecStatus, exec_commands |
| 30 |
from baculak8s.util.respbody import parse_json_descr |
| 31 |
from baculak8s.util.boolparam import BoolParam |
| 32 |
from baculak8s.plugins.k8sbackend.k8sfileinfo import defaultk8spath |
| 33 |
|
| 34 |
BACKUP_START_PACKET = "BackupStart" |
| 35 |
BACKUP_PARAM_LABELS = "Resource Selector: {}" |
| 36 |
FILE_BACKUP_ERROR = "Error while reading file contents from the chosen Data Source: {}" |
| 37 |
POD_DATA_RECV_ERR = "Error in receiving data from bacula-backup Pod!" |
| 38 |
BA_MODE_ERROR = "Invalid annotations for Pod: {namespace}/{podname}. Backup Mode '{mode}' not supported!" |
| 39 |
BA_EXEC_STDOUT = "{}:{}" |
| 40 |
BA_EXEC_STDERR = "{} Error:{}" |
| 41 |
BA_EXEC_ERROR = "Pod Container execution: {}" |
| 42 |
POD_BACKUP_SELECTED = "The selected backup mode to do pvc backup of the pvc `{}` is `{}`" |
| 43 |
CHANGE_BACKUP_MODE_FOR_INCOMPATIBLITY_PVC = "The pvc `{}` is not compatible with snapshot backup, changing mode to clone. Only pvc with storage that they use CSI driver are compatible." |
| 44 |
PVC_BACKUP_MODE_APPLIED_INFO = "The pvc `{}` will be backup with {} mode." |
| 45 |
RETRY_BACKUP_WITH_STANDARD_MODE = "If the clone backup is empty. It will try again to do a backup using standard mode." |
| 46 |
|
| 47 |
class BackupJob(EstimationJob): |
| 48 |
""" |
| 49 |
Job that contains the business logic |
| 50 |
related to the backup mode of the Backend. |
| 51 |
It depends upon a Plugin Class implementation |
| 52 |
that retrieves backup data from the Plugins Data Source |
| 53 |
""" |
| 54 |
|
| 55 |
def __init__(self, plugin, params): |
| 56 |
super().__init__(plugin, params, BACKUP_START_PACKET) |
| 57 |
_label = params.get('labels', None) |
| 58 |
self.fs_backup_mode = BaculaBackupMode.process_param(params.get("backup_mode", BaculaBackupMode.Snapshot)) # Fileset backup mode defined. |
| 59 |
if _label is not None: |
| 60 |
self._io.send_info(BACKUP_PARAM_LABELS.format(_label)) |
| 61 |
if params.get('pvcdata', None) is not None: |
| 62 |
self._io.send_info("The selected default backup mode to do pvc backup in all job is `{}`.".format(self.fs_backup_mode)) |
| 63 |
|
| 64 |
def execution_loop(self): |
| 65 |
super().processing_loop(estimate=False) |
| 66 |
self.process_plugin_objects() |
| 67 |
|
| 68 |
def process_file(self, data): |
| 69 |
return self._backup_file(data) |
| 70 |
|
| 71 |
def process_plugin_objects(self): |
| 72 |
# logging.debug("SELF: {}".format(dir(self))) |
| 73 |
""" |
| 74 |
name: plugin command line |
| 75 |
category: Container |
| 76 |
type: Kubernetes/Openshift POD |
| 77 |
source: (name on the network?) |
| 78 |
uuid: (I don't know if available) |
| 79 |
size: total size POD would be nice |
| 80 |
status: T/W/e |
| 81 |
count: Number of POD |
| 82 |
""" |
| 83 |
logging.debug("PO_PODS: {}".format(self._plugin.pods_counter)) |
| 84 |
if self._plugin.pods_counter > 0: |
| 85 |
po_pods = PluginObject("/{}/".format(defaultk8spath), |
| 86 |
"Kubernetes PODs", |
| 87 |
cat="Container", |
| 88 |
potype="POD", |
| 89 |
src=self._plugin.po_source_data, |
| 90 |
uuid=self._plugin.po_source_data, |
| 91 |
count=self._plugin.pods_counter) |
| 92 |
self._io.send_plugin_object(po_pods) |
| 93 |
logging.debug("PO_PVCS: {} {}".format(self._plugin.pvcs_counter, self._plugin.pvcs_totalsize)) |
| 94 |
if self._plugin.pvcs_counter > 0: |
| 95 |
po_pvcs = PluginObject("/{}/".format(defaultk8spath), |
| 96 |
"Kubernetes Persistent Volume Claims", |
| 97 |
cat="Container", |
| 98 |
potype="PVC", |
| 99 |
src=self._plugin.po_source_data, |
| 100 |
uuid=self._plugin.po_source_data, |
| 101 |
count=self._plugin.pvcs_counter, |
| 102 |
size=self._plugin.pvcs_totalsize) |
| 103 |
self._io.send_plugin_object(po_pvcs) |
| 104 |
|
| 105 |
def _backup_file(self, data): |
| 106 |
file_info = data.get('fi') |
| 107 |
super()._estimate_file(file_info) |
| 108 |
if file_info.type != DIRECTORY: |
| 109 |
self.__backup_data(file_info, data.get('spec')) |
| 110 |
self._io.send_eod() |
| 111 |
|
| 112 |
def __backup_data(self, info, spec_data): |
| 113 |
self._io.send_command(FILE_DATA_START) |
| 114 |
if spec_data is None: |
| 115 |
self._handle_error(FILE_BACKUP_ERROR.format(info.name)) |
| 116 |
else: |
| 117 |
for file_chunk in [spec_data[i:i+DEFAULTRECVBUFFERSIZE] for i in range(0, len(spec_data), DEFAULTRECVBUFFERSIZE)]: |
| 118 |
self._io.send_data(str.encode(file_chunk)) |
| 119 |
|
| 120 |
def __backup_pvcdata(self, namespace): |
| 121 |
logging.debug('backup_pvcdata:data recv') |
| 122 |
self._io.send_command(FILE_DATA_START) |
| 123 |
response = self.connsrv.handle_connection(self.handle_pod_data_recv) |
| 124 |
if 'error' in response: |
| 125 |
self._handle_error(response['error']) |
| 126 |
if 'should_remove_pod' in response: |
| 127 |
self.delete_pod(namespace=namespace, force=True) |
| 128 |
return False |
| 129 |
logging.debug('backup_pvcdata:logs recv') |
| 130 |
response = self.connsrv.handle_connection(self.handle_pod_logs) |
| 131 |
if 'error' in response: |
| 132 |
self._handle_error(response['error']) |
| 133 |
return False |
| 134 |
return True |
| 135 |
|
| 136 |
def process_pvcdata(self, namespace, pvcdata, backup_with_pod = False, retry_backup = False): |
| 137 |
status = None |
| 138 |
vsnapshot = None |
| 139 |
is_cloned = False |
| 140 |
cloned_pvc_name = None |
| 141 |
# For retry if clone backup is incompatible. |
| 142 |
orig_pvcdata = pvcdata |
| 143 |
# Detect if pvcdata is compatible with snapshots |
| 144 |
if not backup_with_pod and not retry_backup: |
| 145 |
logging.debug('Backup mode {} of pvc {} without pod:'.format(self.fs_backup_mode, pvcdata.get('name'))) |
| 146 |
pvc_raw = self._plugin.get_persistentvolumeclaim_read_namespaced(namespace, pvcdata.get('name')) |
| 147 |
pvc_backup_mode = annotated_pvc_backup_mode(pvc_raw, self.fs_backup_mode) |
| 148 |
if pvc_backup_mode == BaculaBackupMode.Snapshot: |
| 149 |
logging.debug('Snapshot is activated') |
| 150 |
vsnapshot, pvcdata = self.handle_create_vsnapshot_backup(namespace, pvcdata.get('name')) |
| 151 |
self._io.send_info(PVC_BACKUP_MODE_APPLIED_INFO.format(pvcdata.get('name'), BaculaBackupMode.Snapshot)) |
| 152 |
self.current_backup_mode = BaculaBackupMode.Snapshot |
| 153 |
|
| 154 |
if (vsnapshot is None and pvc_backup_mode != BaculaBackupMode.Standard) or pvc_backup_mode == BaculaBackupMode.Clone: |
| 155 |
if pvc_backup_mode != BaculaBackupMode.Clone: |
| 156 |
self._io.send_info(CHANGE_BACKUP_MODE_FOR_INCOMPATIBLITY_PVC.format(pvcdata.get('name'))) |
| 157 |
self._io.send_info(PVC_BACKUP_MODE_APPLIED_INFO.format(pvcdata.get('name'), BaculaBackupMode.Clone)) |
| 158 |
cloned_pvc_name = self.create_pvcclone(namespace, pvcdata.get('name')) |
| 159 |
cloned_pvc = self._plugin.get_pvcdata_namespaced(namespace, cloned_pvc_name) |
| 160 |
logging.debug('Cloned pvc fi:{}'.format(cloned_pvc.get('fi'))) |
| 161 |
cloned_pvc.get('fi').set_name(pvcdata.get('fi').name) |
| 162 |
pvcdata = cloned_pvc |
| 163 |
is_cloned = True |
| 164 |
self.current_backup_mode = BaculaBackupMode.Clone |
| 165 |
|
| 166 |
if pvc_backup_mode == BaculaBackupMode.Standard: |
| 167 |
self._io.send_info(PVC_BACKUP_MODE_APPLIED_INFO.format(pvcdata.get('name'), BaculaBackupMode.Standard)) |
| 168 |
self.current_backup_mode = BaculaBackupMode.Standard |
| 169 |
logging.debug('Process_pvcdata (Backup_job): {} --- {}'.format(vsnapshot, pvcdata)) |
| 170 |
|
| 171 |
if self.prepare_bacula_pod(pvcdata, namespace=namespace, mode='backup'): |
| 172 |
super()._estimate_file(pvcdata) # here to send info about pvcdata to plugin |
| 173 |
status = self.__backup_pvcdata(namespace=namespace) |
| 174 |
if status: |
| 175 |
self._io.send_eod() |
| 176 |
self.handle_tarstderr() |
| 177 |
self.handle_delete_pod(namespace=namespace) |
| 178 |
# Both prepare_bacula_pod fails or not, we must remove snapshot and pvc |
| 179 |
if not backup_with_pod: |
| 180 |
self.handle_delete_vsnapshot_backup(namespace, vsnapshot, pvcdata) |
| 181 |
if is_cloned: |
| 182 |
self.delete_pvcclone(namespace, cloned_pvc_name) |
| 183 |
# It retries when the backup is not with pod annotation (it is controlled in their function) |
| 184 |
if not backup_with_pod and not retry_backup and not self.backup_clone_compatibility: |
| 185 |
# It is important set to True before recall the process. |
| 186 |
self.backup_clone_compatibility = True # We only try once |
| 187 |
self._io.send_info(RETRY_BACKUP_WITH_STANDARD_MODE) |
| 188 |
logging.debug("Sent info to joblog: " + RETRY_BACKUP_WITH_STANDARD_MODE) |
| 189 |
|
| 190 |
status = self.process_pvcdata(namespace, orig_pvcdata, backup_with_pod, True) |
| 191 |
return status |
| 192 |
|
| 193 |
def handle_pod_container_exec_command(self, corev1api, namespace, pod, runjobparam, failonerror=False): |
| 194 |
podname = pod.get('name') |
| 195 |
containers = pod.get('containers') |
| 196 |
logging.debug("[{}] pod {} containers: {}".format(runjobparam, podname, containers)) |
| 197 |
# now check if run before job |
| 198 |
container, command = BaculaAnnotationsClass.handle_run_job_container_command(pod.get(runjobparam)) |
| 199 |
if container is not None: |
| 200 |
logging.info("container: {}".format(container)) |
| 201 |
logging.info("command: {}".format(command)) |
| 202 |
if container != '*': |
| 203 |
# check if container exist |
| 204 |
if container not in containers: |
| 205 |
# error |
| 206 |
logging.error("container {} not found".format(container)) |
| 207 |
return False |
| 208 |
containers = [container] |
| 209 |
# here execute command |
| 210 |
for cname in containers: |
| 211 |
logging.info("executing command: {} on {}".format(command, cname)) |
| 212 |
outch, errch, infoch = exec_commands(corev1api, namespace, podname, cname, command) |
| 213 |
logging.info("stdout:\n{}".format(outch)) |
| 214 |
if len(outch) > 0: |
| 215 |
outch = outch.rstrip('\n') |
| 216 |
self._io.send_info(BA_EXEC_STDOUT.format(runjobparam, outch)) |
| 217 |
logging.info("stderr:\n{}".format(errch)) |
| 218 |
if len(errch) > 0: |
| 219 |
errch = errch.rstrip('\n') |
| 220 |
self._io.send_warning(BA_EXEC_STDERR.format(runjobparam, errch)) |
| 221 |
execstatus = ExecStatus.check_status(infoch) |
| 222 |
logging.info("Exec status: {}".format(execstatus)) |
| 223 |
if not execstatus: |
| 224 |
self._io.send_warning(BA_EXEC_ERROR.format(infoch.get('message'))) |
| 225 |
if failonerror: |
| 226 |
self._handle_error("Failing job on request...") |
| 227 |
return False |
| 228 |
|
| 229 |
return True |
| 230 |
|
| 231 |
def process_pod_pvcdata(self, namespace, pod, pvcnames): |
| 232 |
logging.debug("process_pod_pvcdata:{}/{} {}".format(namespace, pod, pvcnames)) |
| 233 |
status = None |
| 234 |
corev1api = self._plugin.corev1api |
| 235 |
pod_backup_mode = BaculaBackupMode.process_param(pod.get(BaculaAnnotationsClass.BackupMode, BaculaBackupMode.Snapshot)) |
| 236 |
if pod_backup_mode is None: |
| 237 |
self._handle_error(BA_MODE_ERROR.format(namespace=namespace, |
| 238 |
podname=pod.get('name'), |
| 239 |
mode=pod.get(BaculaAnnotationsClass.BackupMode))) |
| 240 |
return False |
| 241 |
|
| 242 |
self._io.send_info("The selected default backup mode to do pvc backup of the pod `{}` is `{}`".format(pod.get('name'), pod_backup_mode)) |
| 243 |
|
| 244 |
failonerror = BoolParam.handleParam(pod.get(BaculaAnnotationsClass.RunBeforeJobonError), True) # the default is to fail job on error |
| 245 |
# here we execute remote command before Pod backup |
| 246 |
if not self.handle_pod_container_exec_command(corev1api, namespace, pod, BaculaAnnotationsClass.RunBeforeJob, failonerror): |
| 247 |
logging.error("handle_pod_container_exec_command execution error!") |
| 248 |
return False |
| 249 |
|
| 250 |
requestedvolumes = [v.lstrip().rstrip() for v in pvcnames.split(',')] |
| 251 |
handledvolumes = [] |
| 252 |
|
| 253 |
# iterate on requested volumes for shapshot |
| 254 |
logging.debug("iterate over requested vols for backup: {}".format(requestedvolumes)) |
| 255 |
for pvc in requestedvolumes: |
| 256 |
pvcname = pvc |
| 257 |
original_pvc = self._plugin.get_pvcdata_namespaced(namespace, pvcname) |
| 258 |
vsnapshot = None |
| 259 |
logging.debug("handling vol before backup: {}".format(pvcname)) |
| 260 |
pvc_raw = self._plugin.get_persistentvolumeclaim_read_namespaced(namespace, pvcname) |
| 261 |
pvc_backup_mode = annotated_pvc_backup_mode(pvc_raw, pod_backup_mode) |
| 262 |
self._io.send_info(POD_BACKUP_SELECTED.format(pvcname, pvc_backup_mode)) |
| 263 |
|
| 264 |
# Check if pvc has status: 'Terminating'. Because in this state, the backup raise error. |
| 265 |
if self._plugin.pvc_is_terminating(namespace, original_pvc): |
| 266 |
logging.debug("Skip pvc. Cause Terminating status") |
| 267 |
self._io.send_warning("Skip pvc `{}` because it is in Terminating status.".format(pvcname)) |
| 268 |
continue |
| 269 |
if self._plugin.pvc_is_pending(namespace, original_pvc): |
| 270 |
logging.debug("Skip pvc. Cause Pending status") |
| 271 |
self._io.send_warning("Skip pvc `{}` because it is in Pending status.".format(pvcname)) |
| 272 |
continue |
| 273 |
|
| 274 |
if pvc_backup_mode == BaculaBackupMode.Snapshot: |
| 275 |
logging.debug('Snapshot mode chosen') |
| 276 |
vsnapshot, pvc_from_vsnap = self.handle_create_vsnapshot_backup(namespace, pvcname) |
| 277 |
logging.debug("The vsnapshot created from pvc {} is: {}".format(pvcname, vsnapshot)) |
| 278 |
logging.debug("The pvc create from vsnapshot {} is: {}. FI: {}".format(vsnapshot, pvc_from_vsnap, pvc_from_vsnap.get('fi'))) |
| 279 |
if vsnapshot is None: |
| 280 |
logging.debug(CHANGE_BACKUP_MODE_FOR_INCOMPATIBLITY_PVC.format(pvcname)) |
| 281 |
# backupmode = BaculaBackupMode.Clone |
| 282 |
self._io.send_info(CHANGE_BACKUP_MODE_FOR_INCOMPATIBLITY_PVC.format(pvcname)) |
| 283 |
pvc_backup_mode = BaculaBackupMode.Clone |
| 284 |
else: |
| 285 |
pvc = pvc_from_vsnap |
| 286 |
pvcname = pvc_from_vsnap.get("name") |
| 287 |
|
| 288 |
if pvc_backup_mode == BaculaBackupMode.Clone: |
| 289 |
pvcname = self.create_pvcclone(namespace, pvcname) |
| 290 |
cloned_pvc = self._plugin.get_pvcdata_namespaced(namespace, pvcname) |
| 291 |
if pvcname is None: |
| 292 |
# error |
| 293 |
logging.error("create_pvcclone failed!") |
| 294 |
return False |
| 295 |
else: |
| 296 |
logging.debug('Original_pvc: {}'.format(original_pvc.get('fi'))) |
| 297 |
logging.debug('Cloned_pvc->fi: {}'.format(cloned_pvc.get('fi'))) |
| 298 |
cloned_pvc.get('fi').set_name(original_pvc.get('fi').name) |
| 299 |
pvc = cloned_pvc |
| 300 |
|
| 301 |
logging.debug("handling vol after snapshot/clone: {}".format(pvcname)) |
| 302 |
handledvolumes.append({ |
| 303 |
'pvcname': pvcname, |
| 304 |
'pvc': pvc, |
| 305 |
'vsnapshot': vsnapshot, |
| 306 |
'backupmode': pvc_backup_mode, |
| 307 |
'original_pvc': original_pvc |
| 308 |
}) |
| 309 |
|
| 310 |
failonerror = BoolParam.handleParam(pod.get(BaculaAnnotationsClass.RunAfterSnapshotonError), False) # the default is ignore errors |
| 311 |
# here we execute remote command after vol snapshot |
| 312 |
if not self.handle_pod_container_exec_command(corev1api, namespace, pod, BaculaAnnotationsClass.RunAfterSnapshot, failonerror): |
| 313 |
return False |
| 314 |
|
| 315 |
# iterate on requested volumes for backup |
| 316 |
logging.debug("iterate over requested vols for backup: {}".format(handledvolumes)) |
| 317 |
for volumes in handledvolumes: |
| 318 |
logging.debug('Volume in handlevolumes:\n{}'.format(volumes)) |
| 319 |
pvc = volumes['pvc'] |
| 320 |
pvcname = volumes['pvcname'] |
| 321 |
# get pvcdata for this volume |
| 322 |
""" |
| 323 |
PVCDATA:plugintest-pvc-alone:{'name': 'plugintest-pvc-alone-baculaclone-lfxrra', 'node_name': None, 'storage_class_name': 'ocs-storagecluster-cephfs', 'capacity': '1Gi', 'fi': <baculak8s.entities.file_info.FileInfo object at 0x7fc3c08bc668>} |
| 324 |
""" |
| 325 |
pvcdata = self._plugin.get_pvcdata_namespaced(namespace, pvcname, pvcname) |
| 326 |
if isinstance(pvcdata, dict) and 'error' in pvcdata: |
| 327 |
self._handle_error(PVCDATA_GET_ERROR.format(parse_json_descr(pvcdata))) |
| 328 |
|
| 329 |
else: |
| 330 |
# Modify the name in FileInfo because we need save the file like original name |
| 331 |
# and not the new pvc (from vsnapshot) name. |
| 332 |
if volumes.get('backupmode') == BaculaBackupMode.Snapshot or volumes.get('backupmode') == BaculaBackupMode.Clone: |
| 333 |
logging.debug('We change the name of FileInfo to adapt the original pvc name with the new pvc name') |
| 334 |
pvcdata.get('fi').set_name(pvc.get('fi').name) |
| 335 |
|
| 336 |
if len(pvcdata) > 0: |
| 337 |
status = self.process_pvcdata(namespace, pvcdata, True) |
| 338 |
# Control the compatibility of snapshot or clone. If it is not compatible, retry again with standard backup mode. |
| 339 |
logging.debug('Call again process_pvcdata from process_pod_pvcdata? {}'.format(self.backup_clone_compatibility)) |
| 340 |
if not self.backup_clone_compatibility: |
| 341 |
status = self.process_pvcdata(namespace, volumes['original_pvc'], True) |
| 342 |
|
| 343 |
# iterate on requested volumes for delete snap |
| 344 |
logging.debug("iterate over requested vols for delete snap: {}".format(handledvolumes)) |
| 345 |
for volumes in handledvolumes: |
| 346 |
pvcname = volumes['pvcname'] |
| 347 |
logging.debug("Should remove this pvc: {}".format(pvcname)) |
| 348 |
if volumes.get('backupmode') == BaculaBackupMode.Clone: |
| 349 |
# snapshot delete if snapshot requested |
| 350 |
status = self.delete_pvcclone(namespace, pvcname) |
| 351 |
if volumes.get('backupmode') == BaculaBackupMode.Snapshot and volumes['vsnapshot'] is not None: |
| 352 |
status = self.handle_delete_vsnapshot_backup(namespace, volumes['vsnapshot'], volumes['pvc']) |
| 353 |
logging.debug("Finish removing pvc clones and vsnapshots. Status {}".format(status)) |
| 354 |
|
| 355 |
failonerror = BoolParam.handleParam(pod.get(BaculaAnnotationsClass.RunAfterJobonError), False) # the default is ignore errors |
| 356 |
# here we execute remote command after Pod backup |
| 357 |
if not self.handle_pod_container_exec_command(corev1api, namespace, pod, BaculaAnnotationsClass.RunAfterJob, failonerror): |
| 358 |
return False |
| 359 |
|
| 360 |
return status |