fix remaining reference to debuginfo
[nodemanager.git] / sliver_libvirt.py
1 """LibVirt slivers"""
2
3 import sys
4 import os, os.path
5 import subprocess
6 import pprint
7 import random
8
9 import libvirt
10
11 from account import Account
12 import logger
13 import plnode.bwlimit as bwlimit
14 import cgroups
15
16 STATES = {
17     libvirt.VIR_DOMAIN_NOSTATE:  'no state',
18     libvirt.VIR_DOMAIN_RUNNING:  'running',
19     libvirt.VIR_DOMAIN_BLOCKED:  'blocked on resource',
20     libvirt.VIR_DOMAIN_PAUSED:   'paused by user',
21     libvirt.VIR_DOMAIN_SHUTDOWN: 'being shut down',
22     libvirt.VIR_DOMAIN_SHUTOFF:  'shut off',
23     libvirt.VIR_DOMAIN_CRASHED:  'crashed',
24 }
25
26 REASONS = {
27     libvirt.VIR_CONNECT_CLOSE_REASON_ERROR: 'Misc I/O error',
28     libvirt.VIR_CONNECT_CLOSE_REASON_EOF: 'End-of-file from server',
29     libvirt.VIR_CONNECT_CLOSE_REASON_KEEPALIVE: 'Keepalive timer triggered',
30     libvirt.VIR_CONNECT_CLOSE_REASON_CLIENT: 'Client requested it',
31 }
32
33 connections = dict()
34
35 # Common Libvirt code
36
37 class Sliver_Libvirt(Account):
38
39     # Helper methods
40
41     @staticmethod
42     def getConnection(sliver_type):
43         # TODO: error checking
44         # vtype is of the form sliver.[LXC/QEMU] we need to lower case to lxc/qemu
45         vtype = sliver_type.split('.')[1].lower()
46         uri = vtype + '://'
47         return connections.setdefault(uri, libvirt.open(uri))
48
49     def __init__(self, rec):
50         self.name = rec['name']
51         logger.verbose ('sliver_libvirt: %s init'%(self.name))
52
53         # Assume the directory with the image and config files
54         # are in place
55
56         self.keys = ''
57         self.rspec = {}
58         self.slice_id = rec['slice_id']
59         self.enabled = True
60         self.conn = Sliver_Libvirt.getConnection(rec['type'])
61         self.xid = bwlimit.get_xid(self.name)
62
63         dom = None
64         try:
65             dom = self.conn.lookupByName(self.name)
66         except:
67             logger.log('sliver_libvirt: Domain %s does not exist. ' \
68                        'Will try to create it again.' % (self.name))
69             self.__class__.create(rec['name'], rec)
70             dom = self.conn.lookupByName(self.name)
71         self.dom = dom
72
73     @staticmethod
74     def dom_details (dom):
75         output=""
76         output += " id=%s - OSType=%s"%(dom.ID(),dom.OSType())
77         # calling state() seems to be working fine
78         (state,reason)=dom.state()
79         output += " state=%s, reason=%s"%(STATES.get(state,state),REASONS.get(reason,reason))
80         try:
81             # try to use info() - this however does not work for some reason on f20
82             # info cannot get info operation failed: Cannot read cputime for domain
83             [state, maxmem, mem, ncpu, cputime] = dom.info()
84             output += " [info: maxmem = %s, mem = %s, ncpu = %s, cputime = %s]" % (STATES.get(state, state), maxmem, mem, ncpu, cputime)
85         except:
86             # too bad but libvirt.py prints out stuff on stdout when this fails, don't know how to get rid of that..
87             output += " [info: not available]"
88         return output
89
90     def __repr__(self):
91         ''' Helper method to get a "nice" output of the domain struct for debug purposes'''
92         output="Domain %s"%self.name
93         dom=self.dom
94         if dom is None: 
95             output += " [no attached dom ?!?]"
96         else:
97             output += Sliver_Libvirt.dom_details (dom)
98         return output
99             
100
101     def start(self, delay=0):
102         ''' Just start the sliver '''
103         logger.verbose('sliver_libvirt: %s start'%(self.name))
104
105         # Check if it's running to avoid throwing an exception if the
106         # domain was already running, create actually means start
107         if not self.is_running():
108             self.dom.create()
109         else:
110             logger.verbose('sliver_libvirt: sliver %s already started'%(self.name))
111
112         # After the VM is started... we can play with the virtual interface
113         # Create the ebtables rule to mark the packets going out from the virtual
114         # interface to the actual device so the filter canmatch against the mark
115         bwlimit.ebtables("-A INPUT -i veth%d -j mark --set-mark %d" % \
116             (self.xid, self.xid))
117
118     def stop(self):
119         logger.verbose('sliver_libvirt: %s stop'%(self.name))
120
121         # Remove the ebtables rule before stopping 
122         bwlimit.ebtables("-D INPUT -i veth%d -j mark --set-mark %d" % \
123             (self.xid, self.xid))
124
125         try:
126             self.dom.destroy()
127         except:
128             logger.log_exc("in sliver_libvirt.stop",name=self.name)
129
130     def is_running(self):
131         ''' Return True if the domain is running '''
132         (state,_) = self.dom.state()
133         result = (state == libvirt.VIR_DOMAIN_RUNNING)
134         logger.verbose('sliver_libvirt.is_running: %s => %s'%(self,result))
135         return result
136
137     def configure(self, rec):
138
139         #sliver.[LXC/QEMU] tolower case
140         #sliver_type = rec['type'].split('.')[1].lower() 
141
142         #BASE_DIR = '/cgroup/libvirt/%s/%s/'%(sliver_type, self.name)
143
144         # Disk allocation
145         # No way through cgroups... figure out how to do that with user/dir quotas.
146         # There is no way to do quota per directory. Chown-ing would create
147         # problems as username namespaces are not yet implemented (and thus, host
148         # and containers share the same name ids
149
150         # Btrfs support quota per volumes
151
152         if rec.has_key("rspec") and rec["rspec"].has_key("tags"):
153             if cgroups.get_cgroup_path(self.name) == None:
154                 # If configure is called before start, then the cgroups won't exist
155                 # yet. NM will eventually re-run configure on the next iteration.
156                 # TODO: Add a post-start configure, and move this stuff there
157                 logger.log("Configure: postponing tag check on %s as cgroups are not yet populated" % self.name)
158             else:
159                 tags = rec["rspec"]["tags"]
160                 # It will depend on the FS selection
161                 if tags.has_key('disk_max'):
162                     disk_max = tags['disk_max']
163                     if disk_max == 0:
164                         # unlimited
165                         pass
166                     else:
167                         # limit to certain number
168                         pass
169
170                 # Memory allocation
171                 if tags.has_key('memlock_hard'):
172                     mem = str(int(tags['memlock_hard']) * 1024) # hard limit in bytes
173                     cgroups.write(self.name, 'memory.limit_in_bytes', mem, subsystem="memory")
174                 if tags.has_key('memlock_soft'):
175                     mem = str(int(tags['memlock_soft']) * 1024) # soft limit in bytes
176                     cgroups.write(self.name, 'memory.soft_limit_in_bytes', mem, subsystem="memory")
177
178                 # CPU allocation
179                 # Only cpu_shares until figure out how to provide limits and guarantees
180                 # (RT_SCHED?)
181                 if tags.has_key('cpu_share'):
182                     cpu_share = tags['cpu_share']
183                     cgroups.write(self.name, 'cpu.shares', cpu_share)
184
185         # Call the upper configure method (ssh keys...)
186         Account.configure(self, rec)
187
188     @staticmethod
189     def get_unique_vif():
190         return 'veth%s' % random.getrandbits(32)
191
192     # A placeholder until we get true VirtualInterface objects
193     @staticmethod
194     def get_interfaces_xml(rec):
195         xml = """
196     <interface type='network'>
197       <source network='default'/>
198       <target dev='%s'/>
199     </interface>
200 """ % (Sliver_Libvirt.get_unique_vif())
201         try:
202             tags = rec['rspec']['tags']
203             if 'interface' in tags:
204                 interfaces = eval(tags['interface'])
205                 if not isinstance(interfaces, (list, tuple)):
206                     # if interface is not a list, then make it into a singleton list
207                     interfaces = [interfaces]
208                 tag_xml = ""
209                 for interface in interfaces:
210                     if 'vlan' in interface:
211                         vlanxml = "<vlan><tag id='%s'/></vlan>" % interface['vlan']
212                     else:
213                         vlanxml = ""
214                     if 'bridge' in interface:
215                         tag_xml = tag_xml + """
216         <interface type='bridge'>
217           <source bridge='%s'/>
218           %s
219           <virtualport type='openvswitch'/>
220           <target dev='%s'/>
221         </interface>
222     """ % (interface['bridge'], vlanxml, Sliver_Libvirt.get_unique_vif())
223                     else:
224                         tag_xml = tag_xml + """
225         <interface type='network'>
226           <source network='default'/>
227           <target dev='%s'/>
228         </interface>
229     """ % (Sliver_Libvirt.get_unique_vif())
230
231                 xml = tag_xml
232                 logger.log('sliver_libvirty.py: interface XML is: %s' % xml)
233
234         except:
235             logger.log('sliver_libvirt.py: ERROR parsing "interface" tag for slice %s' % rec['name'])
236             logger.log('sliver_libvirt.py: tag value: %s' % tags['interface'])
237
238         return xml