====
[plcapi.git] / PLC / PCUs.py
index bcf9255..d628677 100644 (file)
 # Mark Huang <mlhuang@cs.princeton.edu>
 # Copyright (C) 2006 The Trustees of Princeton University
 #
-# $Id$
-#
 
 from PLC.Faults import *
 from PLC.Parameter import Parameter
+from PLC.Filter import Filter
 from PLC.Debug import profile
 from PLC.Table import Row, Table
+from PLC.Interfaces import valid_ip, Interface, Interfaces
+from PLC.Nodes import Node, Nodes
 
 class PCU(Row):
     """
-    Representation of a row in the pcu table. To use,
+    Representation of a row in the pcus table. To use,
     instantiate with a dict of values.
     """
 
+    table_name = 'pcus'
+    primary_key = 'pcu_id'
+    join_tables = ['pcu_node']
     fields = {
-        'pcu_id': Parameter(int, "Node group identifier"),
-        'hostname': Parameter(str, "Fully qualified hostname"),
-        }
-
-    # These fields are derived from join tables and are not
-    # actually in the pcu table.
-    join_fields = {
+        'pcu_id': Parameter(int, "PCU identifier"),
+        'site_id': Parameter(int, "Identifier of site where PCU is located"),
+        'hostname': Parameter(str, "PCU hostname", max = 254),
+        'ip': Parameter(str, "PCU IP address", max = 254),
+        'protocol': Parameter(str, "PCU protocol, e.g. ssh, https, telnet", max = 16, nullok = True),
+        'username': Parameter(str, "PCU username", max = 254, nullok = True),
+        'password': Parameter(str, "PCU username", max = 254, nullok = True),
+        'notes': Parameter(str, "Miscellaneous notes", max = 254, nullok = True),
+        'model': Parameter(str, "PCU model string", max = 32, nullok = True),
         'node_ids': Parameter([int], "List of nodes that this PCU controls"),
+        'ports': Parameter([int], "List of the port numbers that each node is connected to"),
+        'last_updated': Parameter(int, "Date and time when node entry was created", ro = True),
         }
 
-    def __init__(self, api, fields):
-        Row.__init__(self, fields)
-        self.api = api
+    def validate_ip(self, ip):
+        if not valid_ip(ip):
+            raise PLCInvalidArgument, "Invalid IP address " + ip
+        return ip
 
-    def flush(self, commit = True):
+    validate_last_updated = Row.validate_timestamp
+
+    def update_timestamp(self, col_name, commit = True):
         """
-        Commit changes back to the database.
+        Update col_name field with current time
         """
 
-        self.validate()
-
-        # Fetch a new pcu_id if necessary
-        if 'pcu_id' not in self:
-            rows = self.api.db.selectall("SELECT NEXTVAL('pcu_pcu_id_seq') AS pcu_id")
-            if not rows:
-                raise PLCDBError, "Unable to fetch new pcu_id"
-            self['pcu_id'] = rows[0]['pcu_id']
-            insert = True
-        else:
-            insert = False
-
-        # Filter out unknown fields
-        fields = dict(filter(lambda (key, value): key in self.fields,
-                             self.items()))
-
-        # Parameterize for safety
-        keys = fields.keys()
-        values = [self.api.db.param(key, value) for (key, value) in fields.items()]
-
-        if insert:
-            # Insert new row in pcu table
-            sql = "INSERT INTO pcu (%s) VALUES (%s)" % \
-                  (", ".join(keys), ", ".join(values))
-        else:
-            # Update existing row in sites table
-            columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
-            sql = "UPDATE pcu SET " + \
-                  ", ".join(columns) + \
-                  " WHERE pcu_id = %(pcu_id)d"
-
-        self.api.db.do(sql, fields)
-
-        if commit:
-            self.api.db.commit()
-
-    def delete(self, commit = True):
+        assert 'pcu_id' in self
+        assert self.table_name
+
+        self.api.db.do("UPDATE %s SET %s = CURRENT_TIMESTAMP " % (self.table_name, col_name) + \
+                       " where pcu_id = %d" % (self['pcu_id']) )
+        self.sync(commit)
+
+    def update_last_updated(self, commit = True):
+        self.update_timestamp('last_updated', commit)
+
+    def add_node(self, node, port, commit = True):
         """
-        Delete existing PCU.
+        Add node to existing PCU.
         """
 
         assert 'pcu_id' in self
+        assert isinstance(node, Node)
+        assert isinstance(port, (int, long))
+        assert 'node_id' in node
+
+        pcu_id = self['pcu_id']
+        node_id = node['node_id']
 
-        # Delete ourself
-        for table in ['pcu_ports', 'pcu']:
-            self.api.db.do("DELETE FROM %s" \
-                           " WHERE nodenetwork_id = %(pcu_id)" % \
-                           table, self)
+        if node_id not in self['node_ids'] and port not in self['ports']:
+            self.api.db.do("INSERT INTO pcu_node (pcu_id, node_id, port)" \
+                           " VALUES(%(pcu_id)d, %(node_id)d, %(port)d)",
+                           locals())
 
-        if commit:
-            self.api.db.commit()
+            if commit:
+                self.api.db.commit()
+
+            self['node_ids'].append(node_id)
+            self['ports'].append(port)
+
+    def remove_node(self, node, commit = True):
+        """
+        Remove node from existing PCU.
+        """
+
+        assert 'pcu_id' in self
+        assert isinstance(node, Node)
+        assert 'node_id' in node
+
+        pcu_id = self['pcu_id']
+        node_id = node['node_id']
+
+        if node_id in self['node_ids']:
+            i = self['node_ids'].index(node_id)
+            port = self['ports'][i]
+
+            self.api.db.do("DELETE FROM pcu_node" \
+                           " WHERE pcu_id = %(pcu_id)d" \
+                           " AND node_id = %(node_id)d",
+                           locals())
+
+            if commit:
+                self.api.db.commit()
+
+            self['node_ids'].remove(node_id)
+            self['ports'].remove(port)
 
 class PCUs(Table):
     """
-    Representation of row(s) from the pcu table in the
+    Representation of row(s) from the pcus table in the
     database.
     """
 
-    def __init__(self, api, pcu_id_or_hostname_list = None):
-        self.api = api
-
-        # N.B.: Node IDs returned may be deleted.
-        sql = "SELECT pcu.*, pcu_ports.node_id" \
-              " FROM pcu" \
-              " LEFT JOIN pcu_ports USING (pcu_id)"
-
-        if pcu_id_or_hostname_list:
-            # Separate the list into integers and strings
-            pcu_ids = filter(lambda pcu_id: isinstance(pcu_id, (int, long)),
-                                   pcu_id_or_hostname_list)
-            hostnames = filter(lambda hostname: isinstance(hostname, StringTypes),
-                           pcu_id_or_hostname_list)
-            sql += " AND (False"
-            if pcu_ids:
-                sql += " OR pcu_id IN (%s)" % ", ".join(map(str, pcu_ids))
-            if hostnames:
-                sql += " OR hostname IN (%s)" % ", ".join(api.db.quote(hostnames)).lower()
-            sql += ")"
-
-        rows = self.api.db.selectall(sql, locals())
-        for row in rows:
-            if self.has_key(row['pcu_id']):
-                pcu = self[row['pcu_id']]
-                pcu.update(row)
+    def __init__(self, api, pcu_filter = None, columns = None):
+        Table.__init__(self, api, PCU, columns)
+
+        sql = "SELECT %s FROM view_pcus WHERE True" % \
+              ", ".join(self.columns)
+
+        if pcu_filter is not None:
+            if isinstance(pcu_filter, (list, tuple, set, int, long)):
+                pcu_filter = Filter(PCU.fields, {'pcu_id': pcu_filter})
+            elif isinstance(pcu_filter, dict):
+                pcu_filter = Filter(PCU.fields, pcu_filter)
             else:
-                self[row['pcu_id']] = PCU(api, row)
+                raise PLCInvalidArgument, "Wrong pcu filter %r"%pcu_filter
+            sql += " AND (%s) %s" % pcu_filter.sql(api)
+
+        self.selectall(sql)