/
pyvirsh.py
executable file
·425 lines (265 loc) · 9.05 KB
/
pyvirsh.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
#! /usr/bin/env python
# -*- coding: utf8 -*-
#
'''Module for libvirt shell.'''
import libvirt
import sys
import readline
import os
import atexit
class PyVirsh:
'''Class for libvirt shell.'''
def __init__(self):
self.conn = None
self.history_path = os.path.expanduser("~/.pyvirsh.history")
atexit.register(self.save_shell_history)
self.update_connect_completion()
self.commands = [
'list',
'shutdown',
'start',
'quit'
]
# shell completion logic
self.logic = {
'connect': {},
'exit': {},
'export': {},
'import': {},
'list': {},
'resume': {},
'shutdown': {},
'start': {},
'suspend': {},
'test': {},
'quit': {}
}
def update_domains_completion(self):
'''Update domain names in shell completion.'''
if self.conn is not None:
domains = self.list_all_domains(self.conn)
doms = {}
for dom in domains:
doms[dom[1]] = None
self.logic['start'] = doms
self.logic['shutdown'] = doms
self.logic['suspend'] = doms
self.logic['resume'] = doms
return
def update_connect_completion(self):
'''Update connect strings.'''
pass
def connect(self, conn_str):
'''Connect to server.'''
self.conn = libvirt.open(conn_str)
self.update_domains_completion()
return
def save_shell_history(self):
'''Save shell history to file.'''
readline.write_history_file(self.history_path)
return
def load_shell_history(self):
'''Load history from file.'''
if os.path.exists(self.history_path):
readline.read_history_file(self.history_path)
return
def save_connect_history(self):
'''Save connect history to file.'''
pass
def load_connect_history(self):
'''Load connect history from file.'''
pass
def export_domain(self, domain):
'''Export domain to archive.'''
#xml = self.domain_xml_desc(domain, "FLAGS")
pass
def import_domain(self):
'''Import domain from archive.'''
#conn.defineXML(XML)
pass
def domain_xml_desc(self, domain, flags):
'''Return domain XML description'''
pass
def run_shell(self):
'''Run shell.'''
run = 1
self.load_shell_history()
readline.parse_and_bind('tab: complete')
readline.set_completer(self.shell_completer2)
readline.set_completer_delims(
' \t\n`~!@#$%^&*()=+[{]}\\|;:\'",<>/?')
while run:
try:
comm = raw_input("# ")
except EOFError:
print('')
sys.exit(0)
self.simple_parse(comm)
if comm == 'quit':
run = 0
return
def list_all_domains(self, conn):
'''Find all available domains and return list.'''
domains = []
for dom_id in conn.listDomainsID():
dom = conn.lookupByID(dom_id)
domains.append((str(dom_id), dom.name(), dom.isActive()))
for dom in conn.listDefinedDomains():
domain = conn.lookupByName(dom)
domains.append(('-', dom, domain.isActive()))
return domains
@staticmethod
def print_dom_info(values):
'''Print domains info.'''
print('{0:5} {1:20} {2:8}'.format("ID", "Name", "State"))
print('-' * 40)
for line in values:
# TODO: more states
state = ''
if(line[2] == 0):
state = 'shut off'
else:
state = 'running'
print('{0:5} {1:20} {2:8}'.format(line[0], line[1], state))
return
@staticmethod
def print_comm_not_found(command):
'''Print info about bad command.'''
print('{}: command not found'.format(command))
return
def find_domain(self, string):
'''Find domain object from string and return it.'''
for dom_id in self.conn.listDomainsID():
domain = self.conn.lookupByID(dom_id)
if string == domain.name():
return domain
try:
if dom_id == int(string):
return domain
except ValueError as error:
print(error)
for dom in self.conn.listDefinedDomains():
try:
if dom == string:
domain = self.conn.lookupByName(dom)
return domain
except ValueError as error:
print(error)
return
def resolve_domain(self, string):
'''Resolve domain from string parameter and return domain object.'''
domain = None
choices = ('ID', 'name', 'UUID')
for choice in choices:
try:
if (choice == 'ID'):
domain = self.conn.lookupByID(int(string))
break
elif (choice == 'name'):
domain = self.conn.lookupByName(string)
break
elif(choice == 'UUID'):
domain = self.conn.lookupByUUID(string)
break
except libvirt.libvirtError:
# print('libvirt error')
pass
except ValueError:
# print('Value error')
pass
except TypeError:
# print('Type error')
pass
return domain
def simple_parse(self, data):
'''Simple parser for commands.'''
if(len(data) == 0):
return
commands = data.split()
if (commands[0] == 'list'):
self.print_dom_info(self.list_all_domains(self.conn))
elif (commands[0] == 'export'):
if (len(commands) == 2):
self.export_domain(self.find_domain(commands[1]))
elif (commands[0] == 'import'):
if (len(commands) == 2):
self.import_domain(commands[1])
elif (commands[0] == 'resume'):
if (len(commands) == 2):
self.resume_domain(self.find_domain(commands[1]))
elif (commands[0] == 'start'):
if (len(commands) == 2):
self.start_domain(commands[1])
elif (commands[0] == 'shutdown'):
if (len(commands) == 2):
self.shutdown_domain(commands[1])
elif (commands[0] == 'suspend'):
if (len(commands) == 2):
self.suspend_domain(self.find_domain(commands[1]))
elif (commands[0] == 'quit' or commands[0] == 'exit'):
sys.exit(0)
# testing place
elif(commands[0] == 'test'):
# print(self.resolve_domain(commands[1]))
# print(self.find_domain(commands[1]))
self.suspend_domain(self.find_domain(commands[1]))
else:
self.print_comm_not_found(commands[0])
return
def shell_completer2(self, text, state):
'''More complex method for shell completion.'''
try:
tokens = readline.get_line_buffer().split()
if not tokens or readline.get_line_buffer()[-1] == ' ':
tokens.append('')
result = self.traverse(tokens, self.logic) + [None]
return result[state]
except IOError, error:
print(error)
def shell_completer(self, text, state):
'''Method for shell completion.'''
string = [choice for choice in self.commands
if choice.startswith(text)]
if state < len(string):
return string[state]
else:
return None
def shutdown_domain(self, name):
'''Shutdown domain.'''
domain = self.conn.lookupByName(name)
domain.shutdown()
return
def start_domain(self, name):
'''Start domain.'''
domain = self.conn.lookupByName(name)
domain.create()
return
def suspend_domain(self, domain):
'''Suspend domain.'''
domain.suspend()
return
def resume_domain(self, domain):
'''Resume domain.'''
domain.resume()
return
def traverse(self, tokens, tree):
'''Auxiliary method for completion.'''
if tree is None:
return []
elif len(tokens) == 0:
return []
if len(tokens) == 1:
return [x + ' ' for x in tree if x.startswith(tokens[0])]
else:
if tokens[0] in tree.keys():
return self.traverse(tokens[1:], tree[tokens[0]])
else:
return []
return []
def main():
'''Main function.'''
vir_sh = PyVirsh()
vir_sh.connect('qemu:///system')
vir_sh.run_shell()
if __name__ == "__main__":
main()