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