-
Notifications
You must be signed in to change notification settings - Fork 0
/
velero-watchdog.py
executable file
·239 lines (179 loc) · 6.65 KB
/
velero-watchdog.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#!/usr/bin/env python3
"""
A script to fetch failed Velero backups and triggers the backups manually
"""
import argparse
import re
import subprocess
import sys
from datetime import datetime, timedelta, timezone
from itertools import chain
from typing import Dict, List
from kubernetes import client, config
from loguru import logger
PHASES = ["PartiallyFailed", "Failed"]
class KubernetesAPI:
"""Kubernetes Client"""
def __init__(self):
logger.info("Access Kubernetes API")
try:
config.load_incluster_config()
except config.config_exception.ConfigException:
config.load_kube_config()
self.v1 = client.CustomObjectsApi()
def get_velero_backups(self) -> list:
"""Gets velero backup K8s spec
:return: list of velero backup k8s specs
:rtype: list
"""
logger.debug("Fetch velero backups K8s specs")
return self.v1.list_namespaced_custom_object(
group="velero.io", version="v1", namespace="velero", plural="backups"
)["items"]
def delete_velero_backups(self, backup_name):
"""Delete velero backup K8s specs
:parm backup_name: backups list to be deleted
:type backup_name: list
"""
logger.debug(f"Delete velero backup K8s spec '{backup_name}'")
self.v1.delete_namespaced_custom_object(
group="velero.io",
version="v1",
namespace="velero",
plural="backups",
name=backup_name,
)
def execute(cmd) -> str:
"""Executes shell command and returns output
:parm cmd: shell command
:type cmd: str
:return: shell command output
:rtype: str
"""
logger.debug(f"Executing {cmd}")
process = subprocess.run(
cmd.split(), capture_output=True, text=True, check=False, encoding="utf-8"
)
return process.stdout
def find_failed_backup_schedules(backups_specs, window_hours) -> dict:
"""Identifies failed backups (with associated schedules) from a list of backup
specs within a given time window.
1. Filters backups whose backup phases are ["PartiallyFailed", "Failed"].
2. Checks whether there are any failed backups within the given time window.
3. Checks the "ownerReferences" of the backups with "kind" == "Schedule".
4. Stores the "Schedule" as the key with its associated failed backups as the value."
:param backups_spec: List of velero backups specs
:type backups_spec: list
:param window_hours: Time window to look failed backups
:type window_hours: int
:return: Dictionary of schedules with thier failed backups
:rtype: dict
"""
recent_failures: Dict[str, List[str]] = {}
current_time_utc = datetime.now(timezone.utc)
for backup in backups_specs:
status = backup.get("status", {})
phase = status.get("phase")
start_timestamp_str = status.get("startTimestamp")
if start_timestamp_str is None:
continue
start_timestamp = datetime.fromisoformat(start_timestamp_str).replace(
tzinfo=timezone.utc
)
if phase in PHASES and current_time_utc - start_timestamp <= timedelta(
hours=window_hours
):
owner_references = backup.get("metadata", {}).get("ownerReferences", [])
for owner_ref in owner_references:
if owner_ref.get("kind") == "Schedule":
schedule_name = owner_ref.get("name")
backup_name = backup["metadata"]["name"]
failure_reason = status.get("failureReason", "N/A")
logger.info(
f"Failed backup '{backup_name}' from '{schedule_name}' schedule. "
f"Reason: {failure_reason}"
)
recent_failures.setdefault(schedule_name, []).append(backup_name)
return recent_failures
def trigger_backups_from_schedules(schedules_list) -> list:
"""Trigger backups from given schedules
:param failed_backup_schedules: List of schdules
:type failed_backup_schedules: list
:return: List of newly created backups from schedule
:rtype: list
"""
new_backups: List[str] = []
for schedule in schedules_list:
output = execute(f"velero backup create --from-schedule {schedule}")
logger.debug(output.replace("\n", ""))
new_bkp = re.findall(r"Backup request \"(.*?)\"", output)[0]
new_backups.append(new_bkp)
logger.info(f"New backup '{new_bkp}' from '{schedule}' schedule created")
return new_backups
def delete_backups(backups) -> None:
"""Delete Velero backup with velero cli
:param backups: List of backups
:type backups: list
:param k8s: Kubernetes client object
:type k8s: kubernetes.client.api.custom_objects_api.CustomObjectsApi
:return: None
"""
for backup in backups:
logger.info(f"Deleted failed backup '{backup}'")
velero_output = execute(f"velero delete backup {backup} --confirm")
logger.debug(velero_output.replace("\n", ""))
def parse_arguments():
"""Argument parser"""
parser = argparse.ArgumentParser(
description="A script to fetch failed Velero backups and triggers the backups manually",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-t",
"--time-window",
type=int,
default="24",
help="Time window(Hours) to look for failed backups in past",
)
parser.add_argument(
"-d",
"--dry-run",
action="store_true",
help="Dry run mode",
)
parser.add_argument(
"-e",
"--debug",
action="store_true",
help="Enable debug",
)
parser.add_argument(
"-o",
"--dont-delete-backups",
action="store_true",
help="Don't delete failed backups",
)
return parser.parse_args()
def main():
"""Main function"""
args = parse_arguments()
# Verbose
logger.remove()
logger.add(sys.stderr, level="DEBUG" if args.debug else "INFO")
k8s = KubernetesAPI()
backup_specs = k8s.get_velero_backups()
schedules = find_failed_backup_schedules(
backups_specs=backup_specs, window_hours=args.time_window
)
if not schedules:
logger.info(f"No failed backups in last {args.time_window} hours")
return
if args.dry_run:
return
# Trigger new backups from schedules
trigger_backups_from_schedules(schedules_list=schedules.keys())
if not args.dont_delete_backups:
# Delete failed backups
delete_backups(list(chain.from_iterable(schedules.values())))
if __name__ == "__main__":
main()