cc1  v2.1
CC1 source code docs
 All Classes Namespaces Files Functions Variables Pages
vnc.py
Go to the documentation of this file.
1 ##
2 #
3 # @author Maciej Nabozny <mn@mnabozny.pl>
4 #
5 
6 
7 import subprocess
8 import sys
9 import os
10 import pwd
11 import grp
12 
13 from cm.models.vm import VM
14 from common.states import vnc_states
15 
16 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cm.settings")
17 
18 
19 def start():
20  stop()
21  print "CM: Preparing CM to redirect vnc..."
22  dev_null = open('/dev/null', 'w')
23  subprocess.call('echo 1 > /proc/sys/net/ipv4/ip_forward', shell=True)
24 
25  # Remove old rules, if exists
26  subprocess.call('/sbin/iptables -t nat -D POSTROUTING -j CC1_VNC_MASQUERADE', shell=True, stdout=dev_null, stderr=dev_null)
27  subprocess.call('/sbin/iptables -t nat -D PREROUTING -j CC1_VNC_REDIRECT', shell=True, stdout=dev_null, stderr=dev_null)
28 
29  # Add new rules
30  subprocess.call('/sbin/iptables -t nat -N CC1_VNC_MASQUERADE', shell=True)
31  subprocess.call('/sbin/iptables -t nat -N CC1_VNC_REDIRECT', shell=True)
32 
33  subprocess.call('/sbin/iptables -t nat -A POSTROUTING -j CC1_VNC_MASQUERADE', shell=True)
34  subprocess.call('/sbin/iptables -t nat -A PREROUTING -j CC1_VNC_REDIRECT', shell=True)
35 
36  dev_null.close()
37 
38  print "CM: Reattaching all vnc redirections..."
39  uid_cc1 = pwd.getpwnam('cc1').pw_uid
40  gid_cc1 = grp.getgrnam('cc1').gr_gid
41  gid_kvm = grp.getgrnam('kvm').gr_gid
42  gid_libvirt = grp.getgrnam('libvirt').gr_gid
43 
44  if os.getuid() == 0:
45  os.environ['HOME'] = '/var/lib/cc1/'
46 
47  os.setgroups([gid_cc1, gid_kvm, gid_libvirt])
48  os.setregid(gid_cc1, gid_cc1)
49  os.setreuid(uid_cc1, uid_cc1)
50  elif os.getuid() != uid_cc1:
51  print "ERROR: Cannot change user"
52  sys.exit(1)
53 
54  for vm in VM.objects.filter(vnc_enabled=vnc_states['attached']).all():
55  try:
56  vm.attach_vnc(reattach=True)
57  vm.save()
58  print "CM: Vnc for vm %d is attached" % vm.id
59  except:
60  pass
61  #print "CM: VM %d will have no VNC: %s" % (vm.id, str(e))
62 
63 
64 def stop():
65  print "CM: Removing all vnc redirections..."
66  dev_null = open('/dev/null', 'w')
67  # Remove old rules
68  subprocess.call('/sbin/iptables -t nat -D POSTROUTING -j CC1_VNC_MASQUERADE', shell=True, stdout=dev_null, stderr=dev_null)
69  subprocess.call('/sbin/iptables -t nat -D PREROUTING -j CC1_VNC_REDIRECT', shell=True, stdout=dev_null, stderr=dev_null)
70 
71  # Clean old vnc chains
72  subprocess.call('/sbin/iptables -t nat -F CC1_VNC_MASQUERADE', shell=True, stdout=dev_null, stderr=dev_null)
73  subprocess.call('/sbin/iptables -t nat -F CC1_VNC_REDIRECT', shell=True, stdout=dev_null, stderr=dev_null)
74  subprocess.call('/sbin/iptables -t nat -X CC1_VNC_MASQUERADE', shell=True, stdout=dev_null, stderr=dev_null)
75  subprocess.call('/sbin/iptables -t nat -X CC1_VNC_REDIRECT', shell=True, stdout=dev_null, stderr=dev_null)
76 
77  dev_null.close()
78