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