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