12 from account import Account
14 import plnode.bwlimit as bwlimit
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',
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',
38 class Sliver_Libvirt(Account):
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()
48 return connections.setdefault(uri, libvirt.open(uri))
50 def __init__(self, rec):
51 self.name = rec['name']
52 logger.verbose ('sliver_libvirt: %s init'%(self.name))
54 # Assume the directory with the image and config files
59 self.slice_id = rec['slice_id']
61 self.conn = Sliver_Libvirt.getConnection(rec['type'])
62 self.xid = bwlimit.get_xid(self.name)
66 dom = self.conn.lookupByName(self.name)
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)
75 def dom_details (dom):
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))
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)
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]"
92 ''' Helper method to get a "nice" output of the domain struct for debug purposes'''
93 output="Domain %s"%self.name
96 output += " [no attached dom ?!?]"
98 output += Sliver_Libvirt.dom_details (dom)
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]
107 command = ["ip", "link", "delete", veth]
108 logger.log_call(command)
110 logger.log("trying to redefine the VM")
111 command = ["virsh", "define", "/etc/libvirt/lxc/%s.xml" % self.name]
112 logger.log_call(command)
114 def start(self, delay=0):
115 ''' Just start the sliver '''
116 logger.verbose('sliver_libvirt: %s start'%(self.name))
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():
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)
129 logger.log("trying dom.create again")
134 logger.verbose('sliver_libvirt: sliver %s already started'%(self.name))
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))
143 logger.verbose('sliver_libvirt: %s stop'%(self.name))
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))
152 logger.log_exc("in sliver_libvirt.stop",name=self.name)
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))
161 def configure(self, rec):
163 #sliver.[LXC/QEMU] tolower case
164 #sliver_type = rec['type'].split('.')[1].lower()
166 #BASE_DIR = '/cgroup/libvirt/%s/%s/'%(sliver_type, self.name)
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
174 # Btrfs support quota per volumes
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)
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']
191 # limit to certain number
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")
203 # Only cpu_shares until figure out how to provide limits and guarantees
205 if tags.has_key('cpu_share'):
206 cpu_share = tags['cpu_share']
207 cgroups.write(self.name, 'cpu.shares', cpu_share)
209 # Call the upper configure method (ssh keys...)
210 Account.configure(self, rec)
213 def get_unique_vif():
214 return 'veth%s' % random.getrandbits(32)
216 # A placeholder until we get true VirtualInterface objects
218 def get_interfaces_xml(rec):
220 <interface type='network'>
221 <source network='default'/>
224 """ % (Sliver_Libvirt.get_unique_vif())
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]
233 for interface in interfaces:
234 if 'vlan' in interface:
235 vlanxml = "<vlan><tag id='%s'/></vlan>" % interface['vlan']
238 if 'bridge' in interface:
239 tag_xml = tag_xml + """
240 <interface type='bridge'>
241 <source bridge='%s'/>
243 <virtualport type='openvswitch'/>
246 """ % (interface['bridge'], vlanxml, Sliver_Libvirt.get_unique_vif())
248 tag_xml = tag_xml + """
249 <interface type='network'>
250 <source network='default'/>
253 """ % (Sliver_Libvirt.get_unique_vif())
256 logger.log('sliver_libvirty.py: interface XML is: %s' % xml)
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'])