blind and brutal 2to3
[nodemanager.git] / sliver_libvirt.py
1 """LibVirt slivers"""
2
3 import sys
4 import os, os.path
5 import re
6 import subprocess
7 import pprint
8 import random
9
10 import libvirt
11
12 from account import Account
13 import logger
14 import plnode.bwlimit as bwlimit
15 import cgroups
16
17 STATES = {
18     libvirt.VIR_DOMAIN_NOSTATE:  'no state',
19     libvirt.VIR_DOMAIN_RUNNING:  'running',
20     libvirt.VIR_DOMAIN_BLOCKED:  'blocked on resource',
21     libvirt.VIR_DOMAIN_PAUSED:   'paused by user',
22     libvirt.VIR_DOMAIN_SHUTDOWN: 'being shut down',
23     libvirt.VIR_DOMAIN_SHUTOFF:  'shut off',
24     libvirt.VIR_DOMAIN_CRASHED:  'crashed',
25 }
26
27 # with fedora24 and (broken) libvirt-python-1.3.3-3,
28 # the following symbols are not available
29 # kashyap on IRC reported that libvirt-python-1.3.5-1.fc24.x86_64
30 # did not have the issue though
31 try:
32     REASONS = {
33         # 0
34         libvirt.VIR_CONNECT_CLOSE_REASON_ERROR: 'Misc I/O error',
35         # 1
36         libvirt.VIR_CONNECT_CLOSE_REASON_EOF: 'End-of-file from server',
37         # 2
38         libvirt.VIR_CONNECT_CLOSE_REASON_KEEPALIVE: 'Keepalive timer triggered',
39         # 3
40         libvirt.VIR_CONNECT_CLOSE_REASON_CLIENT: 'Client requested it',
41     }
42 except:
43     REASONS = {
44         # libvirt.VIR_CONNECT_CLOSE_REASON_ERROR
45         0 : 'Misc I/O error',
46         # libvirt.VIR_CONNECT_CLOSE_REASON_EOF
47         1 : 'End-of-file from server',
48         # libvirt.VIR_CONNECT_CLOSE_REASON_KEEPALIVE
49         2 : 'Keepalive timer triggered',
50         # libvirt.VIR_CONNECT_CLOSE_REASON_CLIENT
51         3 : 'Client requested it',
52     }
53     logger.log("WARNING : using hard-wired constants instead of symbolic names for CONNECT_CLOSE*")
54
55 connections = dict()
56
57 # Common Libvirt code
58
59 class Sliver_Libvirt(Account):
60
61     # Helper methods
62
63     @staticmethod
64     def getConnection(sliver_type):
65         """
66         returns a connection to the underlying libvirt service
67         a single connection is created and shared among slivers
68         this call ensures the connection is alive
69         and will reconnect if it appears to be necessary
70         """
71         # sliver_type comes from rec['type'] and is of the form sliver.{LXC,QEMU}
72         # so we need to lower case to lxc/qemu
73         vtype = sliver_type.split('.')[1].lower()
74         uri = vtype + ':///'
75         if uri not in connections:
76             # create connection
77             conn = libvirt.open(uri)
78             connections[uri] = conn
79             return conn
80         else:
81             # connection already available : check for health
82             conn = connections[uri]
83             # see if a reconnection is needed
84             try:
85                 numDomains = conn.numOfDomains()
86             except:
87                 logger.log("libvirt connection to {} looks broken - reconnecting".format(uri))
88                 conn = libvirt.open(uri)
89                 # if this fails then an expection is thrown outside of this function
90                 numDomains = conn.numOfDomains()
91             return conn
92
93     def __init__(self, rec):
94         self.name = rec['name']
95         logger.verbose ('sliver_libvirt: {} init'.format(self.name))
96
97         # Assume the directory with the image and config files
98         # are in place
99
100         self.keys = ''
101         self.rspec = {}
102         self.slice_id = rec['slice_id']
103         self.enabled = True
104         self.conn = Sliver_Libvirt.getConnection(rec['type'])
105         self.xid = bwlimit.get_xid(self.name)
106
107         dom = None
108         try:
109             dom = self.conn.lookupByName(self.name)
110         except:
111             logger.log('sliver_libvirt: Domain {} does not exist. ' \
112                        'Will try to create it again.'.format(self.name))
113             self.__class__.create(rec['name'], rec)
114             dom = self.conn.lookupByName(self.name)
115         self.dom = dom
116
117     @staticmethod
118     def dom_details (dom):
119         output = ""
120         output += " id={} - OSType={}".format(dom.ID(), dom.OSType())
121         # calling state() seems to be working fine
122         (state, reason) = dom.state()
123         output += " state={}, reason={}".format(STATES.get(state, state),
124                                                 REASONS.get(reason, reason))
125         try:
126             # try to use info() - this however does not work for some reason on f20
127             # info cannot get info operation failed: Cannot read cputime for domain
128             [state, maxmem, mem, ncpu, cputime] = dom.info()
129             output += " [info: state={}, maxmem = {}, mem = {}, ncpu = {}, cputime = {}]"\
130                       .format(STATES.get(state, state), maxmem, mem, ncpu, cputime)
131         except:
132             # too bad but libvirt.py prints out stuff on stdout when this fails, don't know how to get rid of that..
133             output += " [info: not available]"
134         return output
135
136     def __repr__(self):
137         ''' Helper method to get a "nice" output of the domain struct for debug purposes'''
138         output = "Domain {}".format(self.name)
139         dom = self.dom
140         if dom is None: 
141             output += " [no attached dom ?!?]"
142         else:
143             output += Sliver_Libvirt.dom_details (dom)
144         return output
145
146     # Thierry : I am not quite sure if /etc/libvirt/lxc/<>.xml holds a reliably up-to-date
147     # copy of the sliver XML config; I feel like issuing a virsh dumpxml first might be safer
148     def repair_veth(self):
149         # See workaround email, 2-14-2014, "libvirt 1.2.1 rollout"
150         xmlfilename = "/etc/libvirt/lxc/{}.xml".format(self.name)
151         with open(xmlfilename) as xmlfile:
152             xml = xmlfile.read()
153         veths = re.findall("<target dev='veth[0-9]*'/>", xml)
154         veths = [x[13:-3] for x in veths]
155         for veth in veths:
156             command = ["ip", "link", "delete", veth]
157             logger.log_call(command)
158
159         logger.log("trying to redefine the VM")
160         command = [ "virsh", "define", xmlfilename ]
161         logger.log_call(command)
162
163     def start(self, delay=0):
164         '''Just start the sliver'''
165         logger.verbose('sliver_libvirt: {} start'.format(self.name))
166
167         # Check if it's running to avoid throwing an exception if the
168         # domain was already running
169         if not self.is_running():
170             try:
171                 # create actually means start
172                 self.dom.create()
173             except Exception as e:
174                 # XXX smbaker: attempt to resolve slivers that are stuck in
175                 #   "failed to allocate free veth".
176                 if "ailed to allocate free veth" in str(e):
177                      logger.log("failed to allocate free veth on {}".format(self.name))
178                      self.repair_veth()
179                      logger.log("trying dom.create again")
180                      self.dom.create()
181                 else:
182                     raise
183         else:
184             logger.verbose('sliver_libvirt: sliver {} already started'.format(self.name))
185
186         # After the VM is started... we can play with the virtual interface
187         # Create the ebtables rule to mark the packets going out from the virtual
188         # interface to the actual device so the filter canmatch against the mark
189         bwlimit.ebtables("-A INPUT -i veth{} -j mark --set-mark {}"
190                          .format(self.xid, self.xid))
191
192     ### this is confusing, because it seems it is not used in fact
193     def stop(self):
194         logger.verbose('sliver_libvirt: {} stop'.format(self.name))
195
196         # Remove the ebtables rule before stopping 
197         bwlimit.ebtables("-D INPUT -i veth{} -j mark --set-mark {}"
198                          .format(self.xid, self.xid))
199
200         try:
201             self.dom.destroy()
202         except:
203             logger.log_exc("in sliver_libvirt.stop", name=self.name)
204
205     def is_running(self):
206         ''' Return True if the domain is running '''
207         (state, _) = self.dom.state()
208         result = (state == libvirt.VIR_DOMAIN_RUNNING)
209         logger.verbose('sliver_libvirt.is_running: {} => {}'
210                        .format(self, result))
211         return result
212
213     def configure(self, rec):
214
215         #sliver.[LXC/QEMU] tolower case
216         #sliver_type = rec['type'].split('.')[1].lower() 
217
218         #BASE_DIR = '/cgroup/libvirt/{}/{}/'.format(sliver_type, self.name)
219
220         # Disk allocation
221         # No way through cgroups... figure out how to do that with user/dir quotas.
222         # There is no way to do quota per directory. Chown-ing would create
223         # problems as username namespaces are not yet implemented (and thus, host
224         # and containers share the same name ids
225
226         # Btrfs support quota per volumes
227
228         if "rspec" in rec and "tags" in rec["rspec"]:
229             if cgroups.get_cgroup_path(self.name) == None:
230                 # If configure is called before start, then the cgroups won't exist
231                 # yet. NM will eventually re-run configure on the next iteration.
232                 # TODO: Add a post-start configure, and move this stuff there
233                 logger.log("Configure: postponing tag check on {} as cgroups are not yet populated"
234                            .format(self.name))
235             else:
236                 tags = rec["rspec"]["tags"]
237                 # It will depend on the FS selection
238                 if 'disk_max' in tags:
239                     disk_max = tags['disk_max']
240                     if disk_max == 0:
241                         # unlimited
242                         pass
243                     else:
244                         # limit to certain number
245                         pass
246
247                 # Memory allocation
248                 if 'memlock_hard' in tags:
249                     mem = str(int(tags['memlock_hard']) * 1024) # hard limit in bytes
250                     cgroups.write(self.name, 'memory.limit_in_bytes', mem, subsystem="memory")
251                 if 'memlock_soft' in tags:
252                     mem = str(int(tags['memlock_soft']) * 1024) # soft limit in bytes
253                     cgroups.write(self.name, 'memory.soft_limit_in_bytes', mem, subsystem="memory")
254
255                 # CPU allocation
256                 # Only cpu_shares until figure out how to provide limits and guarantees
257                 # (RT_SCHED?)
258                 if 'cpu_share' in tags:
259                     cpu_share = tags['cpu_share']
260                     cgroups.write(self.name, 'cpu.shares', cpu_share)
261
262         # Call the upper configure method (ssh keys...)
263         Account.configure(self, rec)
264
265     @staticmethod
266     def get_unique_vif():
267         return 'veth{}'.format(random.getrandbits(32))
268
269     # A placeholder until we get true VirtualInterface objects
270     @staticmethod
271     def get_interfaces_xml(rec):
272         xml = """
273     <interface type='network'>
274       <source network='default'/>
275       <target dev='{}'/>
276     </interface>
277 """.format(Sliver_Libvirt.get_unique_vif())
278         try:
279             tags = rec['rspec']['tags']
280             if 'interface' in tags:
281                 interfaces = eval(tags['interface'])
282                 if not isinstance(interfaces, (list, tuple)):
283                     # if interface is not a list, then make it into a singleton list
284                     interfaces = [interfaces]
285                 tag_xml = ""
286                 for interface in interfaces:
287                     if 'vlan' in interface:
288                         vlanxml = "<vlan><tag id='{}'/></vlan>".format(interface['vlan'])
289                     else:
290                         vlanxml = ""
291                     if 'bridge' in interface:
292                         tag_xml = tag_xml + """
293         <interface type='bridge'>
294           <source bridge='{}'/>
295           {}
296           <virtualport type='openvswitch'/>
297           <target dev='{}'/>
298         </interface>
299     """.format(interface['bridge'], vlanxml, Sliver_Libvirt.get_unique_vif())
300                     else:
301                         tag_xml = tag_xml + """
302         <interface type='network'>
303           <source network='default'/>
304           <target dev='{}'/>
305         </interface>
306     """.format(Sliver_Libvirt.get_unique_vif())
307
308                 xml = tag_xml
309                 logger.log('sliver_libvirty.py: interface XML is: {}'.format(xml))
310
311         except:
312             logger.log('sliver_libvirt.py: ERROR parsing "interface" tag for slice {}'.format(rec['name']))
313             logger.log('sliver_libvirt.py: tag value: {}'.format(tags['interface']))
314
315         return xml