Debian Codegraph @

src/plugins/fd/kubernetes-backend/baculak8s/jobs/job_pod_bacula.py

raw
1 #
2 # Bacula(R) - The Network Backup Solution
3 #
4 # Copyright (C) 2000-2022 Kern Sibbald
5 #
6 # The original author of Bacula is Kern Sibbald, with contributions
7 # from many others, a complete list can be found in the file AUTHORS.
8 #
9 # You may use this file and others of this release according to the
10 # license defined in the LICENSE file, which includes the Affero General
11 # Public License, v3.0 ("AGPLv3") and some additional permissions and
12 # terms pursuant to its AGPLv3 Section 7.
13 #
14 # This notice must be preserved when any source code is
15 # conveyed and/or propagated.
16 #
17 # Bacula(R) is a registered trademark of Kern Sibbald.
18 #
19 # Copyright (c) 2019 by Inteos sp. z o.o.
20 # All rights reserved. IP transfered to Bacula Systems according to agreement.
21 # Author: RadosÅ‚aw Korzeniewski, [email protected], Inteos Sp. z o.o.
22 #
23
24 import logging
25 import time
26 from abc import ABCMeta
27
28 import yaml
29 from baculak8s.jobs.job import Job
30 from baculak8s.plugins.k8sbackend.baculabackup import (BACULABACKUPIMAGE,
31 ImagePullPolicy,
32 prepare_backup_pod_yaml,
33 get_backup_pod_name)
34 from baculak8s.plugins.k8sbackend.pvcclone import prepare_backup_clone_yaml, find_bacula_pvc_clones_from_old_job
35 from baculak8s.plugins.k8sbackend.baculaannotations import BaculaBackupMode
36 from baculak8s.util.respbody import parse_json_descr
37 from baculak8s.util.sslserver import DEFAULTTIMEOUT, ConnectionServer
38 from baculak8s.util.token import generate_token
39
40 DEFAULTRECVBUFFERSIZE = 64 * 1048
41 PLUGINHOST_NONE_ERR = "PLUGINHOST parameter is missing and cannot be autodetected. " \
42 "Cannot continue with pvcdata backup!"
43 POD_EXECUTION_ERR = "Cannot successfully start bacula-backup pod in expected time!"
44 POD_REMOVE_ERR = "Unable to remove proxy Pod {podname}! Other operations with proxy Pod will fail!"
45 POD_EXIST_ERR = "Job already running in '{namespace}' namespace. Check logs or delete {podname} Pod manually."
46 TAR_STDERR_UNKNOWN = "Unknown error. You should check Pod logs for possible explanation."
47 PLUGINPORT_VALUE_ERR = "Cannot use provided pluginport={port} option. Used default!"
48 FDPORT_VALUE_ERR = "Cannot use provided fdport={port} option. Used default!"
49 POD_YAML_PREPARED_INFO = "Prepare bacula-backup Pod with: {image} <{pullpolicy}> {pluginhost}:{pluginport}"
50 POD_YAML_PREPARED_INFO_NODE = "Prepare Bacula Pod on: {nodename} with: {image} <{pullpolicy}> {pluginhost}:{pluginport}"
51 CANNOT_CREATE_BACKUP_POD_ERR = "Cannot create backup pod. Err={}"
52 CANNOT_REMOVE_BACKUP_POD_ERR = "Cannot remove backup pod. Err={}"
53 PVCDATA_GET_ERROR = "Cannot get PVC Data object Err={}"
54 PVCCLONE_YAML_PREPARED_INFO = "Prepare clone: {namespace}/{snapname} storage: {storage} capacity: {capacity}"
55 CANNOT_CREATE_PVC_CLONE_ERR = "Cannot create PVC snapshot. Err={}"
56 CANNOT_CREATE_VSNAPSHOT_ERR = "Cannot create Volume Snapshot. Err={}"
57 CANNOT_CREATE_PVC_SNAPSHOT_ERR = "Cannot create PVC from Volume Snapshot. Err={}"
58 CANNOT_REMOVE_PVC_CLONE_ERR = "Cannot remove PVC snapshot. Err={}"
59 CANNOT_REMOVE_VSNAPSHOT_ERR = "Unable to remove volume snapshot {vsnapshot}! Please you must remove it manually."
60 CANNOT_START_CONNECTIONSERVER = "Cannot start ConnectionServer. Err={}"
61
62 WARNING_CLONED_PVC_WAS_NOT_WORKED = "As clone backup is empty. It will retry again to do a backup with standard mode."
63 VSNAPSHOT_BACKUP_COMPATIBLE_INFO = "The pvc `{}` is compatible with volume snapshot backup. Doing backup with this technology."
64 PVC_FROM_SNAPSHOT_CREATED = "The pvc `{}` was created from volume snapshot from pvc `{}`."
65 CREATING_PVC_FROM_VSNAPSHOT = "Creating pvc from volume snapshot of pvc `{}`."
66 FINISHED_PVC_FROM_VSNAPSHOT = "Finished pvc `{}` volume snapshot from pvc `{}`."
67 class JobPodBacula(Job, metaclass=ABCMeta):
68 """
69
70 This is a common class for all job which handles pvcdata backups using
71 bacula-backup Pod.
72
73 """
74
75 def __init__(self, plugin, io, params):
76 super().__init__(plugin, io, params)
77 self.connsrv = None
78 self.fdaddr = params.get("fdaddress")
79 self.fdport = params.get("fdport", 9104)
80 self.pluginhost = params.get("pluginhost", self.fdaddr)
81 self.pluginport = params.get("pluginport", self.fdport)
82 self.certfile = params.get('fdcertfile')
83 _keyfile = params.get('fdkeyfile')
84 self.keyfile = _keyfile if _keyfile is not None else self.certfile
85 self._prepare_err = False
86 self.token = None
87 self.jobname = '{name}:{jobid}'.format(name=params.get('name', 'undefined'), jobid=params.get('jobid', '0'))
88 self.timeout = params.get('timeout', DEFAULTTIMEOUT)
89 try:
90 self.timeout = int(self.timeout)
91 except ValueError:
92 self.timeout = DEFAULTTIMEOUT
93 self.timeout = max(1, self.timeout)
94 self.tarstderr = ''
95 self.tarexitcode = None
96 self.backupimage = params.get('baculaimage', BACULABACKUPIMAGE)
97 self.imagepullpolicy = ImagePullPolicy.process_param(params.get('imagepullpolicy'))
98 self.imagepullsecret = params.get('imagepullsecret', None)
99 self.backup_clone_compatibility = True
100 self.debug = params.get('debug', 0)
101 self.current_backup_mode = BaculaBackupMode.Standard
102
103 def handle_pod_logs(self, connstream):
104 logmode = ''
105 self.tarstderr = ''
106 file_count = 0
107 bytes_count = 0
108 with connstream.makefile(mode='r') as fd:
109 self.tarexitcode = fd.readline().strip()
110 logging.debug('handle_pod_logs:tarexitcode:{}'.format(self.tarexitcode))
111 while True:
112 data = fd.readline()
113 if not data:
114 break
115 logging.debug('LOGS:{}'.format(data.strip()))
116 if data.startswith('---- stderr ----'):
117 logmode = 'stderr'
118 continue
119 elif data.startswith('---- list ----'):
120 logmode = 'list'
121 continue
122 elif data.startswith('---- end ----'):
123 break
124 if logmode == 'stderr':
125 self.tarstderr += data
126 continue
127 elif logmode == 'list':
128 # no listing feature yet
129 file_count += 1
130 try:
131 file_props = data.split()
132 logging.debug('Data Split:{}'.format(','.join(file_props)))
133 bytes_count += int(file_props[2])
134 except Exception as e:
135 logging.exception(e)
136 continue
137 logging.debug('Bytes/files in backup: {}/{}'.format(bytes_count, file_count))
138 logging.debug('Type of job:' + str(self._params.get('type')))
139 # If the backupMode is standard, we ignore if the backup contains 0 bytes.
140 if self._params.get('type') == 'b' and self.current_backup_mode != BaculaBackupMode.Standard and bytes_count == 0 and file_count < 3:
141 self._io.send_non_fatal_error(WARNING_CLONED_PVC_WAS_NOT_WORKED)
142 self.backup_clone_compatibility = False
143
144
145 def handle_pod_data_recv(self, connstream):
146 while True:
147 data = self.connsrv.streamrecv(DEFAULTRECVBUFFERSIZE)
148 if not data:
149 logging.debug('handle_pod_data_recv:EOT')
150 break
151 if self.debug == '3':
152 logging.debug('handle_pod_data_recv:D' + str(len(data)))
153 self._io.send_data(data)
154
155 def handle_pod_data_send(self, connstream):
156 while True:
157 data = self._io.read_data()
158 if not data:
159 logging.debug('handle_pod_data_send:EOT')
160 break
161 self.connsrv.streamsend(data)
162 if self.debug == '3':
163 logging.debug('handle_pod_data_send:D{}'.format(len(data)))
164
165 def prepare_pod_yaml(self, namespace, pvcdata, mode='backup'):
166 logging.debug('pvcdata: {}'.format(pvcdata))
167 if self.pluginhost is None:
168 self._handle_error(PLUGINHOST_NONE_ERR)
169 self._prepare_err = True
170 return None
171 pport = self.pluginport
172 try:
173 self.pluginport = int(self.pluginport)
174 except ValueError:
175 self.pluginport = 9104
176 logging.warning(PLUGINPORT_VALUE_ERR.format(port=pport))
177 self._io.send_warning(PLUGINPORT_VALUE_ERR.format(port=pport))
178 pvcname = pvcdata.get('name')
179 node_name = pvcdata.get('node_name')
180
181 podyaml = prepare_backup_pod_yaml(mode=mode, nodename=node_name, host=self.pluginhost, port=self.pluginport,
182 token=self.token, namespace=namespace, pvcname=pvcname, image=self.backupimage,
183 imagepullpolicy=self.imagepullpolicy, imagepullsecret=self.imagepullsecret, job=self.jobname)
184 if node_name is None:
185 self._io.send_info(POD_YAML_PREPARED_INFO.format(
186 image=self.backupimage,
187 pullpolicy=self.imagepullpolicy,
188 pluginhost=self.pluginhost,
189 pluginport=self.pluginport
190 ))
191 else:
192 self._io.send_info(POD_YAML_PREPARED_INFO_NODE.format(
193 nodename=node_name,
194 image=self.backupimage,
195 pullpolicy=self.imagepullpolicy,
196 pluginhost=self.pluginhost,
197 pluginport=self.pluginport
198 ))
199 return podyaml
200
201 def prepare_clone_yaml(self, namespace, pvcname, capacity, storage_class):
202 logging.debug('prepare_clone_yaml: {} {} {} {}'.format(namespace, pvcname, capacity, storage_class))
203 if namespace is None or pvcname is None or capacity is None or storage_class is None:
204 logging.error("Invalid params to pvc clone!")
205 return None, None
206 pvcyaml, snapname = prepare_backup_clone_yaml(namespace, pvcname, capacity, storage_class, self.jobname)
207 self._io.send_info(PVCCLONE_YAML_PREPARED_INFO.format(
208 namespace=namespace,
209 snapname=snapname,
210 storage=storage_class,
211 capacity=capacity
212 ))
213 return pvcyaml, snapname
214
215 def prepare_connection_server(self):
216 if self.connsrv is None:
217 if self.fdaddr is None:
218 self.fdaddr = '0.0.0.0'
219 fport = self.fdport
220 try:
221 self.fdport = int(self.fdport)
222 except ValueError:
223 self.fdport = 9104
224 logging.warning(FDPORT_VALUE_ERR.format(port=fport))
225 self._handle_error(FDPORT_VALUE_ERR.format(port=fport))
226 logging.debug("prepare_connection_server:New ConnectionServer: {}:{}".format(
227 str(self.fdaddr),
228 str(self.fdport)))
229 self.connsrv = ConnectionServer(self.fdaddr, self.fdport,
230 token=self.token,
231 certfile=self.certfile,
232 keyfile=self.keyfile,
233 timeout=self.timeout)
234 response = self.connsrv.listen()
235 logging.debug("response:{}".format(response))
236 if isinstance(response, dict) and 'error' in response:
237 self._handle_error(CANNOT_START_CONNECTIONSERVER.format(parse_json_descr(response)))
238 return False
239 else:
240 logging.debug("prepare_connection_server:Reusing ConnectionServer!")
241 self.connsrv.token = self.token
242 return True
243
244 def execute_pod(self, namespace, podyaml):
245 prev_bacula_pod_name = self._plugin.check_bacula_pod(namespace, self.jobname)
246 if prev_bacula_pod_name:
247 logging.debug('Exist previous bacula-backup pod! Name: {}'.format(prev_bacula_pod_name))
248 self._io.send_info('Exist a previous bacula-backup pod: {}'.format(prev_bacula_pod_name))
249 response = self._plugin.remove_backup_pod(namespace, prev_bacula_pod_name)
250 if isinstance(response, dict) and 'error' in response:
251 self._handle_error(CANNOT_REMOVE_BACKUP_POD_ERR.format(parse_json_descr(response)))
252 return False
253 self._io.send_info('Removed previous bacula-backup pod: {}'.format(prev_bacula_pod_name))
254 poddata = yaml.safe_load(podyaml)
255 response = self._plugin.create_backup_pod(namespace, poddata)
256 if isinstance(response, dict) and 'error' in response:
257 self._handle_error(CANNOT_CREATE_BACKUP_POD_ERR.format(parse_json_descr(response)))
258 else:
259 for seq in range(self.timeout):
260 time.sleep(1)
261 isready = self._plugin.backup_pod_isready(namespace, podname=get_backup_pod_name(self.jobname), seq=seq)
262 if isinstance(isready, dict) and 'error' in isready:
263 self._handle_error(CANNOT_CREATE_BACKUP_POD_ERR.format(parse_json_descr(isready)))
264 break
265 elif isready:
266 return True
267 return False
268
269 def execute_pvcclone(self, namespace, clonename, cloneyaml):
270 pass
271
272 def delete_pod(self, namespace, force=False):
273 for a in range(self.timeout):
274 time.sleep(1)
275 response = self._plugin.check_gone_backup_pod(namespace, get_backup_pod_name(self.jobname), force=force)
276 if isinstance(response, dict) and 'error' in response:
277 self._handle_error(CANNOT_REMOVE_BACKUP_POD_ERR.format(parse_json_descr(response)))
278 else:
279 logging.debug('delete_pod:isgone:{}'.format(response))
280 if response:
281 return True
282 return False
283
284 def delete_pvcclone(self, namespace, clonename, force=False):
285 for a in range(self.timeout):
286 time.sleep(1)
287 response = self._plugin.check_gone_pvcclone(namespace, clonename, force=force)
288 if isinstance(response, dict) and 'error' in response:
289 self._handle_error(CANNOT_REMOVE_PVC_CLONE_ERR.format(parse_json_descr(response)))
290 else:
291 logging.debug('delete_pvcclone:isgone:{}'.format(response))
292 if response:
293 return True
294 return False
295
296 def handle_delete_pod(self, namespace):
297 if not self.delete_pod(namespace=namespace):
298 self._handle_error(POD_REMOVE_ERR.format(podname=get_backup_pod_name(self.jobname)))
299
300 def handle_tarstderr(self):
301 if self.tarexitcode != '0' or len(self.tarstderr) > 0:
302 # format or prepare error message
303 if not len(self.tarstderr):
304 self.tarstderr = TAR_STDERR_UNKNOWN
305 else:
306 self.tarstderr = self.tarstderr.rstrip('\n')
307 # classify it as error or warning
308 if self.tarexitcode != '0':
309 self._handle_non_fatal_error(self.tarstderr)
310 else:
311 self._io.send_warning(self.tarstderr)
312
313 def prepare_bacula_pod(self, pvcdata, namespace=None, mode='backup'):
314 if self._prepare_err:
315 # first prepare yaml was unsuccessful, we can't recover from this error
316 return False
317 self.token = generate_token()
318 if namespace is None:
319 namespace = pvcdata.get('fi').namespace
320 logging.debug('prepare_bacula_pod:token={} namespace={}'.format(self.token, namespace))
321 podyaml = self.prepare_pod_yaml(namespace, pvcdata, mode=mode)
322 if podyaml is None:
323 # error preparing yaml
324 self._prepare_err = True
325 return False
326 if not self.prepare_connection_server():
327 self._prepare_err = True
328 return False
329 logging.debug('prepare_bacula_pod:start pod')
330 if not self.execute_pod(namespace, podyaml):
331 self._handle_error(POD_EXECUTION_ERR)
332 return False
333 return True
334
335 def cleanup_old_cloned_pvc(self, namespace):
336 logging.debug("Starting cleanup the old pvc from other previous job")
337 # List all pvc names from namespace
338 pvc_names = self._plugin.get_pvc_names(namespace)
339 # Search old cloned pvcs
340 old_clone_pvcs = find_bacula_pvc_clones_from_old_job(pvc_names, self.jobname)
341 # Remove old pvcs
342 for old_clone_pvc in old_clone_pvcs:
343 self._io.send_info(f"Exist a previous bacula-backup pvc. Name: {old_clone_pvc}")
344 response = self._plugin.delete_persistent_volume_claim(namespace, old_clone_pvc)
345 logging.debug(f"Response from pvc `{old_clone_pvc}` delete request: {response}")
346 if isinstance(response, dict) and "error" in response:
347 return response
348 self._io.send_info(f"Removed the previous bacula-backup pvc: {old_clone_pvc}")
349 logging.debug("Deleted request launched successfully")
350 logging.debug("Ended cleanup the old pvcs from other previous job")
351
352 def create_pvcclone(self, namespace, pvcname):
353 clonename = None
354 logging.debug("pvcclone for:{}/{}".format(namespace, pvcname))
355 self.cleanup_old_cloned_pvc(namespace)
356 pvcdata = self._plugin.get_pvcdata_namespaced(namespace, pvcname)
357 if isinstance(pvcdata, dict) and 'exception' in pvcdata:
358 self._handle_error(PVCDATA_GET_ERROR.format(parse_json_descr(pvcdata)))
359 else:
360 logging.debug('PVCDATA_ORIG:{}:{}'.format(pvcname, pvcdata))
361 cloneyaml, clonename = self.prepare_clone_yaml(namespace, pvcname, pvcdata.get('capacity'), pvcdata.get('storage_class_name'))
362 if cloneyaml is None or clonename is None:
363 # error preparing yaml
364 self._prepare_err = True
365 return None
366 clonedata = yaml.safe_load(cloneyaml)
367 response = self._plugin.create_pvc_clone(namespace, clonedata)
368 if isinstance(response, dict) and 'error' in response:
369 self._handle_error(CANNOT_CREATE_PVC_CLONE_ERR.format(parse_json_descr(response)))
370 return None
371
372 return clonename
373
374 def handle_create_vsnapshot_backup(self, namespace, pvcname):
375 """
376 Manage operations to create snapshot and new pvc from this snapshot to do backup.
377 """
378 pvc = self._plugin.get_pvcdata_namespaced(namespace, pvcname)
379
380 # Check if pvc is compatible with vsnapshot
381 if not self._plugin.check_pvc_compatiblity_with_vsnapshot(namespace, pvc.get('name')):
382 logging.debug('The pvc is not compatible with vsnapshots. Name:{}'.format(pvc.get('name')))
383 return None, pvc
384 logging.debug('Origin pvcdata FileInfo:\n{}'.format(pvc.get('fi')))
385 self._io.send_info(VSNAPSHOT_BACKUP_COMPATIBLE_INFO.format(pvc.get('name')))
386 vsnapshot = self._plugin.create_vsnapshot(namespace, pvc)
387 if isinstance(vsnapshot, dict) and 'error' in vsnapshot:
388 self._handle_error(CANNOT_CREATE_VSNAPSHOT_ERR.format(parse_json_descr(vsnapshot)))
389 return None, None
390 # Create pvc from volume snapshot
391 self._io.send_info(CREATING_PVC_FROM_VSNAPSHOT.format(pvc.get('name')))
392 new_pvc = self._plugin.create_pvc_from_vsnapshot(namespace, pvc)
393 if isinstance(new_pvc, dict) and 'error' in new_pvc:
394 self._handle_error(CANNOT_CREATE_PVC_SNAPSHOT_ERR.format(parse_json_descr(new_pvc)))
395 return None, None
396 self._io.send_info(FINISHED_PVC_FROM_VSNAPSHOT.format(new_pvc.get('name'), pvc.get('name')))
397 return vsnapshot, new_pvc
398
399 def handle_delete_vsnapshot_backup(self, namespace, vsnapshot, pvcdata):
400 logging.debug('handle_delete_vsnapshot: {}/{}/{}'.format(namespace, vsnapshot, pvcdata))
401 if vsnapshot is None:
402 return None
403 pvc_name = pvcdata
404 if type(pvcdata) == dict:
405 pvc_name = pvcdata.get('name')
406 response = self._plugin.remove_pvcclone(namespace, pvc_name)
407 if isinstance(response, dict) and "error" in response:
408 return self._handle_error(CANNOT_REMOVE_PVC_CLONE_ERR.format(pvc_name))
409 response = self._plugin.remove_vsnapshot(namespace, vsnapshot.get('name'))
410 if isinstance(response, dict) and "error" in response:
411 return self._handle_error(CANNOT_REMOVE_VSNAPSHOT_ERR.format(vsnapshot=vsnapshot.get('name')))
412 return True