ia64/xen-unstable

view tools/python/xen/xm/rmlabel.py @ 16273:ceb195042ca7

acm, xm: Propagate error codes.

Fix propagation of error codes to the shell in some of the security
related xm commands.

Signed-off-by: Stefan Berger <stefanb@us.ibm.com>
author Keir Fraser <keir@xensource.com>
date Tue Oct 30 09:33:49 2007 +0000 (2007-10-30)
parents 993655d24b55
children 5255eac35270
line source
1 #============================================================================
2 # This library is free software; you can redistribute it and/or
3 # modify it under the terms of version 2.1 of the GNU Lesser General Public
4 # License as published by the Free Software Foundation.
5 #
6 # This library is distributed in the hope that it will be useful,
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9 # Lesser General Public License for more details.
10 #
11 # You should have received a copy of the GNU Lesser General Public
12 # License along with this library; if not, write to the Free Software
13 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
14 #============================================================================
15 # Copyright (C) 2006 International Business Machines Corp.
16 # Author: Bryan D. Payne <bdpayne@us.ibm.com>
17 #============================================================================
19 """Remove a label from a domain configuration file or a resoruce.
20 """
21 import sys, os, re
22 from xen.util import dictio
23 import xen.util.xsm.xsm as security
24 from xen.xm.opts import OptionError
25 from xen.xm import main as xm_main
26 from xen.xm.main import server
28 def help():
29 return """
30 Example: xm rmlabel dom <configfile>
31 xm rmlabel res <resource>
32 xm rmlabel mgt <domain name>
33 xm rmlabel vif-<idx> <domain name>
35 This program removes an acm_label entry from the 'configfile'
36 for a domain, from a Xend-managed domain, from the global resource label
37 file for a resource or from the virtual network interface of a Xend-managed
38 domain. If the label does not exist for the given domain or resource, then
39 rmlabel fails."""
42 def rm_resource_label(resource):
43 """Removes a resource label from the global resource label file.
44 """
45 # Try Xen-API first if configured to use it
46 if xm_main.serverType == xm_main.SERVER_XEN_API:
47 try:
48 oldlabel = server.xenapi.XSPolicy.get_resource_label(resource)
49 if oldlabel != "":
50 server.xenapi.XSPolicy.set_resource_label(resource,"",
51 oldlabel)
52 else:
53 raise security.XSMError("Resource not labeled")
54 except Exception, e:
55 raise security.XSMError("Could not remove label "
56 "from resource: %s" % e)
57 return
59 #build canonical resource name
60 resource = security.unify_resname(resource)
62 # read in the resource file
63 fil = security.res_label_filename
64 try:
65 access_control = dictio.dict_read("resources", fil)
66 except:
67 raise security.ACMError("Resource file not found, cannot remove label!")
69 # remove the entry and update file
70 if access_control.has_key(resource):
71 del access_control[resource]
72 dictio.dict_write(access_control, "resources", fil)
73 else:
74 raise security.ACMError("Resource not labeled")
77 def rm_domain_label(configfile):
78 # open the domain config file
79 fd = None
80 fil = None
81 if configfile[0] == '/':
82 fil = configfile
83 fd = open(fil, "rb")
84 else:
85 for prefix in [".", "/etc/xen"]:
86 fil = prefix + "/" + configfile
87 if os.path.isfile(fil):
88 fd = open(fil, "rb")
89 break
90 if not fd:
91 raise OptionError("Configuration file '%s' not found." % configfile)
93 # read in the domain config file, removing label
94 ac_entry_re = re.compile("^access_control\s*=.*", re.IGNORECASE)
95 ac_exit_re = re.compile(".*'\].*")
96 file_contents = ""
97 comment = 0
98 removed = 0
99 for line in fd.readlines():
100 if ac_entry_re.match(line):
101 comment = 1
102 if comment:
103 removed = 1
104 line = "#"+line
105 if comment and ac_exit_re.match(line):
106 comment = 0
107 file_contents = file_contents + line
108 fd.close()
110 # send error message if we didn't find anything to remove
111 if not removed:
112 raise security.XSMError('Domain not labeled')
114 # write the data back out to the file
115 fd = open(fil, "wb")
116 fd.writelines(file_contents)
117 fd.close()
119 def rm_domain_label_xapi(domainname):
120 if xm_main.serverType != xm_main.SERVER_XEN_API:
121 raise OptionError('Need to be configure for using xen-api.')
122 uuids = server.xenapi.VM.get_by_name_label(domainname)
123 if len(uuids) == 0:
124 raise OptionError('A VM with that name does not exist.')
125 if len(uuids) != 1:
126 raise OptionError('Too many domains with the same name.')
127 uuid = uuids[0]
128 try:
129 old_lab = server.xenapi.VM.get_security_label(uuid)
130 server.xenapi.VM.set_security_label(uuid, "", old_lab)
131 except Exception, e:
132 raise security.XSMError('Could not remove label from domain: %s' % e)
134 def rm_vif_label(vmname, idx):
135 if xm_main.serverType != xm_main.SERVER_XEN_API:
136 raise OptionError('Need to be configure for using xen-api.')
137 vm_refs = server.xenapi.VM.get_by_name_label(vmname)
138 if len(vm_refs) == 0:
139 raise OptionError('A VM with the name %s does not exist.' %
140 vmname)
141 vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
142 if len(vif_refs) <= idx:
143 raise OptionError("Bad VIF index.")
144 vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
145 if not vif_ref:
146 raise security.XSMError("A VIF with this UUID does not exist.")
147 try:
148 old_lab = server.xenapi.VIF.get_security_label(vif_ref)
149 if old_lab != "":
150 rc = server.xenapi.VIF.set_security_label(vif_ref, "", old_lab)
151 if int(rc) != 0:
152 raise security.XSMError("Could not remove the label from"
153 " the VIF.")
154 else:
155 print "Successfully removed the label from the VIF."
156 else:
157 raise security.XSMError("VIF is not labeled.")
158 except Exception, e:
159 raise security.XSMError("Could not remove the label from the VIF: %s" %
160 str(e))
163 def main (argv):
165 if len(argv) != 3:
166 raise OptionError('Requires 2 arguments')
168 if argv[1].lower() == "dom":
169 configfile = argv[2]
170 rm_domain_label(configfile)
171 elif argv[1].lower() == "mgt":
172 domain = argv[2]
173 rm_domain_label_xapi(domain)
174 elif argv[1].lower().startswith("vif-"):
175 try:
176 idx = int(argv[1][4:])
177 if idx < 0:
178 raise
179 except:
180 raise OptionError("Bad VIF device index.")
181 vmname = argv[2]
182 rm_vif_label(vmname, idx)
183 elif argv[1].lower() == "res":
184 resource = argv[2]
185 rm_resource_label(resource)
186 else:
187 raise OptionError('Unrecognised type argument: %s' % argv[1])
189 if __name__ == '__main__':
190 try:
191 main(sys.argv)
192 except Exception, e:
193 sys.stderr.write('Error: %s\n' % str(e))
194 sys.exit(-1)