Move the remctl code into invirt.remctl
[invirt/packages/invirt-base.git] / python / invirt / remctl.py
1 """
2 Functions to perform remctls.
3 """
4
5 from invirt.common import CodeError
6 import subprocess
7
8 def kinit():
9     """Kinit with a given username and keytab"""
10     p = subprocess.Popen(['kinit', "-k", "-t", '/etc/invirt/keytab',
11                           'daemon/'+config.web.hostname],
12                          stderr=subprocess.PIPE)
13     e = p.wait()
14     if e:
15         raise CodeError("Error %s in kinit: %s" % (e, p.stderr.read()))
16
17 def checkKinit():
18     """If we lack tickets, kinit."""
19     p = subprocess.Popen(['klist', '-s'])
20     if p.wait():
21         kinit()
22
23 def remctl(*args, **kws):
24     """Perform a remctl and return the output.
25
26     kinits if necessary, and outputs errors to stderr.
27     """
28     checkKinit()
29     p = subprocess.Popen(['remctl', config.remote.hostname]
30                          + list(args),
31                          stdout=subprocess.PIPE,
32                          stderr=subprocess.PIPE)
33     v = p.wait()
34     if kws.get('err'):
35         return p.stdout.read(), p.stderr.read()
36     if v:
37         print >> sys.stderr, 'Error', v, 'on remctl', args, ':'
38         print >> sys.stderr, p.stderr.read()
39         raise CodeError('ERROR on remctl')
40     return p.stdout.read()