-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupdate_klp.py
194 lines (161 loc) · 7.06 KB
/
update_klp.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
#!/usr/bin/python
import subprocess
import argparse
#import getpass
import textwrap
#import time
import datetime
import yaml
import os
from xmlrpc.client import ServerProxy, DateTime
import logging
import shutil
from os import access, R_OK
from os.path import isfile
logfilename = "/var/log/klp_deploy.log"
mylogs = logging.getLogger(__name__)
mylogs.setLevel(logging.DEBUG)
#file handler adding here, log file should be overwritten every time as this will be sent via email
file = logging.FileHandler(logfilename, mode='w')
file.setLevel(logging.DEBUG)
fileformat = logging.Formatter("%(asctime)s:%(levelname)s:%(message)s",datefmt="%H:%M:%S")
file.setFormatter(fileformat)
#handler for sending messages to console stdout
stream = logging.StreamHandler()
streamformat = logging.Formatter("%(asctime)s:%(filename)s:%(levelname)s:%(message)s",datefmt="%H:%M:%S")
stream.setLevel(logging.DEBUG)
stream.setFormatter(streamformat)
mylogs.addHandler(file)
mylogs.addHandler(stream)
""" class Password(argparse.Action):
def __call__(self, parser, namespace, values, option_string):
if values is None:
values = getpass.getpass()
setattr(namespace, self.dest, values) """
parser = argparse.ArgumentParser()
parser = argparse.ArgumentParser(prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent('''\
This is SUSE Live Patching patch deployment tool to update existing systems with SUSE Live Patching already installed.
You need a suma_config.yaml file with login and email notification address.
If email notification will be used then you need to have mutt email client installed.
Sample suma_config.yaml:
suma_host: mysumaserver.mydomain.local
suma_user: <USERNAME>
suma_password: <PASSWORD>
notify_email: <EMAIL_ADDRESS>
Sample command:
python3 update_klp.py --config /root/suma_config.yaml --group api_group_test
python3 update_klp.py --config /root/suma_config.yaml --group api_group_test
The script helps to deploy kernel live patching patches to a group of systems and send email notifications optionally.'''))
parser.add_argument("--config", help="enter the config file name that contains login information e.g. /root/suma_config.yaml", required=False)
parser.add_argument("--group", help="Enter the group name for which systems of a group you want to install live kernel patches.", required=False)
parser.add_argument("--email", help="use this option if you want email notifcation, the log file will be sent to it. The email address is provided in the suma_config.yaml", action="store_true")
args = parser.parse_args()
def get_login(path):
if path == "":
path = os.path.join(os.environ["HOME"], "suma_config.yaml")
with open(path) as f:
login = yaml.load_all(f, Loader=yaml.FullLoader)
for a in login:
login = a
return login
def login_suma(login):
MANAGER_LOGIN = login['suma_user']
MANAGER_PASSWORD = login['suma_password']
SUMA = "http://" + login['suma_user'] + ":" + login['suma_password'] + "@" + login['suma_host'] + "/rpc/api"
with ServerProxy(SUMA) as session_client:
session_key = session_client.auth.login(MANAGER_LOGIN, MANAGER_PASSWORD)
return session_client, session_key
def suma_logout(session, key):
session.auth.logout(key)
return
def result2email():
if args.email:
assert isfile(logfilename) and access(logfilename, R_OK), \
"File {} doesn't exist or isn't readable".format(logfilename)
email_client_name = "mutt"
path_to_cmd = shutil.which(email_client_name)
if path_to_cmd is None:
mylogs.error(f"mutt email client is not installed.")
else:
mylogs.info("Sending log %s via email to %s" %(logfilename, suma_data["notify_email"]))
subject = "SUSE Manager - Live Patching patch/updates deployment logs."
cmd1 = ['cat', logfilename]
proc1 = subprocess.run(cmd1, stdout=subprocess.PIPE)
cmd2 = [email_client_name, '-s', subject, suma_data["notify_email"]]
proc2 = subprocess.run(cmd2, input=proc1.stdout)
else:
mylogs.info("Not sending email.")
return
def printdict(dict_object):
mylogs.info("Item---------------------------------------------")
for a, b in dict_object.items():
if isinstance(b, dict):
for k, v in b.items():
print("{:<20}".format(k), "{:<20}".format(v))
else:
print("{:<20}".format(a), "{:<20}".format(b))
mylogs.info("----------------------------------------------------")
def getpkg_servers_lists(mylist):
patch_synopsis = "important: Security update for the Linux Kernel (Live Patch"
temp_patch_list = []
temp_server_list = []
for i, j in mylist.items():
try:
temp_list = session.system.getRelevantErrata(key, i)
except:
mylogs.error("failed to obtain patch list from %s" %(j))
for s in temp_list:
if s['advisory_synopsis'].startswith(patch_synopsis):
mylogs.info("Patch %s will be deployed to %s"%(s['advisory_synopsis'], j))
temp_patch_list.append(s['id'])
temp_server_list.append(i)
final_pkg_list = list(set(temp_patch_list))
final_server_list = list(set(temp_server_list))
return final_pkg_list, final_server_list
def isNotBlank(myString):
if myString and myString.strip():
#myString is not None AND myString is not empty or blank
return True
#myString is None OR myString is empty or blank
return False
def schedule_klp_upgrade(groupname):
nowlater = datetime.datetime.now()
earliest_occurrence = DateTime(nowlater)
try:
result_systemlist = session.systemgroup.listSystemsMinimal(key, groupname)
except Exception as e:
mylogs.error("get systems list from group failed. %s" %(e))
result2email()
exit(1)
mylogs.info("Scheduling SUSE Live Patching patches.")
server_list = {}
patch_list = []
for a in result_systemlist:
server_list[a['id']] = a["name"]
patch_list, server_id_list = getpkg_servers_lists(server_list)
# print(patch_list, server_id_list)
if len(patch_list) and len(server_id_list) > 0:
try:
result_job = session.system.scheduleApplyErrata(key, server_id_list, patch_list, earliest_occurrence, True, True)
mylogs.info("Jobs created %s" %(result_job))
except Exception as e:
mylogs.error("scheduling job failed %s." %(e))
else:
mylogs.info("Nothing to install. Either already installed or channels not available to the systems.")
return "finished."
if args.config:
suma_data = get_login(args.config)
session, key = login_suma(suma_data)
else:
conf_file = "/root/suma_config.yaml"
suma_data = get_login(conf_file)
session, key = login_suma(suma_data)
if isNotBlank(args.group):
result = schedule_klp_upgrade(args.group)
mylogs.info(result)
else:
mylogs.info("group name is empty.")
result2email()
exit(1)
suma_logout(session, key)
result2email()