forked from machacekondra/python-rrmngmnt
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathpackage_manager.py
355 lines (302 loc) · 10.3 KB
/
package_manager.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
from rrmngmnt import errors
from rrmngmnt.service import Service
PIPE_GREP_COMMAND_D = ('|', 'grep', '-E')
PIPE_XARGS_COMMAND_D = ('|', 'xargs')
class PackageManager(Service):
"""
Base class which defines interface for package management.
"""
binary = None
exist_command_d = None
install_command_d = None
remove_command_d = None
update_command_d = None
@classmethod
def is_available(cls, h):
if not cls.binary:
raise NotImplementedError("Name of binary file is not available.")
rc, _, _ = h.executor().run_cmd(
[
'which', cls.binary,
]
)
return not rc
def _execute_cmd(self, cmd):
"""
Run given command on host
Args:
cmd (list): Command to run
Returns:
tuple or None: True, if command success, otherwise false
"""
self.logger.info(
"Execute command '%s' on host %s", " ".join(cmd), self.host
)
rc, out, err = self.host.executor().run_cmd(cmd)
if rc:
self.logger.error(
"Failed to execute command '%s' on host %s; out: %s; err: %s",
" ".join(cmd), self.host, out, err
)
return
return rc, out, err
def _run_command_on_host(self, cmd):
"""
Run given command on host
Args:
cmd (list): Command to run
Returns:
bool: True, if command success, otherwise false
"""
res = self._execute_cmd(cmd=cmd)
return bool(res)
def info(self, package):
"""
Get package info
Args:
package (str): Name of package.
Returns:
str or None: package info or None.
"""
if not self.exist_command_d:
raise NotImplementedError("There is no 'exist' command defined.")
cmd = list(self.exist_command_d)
cmd.append(package)
res = self._execute_cmd(cmd=cmd)
return res[1] if res else res
def exist(self, package):
"""
Check if package exist on host
Args:
package (str): Name of package
Returns:
bool: True, if package exist, otherwise false
Raises:
NotImplementedError
"""
if not self.exist_command_d:
raise NotImplementedError("There is no 'exist' command defined.")
cmd = list(self.exist_command_d)
cmd.append(package)
self.logger.info(
"Check if host %s have %s package", self.host, package
)
return self._run_command_on_host(cmd)
def list_(self):
"""
List installed packages on host
Returns:
list: Installed packages
Raises:
NotImplementedError, CommandExecutionFailure
"""
if not self.list_command_d:
raise NotImplementedError(
"There is no 'list_' command defined."
)
cmd = self.list_command_d
self.logger.debug(
"Getting all instaled packages from host %s", self.host
)
rc, out, err = self.host.executor().run_cmd(cmd)
if not rc:
return out.split('\n')
self.logger.error(
"Failed to get installed packages on host %s, rc: %s, err: %s",
self.host, rc, err
)
raise errors.CommandExecutionFailure(
cmd=cmd, executor=self.host.executor, rc=rc, err=err
)
def install(self, package):
"""
Install package on host
Args:
package (str): Name of package
Returns:
bool: True, if package installation success, otherwise false
Raises:
NotImplementedError
"""
if not self.install_command_d:
raise NotImplementedError("There is no 'install' command defined.")
cmd = list(self.install_command_d)
cmd.append(package)
if not self.exist(package):
self.logger.info(
"Install package %s on host %s", package, self.host
)
return self._run_command_on_host(cmd)
self.logger.info(
"Package %s already exist on host %s", package, self.host
)
return True
def remove(self, package, pattern=False):
"""
Remove package from host, or packages which match pattern if pattern
is set to True
Args:
pattern (bool): If true package name is pattern
package (str): Name of package or extended regular expression
pattern take a look at -e option in man grep
Returns:
bool: True, if package(s) removal success, otherwise false
Raises:
NotImplementedError
"""
if not self.remove_command_d:
raise NotImplementedError("There is no 'remove' command defined.")
if pattern and not self.list_command_d:
raise NotImplementedError(
"list_ is not implemented!"
)
cmd = list(self.remove_command_d)
package_exists = False
if pattern:
self.logger.info(
"Erase packages which match pattern %s on host %s", package,
self.host
)
grep_xargs_command = (
list(PIPE_GREP_COMMAND_D) + ['\'%s\'' % package] +
list(PIPE_XARGS_COMMAND_D)
)
remove_pattern_command = (
list(self.list_command_d) + grep_xargs_command + cmd
)
if not self._run_command_on_host(remove_pattern_command):
return False
return True
package_exists = self.exist(package)
if not package_exists:
self.logger.info(
"Package %s does not exist on host %s", package, self.host
)
return True
self.logger.info(
"Erase package %s on host %s", package, self.host
)
cmd.append(package)
return self._run_command_on_host(cmd)
def update(self, packages=None):
"""
Updated specified packages, or all available system updates
if no packages are specified
__author__ = "omachace"
Args:
packages (list): Packages to be updated, if empty, update system
Returns:
bool: True when updates succeed, false otherwise
Raises:
NotImplementedError
"""
if not self.update_command_d:
raise NotImplementedError("There is no 'update' command defined.")
cmd = list(self.update_command_d)
if packages:
cmd.extend(packages)
self.logger.info(
"Update packages %s on host %s", packages, self.host
)
else:
self.logger.info("Updating system on host %s", self.host)
return self._run_command_on_host(cmd)
class YumPackageManager(PackageManager):
"""
YUM package manager class
"""
binary = 'yum'
exist_command_d = (binary, '-q', 'list', 'installed')
list_command_d = exist_command_d + (
'|', 'cut', '-d', ' ', '-f', '1', '|', 'sed', '\'/^$/d\'', '|', 'tail',
'-n', '+2'
)
install_command_d = (binary, 'install', '-y')
remove_command_d = (binary, 'remove', '-y')
update_command_d = (binary, 'update', '-y')
class DnfPackageManager(PackageManager):
"""
DNF package manager class
"""
binary = 'dnf'
exist_command_d = (binary, '-q', 'list', 'installed')
list_command_d = exist_command_d + (
'|', 'cut', '-d', ' ', '-f', '1', '|', 'sed', '\'/^$/d\'', '|', 'tail',
'-n', '+2'
)
list_command_d = exist_command_d
install_command_d = (binary, 'install', '-y')
remove_command_d = (binary, 'remove', '-y')
update_command_d = (binary, 'update', '-y')
class RPMPackageManager(PackageManager):
"""
RPM package manager class
"""
binary = 'rpm'
exist_command_d = (binary, '-q')
list_command_d = (binary, '-qa')
install_command_d = (binary, '-i')
remove_command_d = (binary, '-e')
update_command_d = (binary, '-U')
class APTPackageManager(PackageManager):
"""
APT package manager class
"""
binary = 'apt'
binary_base = 'dpkg'
list_command_d = (
binary_base, '--get-selections', '|', 'grep', 'install', '|', 'cut',
'-f1'
)
# FIXME: Once apt will return correct return codes fix this
exist_command_d = (binary, 'list', '--installed', '|', 'grep')
install_command_d = (binary, 'install', '-y')
remove_command_d = (binary, 'remove', '-y')
update_command_d = (binary, 'update', '-y')
class PackageManagerProxy(Service):
"""
This class is helper to determine proper package manager for target system
"""
managers = {
"rpm": RPMPackageManager,
"yum": YumPackageManager,
"dnf": DnfPackageManager,
"apt": APTPackageManager,
}
order = ('dnf', 'yum', 'apt', 'rpm')
def __init__(self, h):
super(PackageManagerProxy, self).__init__(h)
self._manager = None
def __call__(self, name):
"""
This method allows you pick up specific package manager.
host.package_manager('rpm').install(...)
"""
try:
return self.managers[name](self.host)
except KeyError:
raise ValueError("Unknown package manager: %s" % name)
def __getattr__(self, name):
"""
This method let you use implicit package manager.
host.package_manager.install(...)
"""
if self._manager is None:
for name_manager in self.order:
manager = self.managers[name_manager]
if manager.is_available(self.host):
self.logger.info(
"Using %s package manager for %s",
name_manager, self.host,
)
self._manager = manager(self.host)
break
else:
self.logger.error(
"None of %s package managers is suitable for %s",
self.order, self.host,
)
raise RuntimeError(
"Can not determine package manager for %s" % self.host
)
return getattr(self._manager, name)