]> git.llucax.com Git - software/pymin.git/blobdiff - pymin/services/vpn/__init__.py
Use the "virual deletion" facilities from XxxSubHandler (fixes #23).
[software/pymin.git] / pymin / services / vpn / __init__.py
index 1e84361fbf5f4a6f219cec891ba2c846e33235da..f3b9f95a422f8ffea42df0c4dd64d447f7cdff96 100644 (file)
@@ -1,7 +1,11 @@
 # vim: set encoding=utf-8 et sw=4 sts=4 :
 
 import os
+import errno
+import signal
 from os import path
+import logging ; log = logging.getLogger('pymin.services.vpn')
+
 
 from pymin.seqtools import Sequence
 from pymin.dispatcher import Handler, handler, HandlerError
@@ -15,7 +19,7 @@ class Host(Sequence):
         self.ip = ip
         self.src_net = vpn_src_net
         self.pub_key = key
-        self.dele = False
+        self._delete = False
 
     def as_tuple(self):
         return(self.name, self.ip, self.src_net, self.pub_key)
@@ -27,16 +31,10 @@ class HostHandler(DictComposedSubHandler):
     _comp_subhandler_attr = 'hosts'
     _comp_subhandler_class = Host
 
-    @handler('usage: add <vpn_src> <ip> <vpn_src_net> <key>')
-    def delete(self, vpn_src, host):
-        DictComposedSubHandler.delete(self, vpn_src, host)
-        if vpn_src in parent.vpns:
-            if host in parent.vpns[vpn_src].hosts:
-                parent.vpns[vpn_src].hosts[host].dele = True
-
 
 class Vpn(Sequence):
-    def __init__(self, vpn_src, vpn_dst, vpn_src_ip, vpn_src_mask, pub_key, priv_key):
+    def __init__(self, vpn_src, vpn_dst, vpn_src_ip, vpn_src_mask,
+                    pub_key=None, priv_key=None):
         self.vpn_src = vpn_src
         self.vpn_dst = vpn_dst
         self.vpn_src_ip = vpn_src_ip
@@ -44,7 +42,7 @@ class Vpn(Sequence):
         self.pub_key = pub_key
         self.priv_key = priv_key
         self.hosts = dict()
-        self.dele = False
+        self._delete = False
 
     def as_tuple(self):
         return(self.vpn_src, self.vpn_dst, self.vpn_src_ip, self.vpn_src_mask, self.pub_key, self.priv_key)
@@ -77,84 +75,106 @@ class VpnHandler(Restorable, ConfigWriter,
     _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
 
     def __init__(self,  pickle_dir='.', config_dir='/etc/tinc'):
-        DictSubHandler.__init__(self,self)
+        log.debug(u'VpnHandler(%r, %r)', pickle_dir, config_dir)
+        DictSubHandler.__init__(self, self)
         self._config_writer_cfg_dir = config_dir
         self._persistent_dir = pickle_dir
         self._config_build_templates()
         self._restore()
         self.host = HostHandler(self)
 
-    @handler('usage : add <vpn_name> <vpn_dst> <vpn_src_ip> <vpn_src_mask>')
-    def add(self, vpn_src, vpn_dst, vpn_src_ip, vpn_src_mask):
-        if not vpn_src in self.vpns:
-            DictSubHandler.add(self,  vpn_src, vpn_dst, vpn_src_ip, vpn_src_mask, None, None)
-        elif vpn_src in self.vpns:
-            if self.vpns[vpn_src].dele :
-                self.vpns[vpn_src] = False
-
-    @handler('usage : delete <vpn_name>')
-    def delete(self, vpn_src):
-        if vpn_src in self.vpns:
-            self.vpns[vpn_src].dele = True;
-
-
     @handler('usage: start <vpn_name>')
     def start(self, vpn_src):
+        log.debug(u'VpnHandler.start(%r)', vpn_src)
         if vpn_src in self.vpns:
             call(('tincd','--net='+ vpn_src))
 
     @handler('usage: stop <vpn_name>')
     def stop(self, vpn_src):
+        log.debug(u'VpnHandler.stop(%r)', vpn_src)
         if vpn_src in self.vpns:
-            if path.exists('/var/lib/run/tincd.' + vpn_src + '.pid'):
-                pid = file('/var/lib/run/tincd.' + vpn_src + '.pid').readline()
+            pid_file = '/var/run/tinc.' + vpn_src + '.pid'
+            log.debug(u'VpnHandler.stop: getting pid from %r', pid_file)
+            if path.exists(pid_file):
+                pid = file(pid_file).readline()
+                pid = int(pid.strip())
                 try:
-                    os.kill(int(pid.strip()), SIGTERM)
+                    log.debug(u'VpnHandler.stop: killing pid %r', pid)
+                    os.kill(pid, signal.SIGTERM)
                 except OSError:
-                    pass # XXX report error?
+                    log.debug(u'VpnHandler.stop: error killing: %r', e)
+            else:
+                log.debug(u'VpnHandler.stop: pid file not found')
 
     def _write_config(self):
+        log.debug(u'VpnHandler._write_config()')
         for v in self.vpns.values():
+            log.debug(u'VpnHandler._write_config: processing %r', v)
             #chek whether it's been created or not.
-            if not v.dele:
-                if v.pub_key is None :
+            if not v._delete:
+                if v.pub_key is None:
+                    log.debug(u'VpnHandler._write_config: new VPN, generating '
+                                'key...')
                     try:
-                        print 'douugh'
+                        log.debug(u'VpnHandler._write_config: creating dir %r',
+                                    path.join(self._config_writer_cfg_dir,
+                                                v.vpn_src ,'hosts'))
                         #first create the directory for the vpn
-                        call(('mkdir','-p', path.join(self._config_writer_cfg_dir, v.vpn_src ,'hosts')))
+                        try:
+                            os.makedirs(path.join(self._config_writer_cfg_dir,
+                                                  v.vpn_src, 'hosts'))
+                        except (IOError, OSError), e:
+                            if e.errno != errno.EEXIST:
+                                raise HandlerError(u"Can't create VPN config "
+                                                   "directory '%s' (%s)'"
+                                                    % (e.filename, e.strerror))
                         #this command should generate 2 files inside the vpn
                         #dir, one rsa_key.priv and one rsa_key.pub
                         #for some reason debian does not work like this
-                        call(('tincd','-n', v.vpn_src,'-K','<','/dev/null'))
+                        # FIXME if the < /dev/null works, is magic!
+                        log.debug(u'VpnHandler._write_config: creating key...')
+                        call(('tincd', '-n', v.vpn_src, '-K', '<', '/dev/null'))
                         #open the created files and load the keys
-                        f = file(path.join(self._config_writer_cfg_dir, v.vpn_src , 'rsa_key.priv'), 'r')
-                        priv = f.read()
-                        f.close()
-                        f = file(path.join(self._config_writer_cfg_dir, v.vpn_src ,'rsa_key.pub'), 'r')
-                        pub = f.read()
-                        f.close()
+                        try:
+                            f = file(path.join(self._config_writer_cfg_dir,
+                                               v.vpn_src, 'rsa_key.pub'),
+                                     'r')
+                            pub = f.read()
+                            f.close()
+                        except (IOError, OSError), e:
+                            raise HandlerError(u"Can't read VPN key '%s' (%s)'"
+                                                % (e.filename, e.strerror))
+
                         v.pub_key = pub
                         v.priv_key = priv
                     except ExecutionError, e:
-                        print e
+                        log.debug(u'VpnHandler._write_config: error executing '
+                                    'the command: %r', e)
 
                 vars = dict(
                     vpn = v,
                 )
-                self._write_single_config('tinc.conf',path.join(v.vpn_src,'tinc.conf'),vars)
-                self._write_single_config('tinc-up',path.join(v.vpn_src,'tinc-up'),vars)
+                self._write_single_config('tinc.conf',
+                                path.join(v.vpn_src, 'tinc.conf'), vars)
+                self._write_single_config('tinc-up',
+                                path.join(v.vpn_src, 'tinc-up'), vars)
                 for h in v.hosts.values():
-                    if not h.dele:
+                    if not h._delete:
                         vars = dict(
                             host = h,
                         )
-                        self._write_single_config('host',path.join(v.vpn_src,'hosts',h.name),vars)
+                        self._write_single_config('host',
+                                path.join(v.vpn_src, 'hosts', h.name), vars)
                     else:
+                        log.debug(u'VpnHandler._write_config: removing...')
                         try:
-                            call(('rm','-f', path.join(v.vpn_src,'hosts',h.name)))
+                            # FIXME use os.unlink()
+                            call(('rm','-f',
+                                    path.join(v.vpn_src, 'hosts', h.name)))
                             del v.hosts[h.name]
                         except ExecutionError, e:
-                            print e
+                            log.debug(u'VpnHandler._write_config: error '
+                                    'removing files: %r', e)
             else:
                 #delete the vpn root at tinc dir
                 if path.exists('/etc/tinc/' + v.vpn_src):
@@ -164,7 +184,16 @@ class VpnHandler(Restorable, ConfigWriter,
 
 
 if __name__ == '__main__':
+
+    logging.basicConfig(
+        level   = logging.DEBUG,
+        format  = '%(asctime)s %(levelname)-8s %(message)s',
+        datefmt = '%H:%M:%S',
+    )
+
     v = VpnHandler()
     v.add('prueba','sarasa','192.168.0.188','255.255.255.0')
-    v.host.add('prueba', 'azazel' ,'192.168.0.77', '192.168.0.0','kjdhfkbdskljvkjblkbjeslkjbvkljbselvslberjhbvslbevlhb')
+    v.host.add('prueba', 'azazel' ,'192.168.0.77', '192.168.0.0',
+                'kjdhfkbdskljvkjblkbjeslkjbvkljbselvslberjhbvslbevlhb')
     v.commit()
+