patch by Thomas Dreibholz - ovs-vsctl and not ovs-ovsctl
[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     ### this is confusing, because it seems it is not used in fact
172     def stop(self):
173         logger.verbose('sliver_libvirt: {} stop'.format(self.name))
174
175         # Remove the ebtables rule before stopping 
176         bwlimit.ebtables("-D INPUT -i veth{} -j mark --set-mark {}"
177                          .format(self.xid, self.xid))
178
179         try:
180             self.dom.destroy()
181         except:
182             logger.log_exc("in sliver_libvirt.stop", name=self.name)
183
184     def is_running(self):
185         ''' Return True if the domain is running '''
186         (state, _) = self.dom.state()
187         result = (state == libvirt.VIR_DOMAIN_RUNNING)
188         logger.verbose('sliver_libvirt.is_running: {} => {}'
189                        .format(self, result))
190         return result
191
192     def configure(self, rec):
193
194         #sliver.[LXC/QEMU] tolower case
195         #sliver_type = rec['type'].split('.')[1].lower() 
196
197         #BASE_DIR = '/cgroup/libvirt/{}/{}/'.format(sliver_type, self.name)
198
199         # Disk allocation
200         # No way through cgroups... figure out how to do that with user/dir quotas.
201         # There is no way to do quota per directory. Chown-ing would create
202         # problems as username namespaces are not yet implemented (and thus, host
203         # and containers share the same name ids
204
205         # Btrfs support quota per volumes
206
207         if rec.has_key("rspec") and rec["rspec"].has_key("tags"):
208             if cgroups.get_cgroup_path(self.name) == None:
209                 # If configure is called before start, then the cgroups won't exist
210                 # yet. NM will eventually re-run configure on the next iteration.
211                 # TODO: Add a post-start configure, and move this stuff there
212                 logger.log("Configure: postponing tag check on {} as cgroups are not yet populated"
213                            .format(self.name))
214             else:
215                 tags = rec["rspec"]["tags"]
216                 # It will depend on the FS selection
217                 if tags.has_key('disk_max'):
218                     disk_max = tags['disk_max']
219                     if disk_max == 0:
220                         # unlimited
221                         pass
222                     else:
223                         # limit to certain number
224                         pass
225
226                 # Memory allocation
227                 if tags.has_key('memlock_hard'):
228                     mem = str(int(tags['memlock_hard']) * 1024) # hard limit in bytes
229                     cgroups.write(self.name, 'memory.limit_in_bytes', mem, subsystem="memory")
230                 if tags.has_key('memlock_soft'):
231                     mem = str(int(tags['memlock_soft']) * 1024) # soft limit in bytes
232                     cgroups.write(self.name, 'memory.soft_limit_in_bytes', mem, subsystem="memory")
233
234                 # CPU allocation
235                 # Only cpu_shares until figure out how to provide limits and guarantees
236                 # (RT_SCHED?)
237                 if tags.has_key('cpu_share'):
238                     cpu_share = tags['cpu_share']
239                     cgroups.write(self.name, 'cpu.shares', cpu_share)
240
241         # Call the upper configure method (ssh keys...)
242         Account.configure(self, rec)
243
244     @staticmethod
245     def get_unique_vif():
246         return 'veth{}'.format(random.getrandbits(32))
247
248     # A placeholder until we get true VirtualInterface objects
249     @staticmethod
250     def get_interfaces_xml(rec):
251         xml = """
252     <interface type='network'>
253       <source network='default'/>
254       <target dev='{}'/>
255     </interface>
256 """.format(Sliver_Libvirt.get_unique_vif())
257         try:
258             tags = rec['rspec']['tags']
259             if 'interface' in tags:
260                 interfaces = eval(tags['interface'])
261                 if not isinstance(interfaces, (list, tuple)):
262                     # if interface is not a list, then make it into a singleton list
263                     interfaces = [interfaces]
264                 tag_xml = ""
265                 for interface in interfaces:
266                     if 'vlan' in interface:
267                         vlanxml = "<vlan><tag id='{}'/></vlan>".format(interface['vlan'])
268                     else:
269                         vlanxml = ""
270                     if 'bridge' in interface:
271                         tag_xml = tag_xml + """
272         <interface type='bridge'>
273           <source bridge='{}'/>
274           {}
275           <virtualport type='openvswitch'/>
276           <target dev='{}'/>
277         </interface>
278     """.format(interface['bridge'], vlanxml, Sliver_Libvirt.get_unique_vif())
279                     else:
280                         tag_xml = tag_xml + """
281         <interface type='network'>
282           <source network='default'/>
283           <target dev='{}'/>
284         </interface>
285     """.format(Sliver_Libvirt.get_unique_vif())
286
287                 xml = tag_xml
288                 logger.log('sliver_libvirty.py: interface XML is: {}'.format(xml))
289
290         except:
291             logger.log('sliver_libvirt.py: ERROR parsing "interface" tag for slice {}'.format(rec['name']))
292             logger.log('sliver_libvirt.py: tag value: {}'.format(tags['interface']))
293
294         return xml