11 from account import Account
13 import plnode.bwlimit as bwlimit
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',
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',
37 class Sliver_Libvirt(Account):
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()
47 return connections.setdefault(uri, libvirt.open(uri))
49 def __init__(self, rec):
50 self.name = rec['name']
51 logger.verbose ('sliver_libvirt: %s init'%(self.name))
53 # Assume the directory with the image and config files
58 self.slice_id = rec['slice_id']
60 self.conn = Sliver_Libvirt.getConnection(rec['type'])
61 self.xid = bwlimit.get_xid(self.name)
65 dom = self.conn.lookupByName(self.name)
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)
74 def dom_details (dom):
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))
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)
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]"
91 ''' Helper method to get a "nice" output of the domain struct for debug purposes'''
92 output="Domain %s"%self.name
95 output += " [no attached dom ?!?]"
97 output += Sliver_Libvirt.dom_details (dom)
101 def start(self, delay=0):
102 ''' Just start the sliver '''
103 logger.verbose('sliver_libvirt: %s start'%(self.name))
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():
110 logger.verbose('sliver_libvirt: sliver %s already started'%(self.name))
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))
119 logger.verbose('sliver_libvirt: %s stop'%(self.name))
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))
128 logger.log_exc("in sliver_libvirt.stop",name=self.name)
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))
137 def configure(self, rec):
139 #sliver.[LXC/QEMU] tolower case
140 #sliver_type = rec['type'].split('.')[1].lower()
142 #BASE_DIR = '/cgroup/libvirt/%s/%s/'%(sliver_type, self.name)
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
150 # Btrfs support quota per volumes
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)
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']
167 # limit to certain number
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")
179 # Only cpu_shares until figure out how to provide limits and guarantees
181 if tags.has_key('cpu_share'):
182 cpu_share = tags['cpu_share']
183 cgroups.write(self.name, 'cpu.shares', cpu_share)
185 # Call the upper configure method (ssh keys...)
186 Account.configure(self, rec)
189 def get_unique_vif():
190 return 'veth%s' % random.getrandbits(32)
192 # A placeholder until we get true VirtualInterface objects
194 def get_interfaces_xml(rec):
196 <interface type='network'>
197 <source network='default'/>
200 """ % (Sliver_Libvirt.get_unique_vif())
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]
209 for interface in interfaces:
210 if 'vlan' in interface:
211 vlanxml = "<vlan><tag id='%s'/></vlan>" % interface['vlan']
214 if 'bridge' in interface:
215 tag_xml = tag_xml + """
216 <interface type='bridge'>
217 <source bridge='%s'/>
219 <virtualport type='openvswitch'/>
222 """ % (interface['bridge'], vlanxml, Sliver_Libvirt.get_unique_vif())
224 tag_xml = tag_xml + """
225 <interface type='network'>
226 <source network='default'/>
229 """ % (Sliver_Libvirt.get_unique_vif())
232 logger.log('sliver_libvirty.py: interface XML is: %s' % xml)
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'])