]> git.llucax.com Git - software/pymin.git/blobdiff - pymin/services/util.py
Merge baryon.com.ar:workspace/pymin
[software/pymin.git] / pymin / services / util.py
index d1788fc76cf65f7ec9167896d5b4e836b1a682c3..91d28c3213830bd5064d5c4705bd2a449088e831 100644 (file)
@@ -11,6 +11,7 @@ except ImportError:
 
 from pymin.dispatcher import Handler, handler, HandlerError, \
                                 CommandNotFoundError
 
 from pymin.dispatcher import Handler, handler, HandlerError, \
                                 CommandNotFoundError
+from pymin.seqtools import Sequence
 
 DEBUG = False
 #DEBUG = True
 
 DEBUG = False
 #DEBUG = True
@@ -21,7 +22,7 @@ __ALL__ = ('Error', 'ReturnNot0Error', 'ExecutionError', 'ItemError',
             'Persistent', 'Restorable', 'ConfigWriter', 'ServiceHandler',
             'RestartHandler', 'ReloadHandler', 'InitdHandler', 'SubHandler',
             'DictSubHandler', 'ListSubHandler', 'ComposedSubHandler',
             'Persistent', 'Restorable', 'ConfigWriter', 'ServiceHandler',
             'RestartHandler', 'ReloadHandler', 'InitdHandler', 'SubHandler',
             'DictSubHandler', 'ListSubHandler', 'ComposedSubHandler',
-            'ListComposedSubHandler', 'DictComposedSubHandler')
+            'ListComposedSubHandler', 'DictComposedSubHandler', 'Device','Address')
 
 class Error(HandlerError):
     r"""
 
 class Error(HandlerError):
     r"""
@@ -152,21 +153,75 @@ class ContainerNotFoundError(ContainerError):
         r"Initialize the object. See class documentation for more info."
         self.message = u'Container not found: "%s"' % key
 
         r"Initialize the object. See class documentation for more info."
         self.message = u'Container not found: "%s"' % key
 
+class Address(Sequence):
+    def __init__(self, ip, netmask, broadcast=None, peer=None):
+        self.ip = ip
+        self.netmask = netmask
+        self.broadcast = broadcast
+        self.peer = peer
+    def update(self, netmask=None, broadcast=None):
+        if netmask is not None: self.netmask = netmask
+        if broadcast is not None: self.broadcast = broadcast
+    def as_tuple(self):
+        return (self.ip, self.netmask, self.broadcast, self.peer)
+
+
+class Device(Sequence):
+    def __init__(self, name, mac, ppp):
+        self.name = name
+        self.mac = mac
+        self.ppp = ppp
+        self.addrs = dict()
+        self.routes = list()
+    def as_tuple(self):
+        return (self.name, self.mac, self.addrs)
+
+
 
 def get_network_devices():
 
 def get_network_devices():
-    p = subprocess.Popen(('ip', 'link', 'list'), stdout=subprocess.PIPE,
+    p = subprocess.Popen(('ip', '-o', 'link'), stdout=subprocess.PIPE,
                                                     close_fds=True)
     string = p.stdout.read()
     p.wait()
     d = dict()
                                                     close_fds=True)
     string = p.stdout.read()
     p.wait()
     d = dict()
-    i = string.find('eth')
-    while i != -1:
-        eth = string[i:i+4]
-        m = string.find('link/ether', i+4)
-        mac = string[ m+11 : m+11+17]
-        d[eth] = mac
-        i = string.find('eth', m+11+17)
+    devices = string.splitlines()
+    for dev in devices:
+        mac = ''
+        if dev.find('link/ether') != -1:
+            i = dev.find('link/ether')
+            mac = dev[i+11 : i+11+17]
+            i = dev.find(':')
+            j = dev.find(':', i+1)
+            name = dev[i+2: j]
+            d[name] = Device(name,mac,False)
+        elif dev.find('link/ppp') != -1:
+            i = dev.find('link/ppp')
+            mac =  '00:00:00:00:00:00'
+            i = dev.find(':')
+            j = dev.find(':', i+1)
+            name = dev[i+2 : j]
+            d[name] = Device(name,mac,True)
+            #since the device is ppp, get the address and peer
+            try:
+                p = subprocess.Popen(('ip', '-o', 'addr', 'show', name), stdout=subprocess.PIPE,
+                                                        close_fds=True, stderr=subprocess.PIPE)
+                string = p.stdout.read()
+                p.wait()
+                addrs = string.splitlines()
+                inet = addrs[1].find('inet')
+                peer = addrs[1].find('peer')
+                bar = addrs[1].find('/')
+                from_addr = addrs[1][inet+5 : peer-1]
+                to_addr = addrs[1][peer+5 : bar]
+                d[name].addrs[from_addr] = Address(from_addr,24, peer=to_addr)
+            except IndexError:
+                pass
+            
     return d
     return d
+       
+def get_peers():
+    p = subprocess.Popen(('ip', '-o', 'addr'), stdout=subprocess.PIPE,
+                                                    close_fds=True)
 
 def call(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
             stderr=subprocess.PIPE, close_fds=True, universal_newlines=True,
 
 def call(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
             stderr=subprocess.PIPE, close_fds=True, universal_newlines=True,
@@ -294,9 +349,6 @@ class Restorable(Persistent):
         r"_restore() -> bool :: Restore persistent data or create a default."
         try:
             self._load()
         r"_restore() -> bool :: Restore persistent data or create a default."
         try:
             self._load()
-            # TODO tener en cuenta servicios que hay que levantar y los que no
-            if hasattr(self, 'commit'): # TODO deberia ser reload y/o algo para comandos
-                self.commit()
             return True
         except IOError:
             for (k, v) in self._restorable_defaults.items():
             return True
         except IOError:
             for (k, v) in self._restorable_defaults.items():
@@ -308,8 +360,6 @@ class Restorable(Persistent):
             self._dump()
             if hasattr(self, '_write_config'):
                 self._write_config()
             self._dump()
             if hasattr(self, '_write_config'):
                 self._write_config()
-            if hasattr(self, 'reload'):
-                self.reload()
             return False
 
 class ConfigWriter:
             return False
 
 class ConfigWriter:
@@ -437,7 +487,7 @@ class ConfigWriter:
             self._write_single_config(t)
 
 
             self._write_single_config(t)
 
 
-class ServiceHandler(Handler):
+class ServiceHandler(Handler, Restorable):
     r"""ServiceHandler([start[, stop[, restart[, reload]]]]) -> ServiceHandler.
 
     This is a helper class to inherit from to automatically handle services
     r"""ServiceHandler([start[, stop[, restart[, reload]]]]) -> ServiceHandler.
 
     This is a helper class to inherit from to automatically handle services
@@ -468,26 +518,63 @@ class ServiceHandler(Handler):
                                                     reload=reload).items():
             if action is not None:
                 setattr(self, '_service_%s' % name, action)
                                                     reload=reload).items():
             if action is not None:
                 setattr(self, '_service_%s' % name, action)
+        self._persistent_attrs = list(self._persistent_attrs)
+        self._persistent_attrs.append('_service_running')
+        if '_service_running' not in self._restorable_defaults:
+            self._restorable_defaults['_service_running'] = False
+        self._restore()
+        if self._service_running:
+            self._service_running = False
+            self.start()
 
     @handler(u'Start the service.')
     def start(self):
         r"start() -> None :: Start the service."
 
     @handler(u'Start the service.')
     def start(self):
         r"start() -> None :: Start the service."
-        call(self._service_start)
+        if not self._service_running:
+            if callable(self._service_start):
+                self._service_start()
+            else:
+                call(self._service_start)
+            self._service_running = True
+            self._dump_attr('_service_running')
 
     @handler(u'Stop the service.')
     def stop(self):
         r"stop() -> None :: Stop the service."
 
     @handler(u'Stop the service.')
     def stop(self):
         r"stop() -> None :: Stop the service."
-        call(self._service_stop)
+        if self._service_running:
+            if callable(self._service_stop):
+                self._service_stop()
+            else:
+                call(self._service_stop)
+            self._service_running = False
+            self._dump_attr('_service_running')
 
     @handler(u'Restart the service.')
     def restart(self):
         r"restart() -> None :: Restart the service."
 
     @handler(u'Restart the service.')
     def restart(self):
         r"restart() -> None :: Restart the service."
-        call(self._service_restart)
+        if callable(self._service_restart):
+            self._service_restart()
+        else:
+            call(self._service_restart)
+        self._service_running = True
+        self._dump_attr('_service_running')
 
     @handler(u'Reload the service config (without restarting, if possible).')
     def reload(self):
         r"reload() -> None :: Reload the configuration of the service."
 
     @handler(u'Reload the service config (without restarting, if possible).')
     def reload(self):
         r"reload() -> None :: Reload the configuration of the service."
-        call(self._service_reload)
+        if self._service_running:
+            if callable(self._service_reload):
+                self._service_reload()
+            else:
+                call(self._service_reload)
+
+    @handler(u'Tell if the service is running.')
+    def running(self):
+        r"reload() -> None :: Reload the configuration of the service."
+        if self._service_running:
+            return 1
+        else:
+            return 0
 
 class RestartHandler(Handler):
     r"""RestartHandler() -> RestartHandler :: Provides generic restart command.
 
 class RestartHandler(Handler):
     r"""RestartHandler() -> RestartHandler :: Provides generic restart command.
@@ -513,9 +600,11 @@ class ReloadHandler(Handler):
     @handler(u'Reload the service config (alias to restart).')
     def reload(self):
         r"reload() -> None :: Reload the configuration of the service."
     @handler(u'Reload the service config (alias to restart).')
     def reload(self):
         r"reload() -> None :: Reload the configuration of the service."
-        self.restart()
+        if hasattr(self, '_service_running') and self._service_running:
+            self.restart()
 
 
-class InitdHandler(Handler):
+class InitdHandler(ServiceHandler):
+    # TODO update docs, declarative style is depracated
     r"""InitdHandler([initd_name[, initd_dir]]) -> InitdHandler.
 
     This is a helper class to inherit from to automatically handle services
     r"""InitdHandler([initd_name[, initd_dir]]) -> InitdHandler.
 
     This is a helper class to inherit from to automatically handle services
@@ -544,26 +633,20 @@ class InitdHandler(Handler):
             self._initd_name = initd_name
         if initd_dir is not None:
             self._initd_dir = initd_dir
             self._initd_name = initd_name
         if initd_dir is not None:
             self._initd_dir = initd_dir
-
-    @handler(u'Start the service.')
-    def start(self):
-        r"start() -> None :: Start the service."
-        call((path.join(self._initd_dir, self._initd_name), 'start'))
-
-    @handler(u'Stop the service.')
-    def stop(self):
-        r"stop() -> None :: Stop the service."
-        call((path.join(self._initd_dir, self._initd_name), 'stop'))
-
-    @handler(u'Restart the service.')
-    def restart(self):
-        r"restart() -> None :: Restart the service."
-        call((path.join(self._initd_dir, self._initd_name), 'restart'))
-
-    @handler(u'Reload the service config (without restarting, if possible).')
-    def reload(self):
-        r"reload() -> None :: Reload the configuration of the service."
-        call((path.join(self._initd_dir, self._initd_name), 'reload'))
+        actions = dict()
+        for action in ('start', 'stop', 'restart', 'reload'):
+            actions[action] = (path.join(self._initd_dir, self._initd_name),
+                                action)
+        ServiceHandler.__init__(self, **actions)
+
+    def handle_timer(self):
+        p = subprocess.Popen(('pgrep', '-f', self._initd_name),
+                                stdout=subprocess.PIPE)
+        pid = p.communicate()[0]
+        if p.wait() == 0 and len(pid) > 0:
+            c._service_running = True
+        else:
+            c._service_running = False
 
 class TransactionalHandler(Handler):
     r"""Handle command transactions providing a commit and rollback commands.
 
 class TransactionalHandler(Handler):
     r"""Handle command transactions providing a commit and rollback commands.
@@ -586,9 +669,10 @@ class TransactionalHandler(Handler):
         r"commit() -> None :: Commit the changes and reload the service."
         if hasattr(self, '_dump'):
             self._dump()
         r"commit() -> None :: Commit the changes and reload the service."
         if hasattr(self, '_dump'):
             self._dump()
+        unchanged = False
         if hasattr(self, '_write_config'):
         if hasattr(self, '_write_config'):
-            self._write_config()
-        if hasattr(self, 'reload'):
+            unchanged = self._write_config()
+        if not unchanged and hasattr(self, 'reload'):
             self.reload()
 
     @handler(u'Discard all the uncommited changes.')
             self.reload()
 
     @handler(u'Discard all the uncommited changes.')
@@ -627,6 +711,8 @@ class ParametersHandler(Handler):
         if not param in self.params:
             raise ParameterNotFoundError(param)
         self.params[param] = value
         if not param in self.params:
             raise ParameterNotFoundError(param)
         self.params[param] = value
+        if hasattr(self, '_update'):
+            self._update = True
 
     @handler(u'Get a service parameter.')
     def get(self, param):
 
     @handler(u'Get a service parameter.')
     def get(self, param):
@@ -1010,6 +1096,8 @@ class DictComposedSubHandler(ComposedSubHandler):
 
 if __name__ == '__main__':
 
 
 if __name__ == '__main__':
 
+    import sys
+
     # Execution tests
     class STestHandler1(ServiceHandler):
         _service_start = ('service', 'start')
     # Execution tests
     class STestHandler1(ServiceHandler):
         _service_start = ('service', 'start')
@@ -1112,3 +1200,5 @@ if __name__ == '__main__':
     os.rmdir('templates')
     print
 
     os.rmdir('templates')
     print
 
+    print get_network_devices()
+