|
46 |
import gettext |
46 |
import gettext |
47 |
import socket |
47 |
import socket |
48 |
import errno |
48 |
import errno |
49 |
import DNS |
49 |
from univention.dvs.sessionbroker import SRV_Resolver |
50 |
import random |
|
|
51 |
try: |
50 |
try: |
52 |
import cPickle as pickle |
51 |
import cPickle as pickle |
53 |
except ImportError: |
52 |
except ImportError: |
|
322 |
conn2.close() |
321 |
conn2.close() |
323 |
|
322 |
|
324 |
|
323 |
|
325 |
class SRV_Resolver: |
|
|
326 |
'''DNS SRV Record Resolver''' |
327 |
|
328 |
def __init__(self, srv_record): # query entries for given SRV record from DNS |
329 |
self.servers = [] |
330 |
DNS.ParseResolvConf() |
331 |
r = DNS.Request(name=srv_record, qtype='srv') |
332 |
for record in r.req().answers: |
333 |
prio, weight, port, target = record['data'] |
334 |
self.servers.append((prio, weight, target, port)) |
335 |
|
336 |
def __iter__(self): |
337 |
return self |
338 |
|
339 |
def next(self): |
340 |
if not self.servers: # out of stock |
341 |
raise StopIteration |
342 |
|
343 |
self.servers.sort(self._serverCmp) |
344 |
minPriority = self.servers[0][0] |
345 |
|
346 |
weightIndex = zip(xrange(len(self.servers)), [x[1] for x in self.servers if x[0] == minPriority]) |
347 |
if len(weightIndex) == 1: |
348 |
index, weight = weightIndex[0] |
349 |
prio, weight, host, port = self.servers[index] |
350 |
del self.servers[index] # drop this server from the list |
351 |
return host, port |
352 |
else: |
353 |
weightSum = reduce(lambda x, y: (None, x[1]+y[1]), weightIndex, (None, 0))[1] |
354 |
offset = random.randint(0, weightSum-1) # random variable |
355 |
for index, weight in weightIndex: |
356 |
if offset < weight: # probability according to weight |
357 |
prio, weight, host, port = self.servers[index] |
358 |
del self.servers[index] # drop this server from the list |
359 |
return host, port |
360 |
offset -= weight |
361 |
|
362 |
def _serverCmp(self, a, b): # sort by prio (and weight) |
363 |
if a[0]!=b[0]: |
364 |
return cmp(a[0], b[0]) |
365 |
else: |
366 |
return cmp(a[1], b[1]) |
367 |
|
368 |
def getavailable(self): # return first available host:port |
369 |
for host, port in self: # try in order of SRV RR priority and weight |
370 |
retcode = subprocess.call(["nc", "-z", "-w1", host, '%s' % port]) |
371 |
if retcode == 0: |
372 |
return host, port |
373 |
return (None , None) # fallback for no open host:port |
374 |
|
375 |
def connect_xrdp(response_dict, options): |
324 |
def connect_xrdp(response_dict, options): |
376 |
"""Print the ip of the desktop vm to stdout for xrdp .""" |
325 |
"""Print the ip of the desktop vm to stdout for xrdp .""" |
377 |
print "ip: %s" % response_dict['desktop_host'] |
326 |
print "ip: %s" % response_dict['desktop_host'] |